code stringlengths 2 1.05M |
|---|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"sn.",
"gn."
],
"DAY": [
"Axad",
"Isniin",
"Talaado",
"Arbaco",
"Khamiis",
"Jimco",
"Sabti"
],
"MONTH": [
"Bisha Koobaad",
"Bisha Labaad",
"Bisha Saddexaad",
"Bisha Afraad",
"Bisha Shanaad",
"Bisha Lixaad",
"Bisha Todobaad",
"Bisha Sideedaad",
"Bisha Sagaalaad",
"Bisha Tobnaad",
"Bisha Kow iyo Tobnaad",
"Bisha Laba iyo Tobnaad"
],
"SHORTDAY": [
"Axd",
"Isn",
"Tal",
"Arb",
"Kha",
"Jim",
"Sab"
],
"SHORTMONTH": [
"Kob",
"Lab",
"Sad",
"Afr",
"Sha",
"Lix",
"Tod",
"Sid",
"Sag",
"Tob",
"KIT",
"LIT"
],
"fullDate": "EEEE, MMMM dd, y",
"longDate": "dd MMMM y",
"medium": "dd-MMM-y h:mm:ss a",
"mediumDate": "dd-MMM-y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yy h:mm a",
"shortDate": "dd/MM/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "SOS",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"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-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "so",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
var exampleFormComponent = flight.component(exampleFormUIMixin, loaderMixin, function () {
this.defaultAttrs({
//loader
loader: "#loader",
//general message
submitMessage: "#submit-message",
//validation
usernameError: "#username-error",
passwordError: "#password-error",
errorSufix: "Error",
showErrorDelay: 2500,
//general
submitButton: "submit-button",
//for emulate errors
delay: 5000,
urlSelector: "url-selector",
successUrl: "/success.json",
errorUrl: "/error.json"
});
this.runAjax = function(url) {
var that = this;
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data, textStatus, jqXHR) {
that.trigger(
that.attr.showSubmitMessageEvent,
{success: data.success, message:data.message}
);
if (!data.success) {
that.trigger(that.attr.showDetailErrorsEvent, data.detail_errors);
}
},
error: function(jqXHR, textStatus, errorThrown) {
that.trigger(
that.attr.showSubmitMessageEvent,
{success: false, message: "Can't connect to server"}
);
}
});
}
this.validation = function(form) {
var errors = {};
if (!form.username.value) {
errors['username'] = "Username can't be blank";
}
if (!form.password.value) {
errors['password'] = "Username can't be blank";
}
if ($.isEmptyObject(errors)) {
return true;
}
this.trigger(this.attr.showDetailErrorsEvent, errors)
return false;
}
this.onSubmit = function (e, data) {
var form = e.target;
if (!this.validation(form)) {
return false;
}
var url;
if (form[this.attr.urlSelector].checked) {
url = this.attr.errorUrl;
} else {
url = this.attr.successUrl;
}
form[this.attr.submitButton].disabled = true;
this.trigger(this.attr.loaderShowEvent);
that = this;
setTimeout(
function() {
that.runAjax(url);
that.trigger(that.attr.loaderHideEvent);
form[that.attr.submitButton].disabled = false;
},
this.attr.delay
);
return false;
}
this.after("initialize", function() {
this.on("submit", this.onSubmit)
});
}); |
import * as types from '../actions/actionTypes';
//import initialState from './initialState';
// IMPORTANT: Note that with Redux, state should NEVER be changed.
// State is considered immutable. Instead,
// create a copy of the state passed and set new values on the copy.
// Note that I'm using Object.assign to create a copy of current state
// and update values on the copy.
export default function users(state = [], action) {
switch (action.type) {
case types.LOAD_USERS:
return action.users;
case "CREATE_USER":
return [
...state,
Object.assign({}, action.user)
];
case "UPDATE_USER":
if (typeof action.user.id !== "undefined") {
return [
...state.filter(user => user.id != action.user.id),
Object.assign({}, action.user)
];
} else {
return [...state];
}
case "DELETE_USER":
return [
...state.filter(user => user.id != action.userId)
];
default:
return state;
}
}
|
var boardIdentifier;
if (!DISABLE_JS) {
var volunteerCellTemplate = '<span class="userLabel"></span> ';
volunteerCellTemplate += '<input ';
volunteerCellTemplate += 'type="hidden" ';
volunteerCellTemplate += 'class="userIdentifier" ';
volunteerCellTemplate += 'name="login">';
volunteerCellTemplate += '<input ';
volunteerCellTemplate += 'type="hidden" ';
volunteerCellTemplate += 'class="boardIdentifier" ';
volunteerCellTemplate += 'name="boardUri">';
volunteerCellTemplate += '<input ';
volunteerCellTemplate += 'type="hidden" ';
volunteerCellTemplate += 'name="add" ';
volunteerCellTemplate += 'value=false>';
volunteerCellTemplate += '<input ';
volunteerCellTemplate += 'type="button" ';
volunteerCellTemplate += 'class="removeJsButton" ';
volunteerCellTemplate += 'value="Remove Volunteer" ';
volunteerCellTemplate += 'class="hidden"> ';
volunteerCellTemplate += '<input ';
volunteerCellTemplate += 'type="submit" ';
volunteerCellTemplate += 'class="removeFormButton" ';
volunteerCellTemplate += 'value="Remove Volunteer">';
if (document.getElementById('ownerControlDiv')) {
document.getElementById('addVolunteerJsButton').style.display = 'inline';
document.getElementById('transferBoardJsButton').style.display = 'inline';
document.getElementById('deleteBoardJsButton').style.display = 'inline';
document.getElementById('cssJsButton').style.display = 'inline';
document.getElementById('spoilerJsButton').style.display = 'inline';
document.getElementById('spoilerFormButton').style.display = 'none';
document.getElementById('cssFormButton').style.display = 'none';
document.getElementById('deleteBoardFormButton').style.display = 'none';
document.getElementById('addVolunteerFormButton').style.display = 'none';
document.getElementById('transferBoardFormButton').style.display = 'none';
if (document.getElementById('customJsForm')) {
document.getElementById('jsJsButton').style.display = 'inline';
document.getElementById('jsFormButton').style.display = 'none';
}
var volunteerDiv = document.getElementById('volunteersDiv');
for (var i = 0; i < volunteerDiv.childNodes.length; i++) {
processVolunteerCell(volunteerDiv.childNodes[i]);
}
}
boardIdentifier = document.getElementById('boardSettingsIdentifier').value;
document.getElementById('closeReportsJsButton').style.display = 'inline';
document.getElementById('closeReportsFormButton').style.display = 'none';
document.getElementById('saveSettingsJsButton').style.display = 'inline';
document.getElementById('saveSettingsFormButton').style.display = 'none';
}
function makeJsRequest(files) {
apiRequest('setCustomJs', {
files : files || [],
boardUri : boardIdentifier,
}, function requestComplete(status, data) {
document.getElementById('JsFiles').type = 'text';
document.getElementById('JsFiles').type = 'file';
if (status === 'ok') {
if (files) {
alert('New javascript set.');
} else {
alert('Javascript deleted.');
}
} else {
alert(status + ': ' + JSON.stringify(data));
}
});
}
function setJs() {
var file = document.getElementById('JsFiles').files[0];
if (!file) {
makeJsRequest();
return;
}
var reader = new FileReader();
reader.onloadend = function() {
makeJsRequest([ {
name : file.name,
content : reader.result
} ]);
};
reader.readAsDataURL(file);
}
function makeSpoilerRequest(files) {
apiRequest('setCustomSpoiler', {
files : files || [],
boardUri : boardIdentifier,
}, function requestComplete(status, data) {
document.getElementById('files').type = 'text';
document.getElementById('files').type = 'file';
if (status === 'ok') {
location.reload(true);
} else {
alert(status + ': ' + JSON.stringify(data));
}
});
}
function setSpoiler() {
var file = document.getElementById('filesSpoiler').files[0];
if (!file) {
makeSpoilerRequest();
return;
}
var reader = new FileReader();
reader.onloadend = function() {
// style exception, too simple
makeSpoilerRequest([ {
name : file.name,
content : reader.result
} ]);
// style exception, too simple
};
reader.readAsDataURL(file);
}
function makeCssRequest(files) {
apiRequest('setCustomCss', {
files : files || [],
boardUri : boardIdentifier,
}, function requestComplete(status, data) {
document.getElementById('files').type = 'text';
document.getElementById('files').type = 'file';
if (status === 'ok') {
if (files) {
alert('New CSS set.');
} else {
alert('CSS deleted.');
}
} else {
alert(status + ': ' + JSON.stringify(data));
}
});
}
function setCss() {
var file = document.getElementById('files').files[0];
if (!file) {
makeCssRequest();
return;
}
var reader = new FileReader();
reader.onloadend = function() {
// style exception, too simple
makeCssRequest([ {
name : file.name,
content : reader.result
} ]);
// style exception, too simple
};
reader.readAsDataURL(file);
}
function saveSettings() {
var typedName = document.getElementById('boardNameField').value.trim();
var typedDescription = document.getElementById('boardDescriptionField').value
.trim();
var typedMessage = document.getElementById('boardMessageField').value.trim();
var typedAnonymousName = document.getElementById('anonymousNameField').value
.trim();
var typedHourlyLimit = document.getElementById('hourlyThreadLimitField').value
.trim();
var typedAutoCaptcha = document.getElementById('autoCaptchaThresholdField').value
.trim();
var typedMaxBumpAge = document.getElementById('maxBumpAgeField').value.trim();
var typedAutoSage = document.getElementById('autoSageLimitField').value
.trim();
var typedFileLimit = document.getElementById('maxFilesField').value.trim();
var typedFileSize = document.getElementById('maxFileSizeField').value.trim();
var typedTypedMimes = document.getElementById('validMimesField').value
.split(',');
var typedThreadLimit = document.getElementById('maxThreadFields').value
.trim();
if (typedHourlyLimit.length && isNaN(typedHourlyLimit)) {
alert('Invalid hourly limit.');
return;
} else if (typedMaxBumpAge.length && isNaN(typedMaxBumpAge)) {
alert('Invalid maximum age for bumping.');
return;
} else if (typedAutoCaptcha.length && isNaN(typedAutoCaptcha)) {
alert('Invalid auto captcha treshold.');
return;
} else if (!typedName.length || !typedName.length) {
alert('Both name and description are mandatory.');
return;
} else if (typedMessage.length > 256) {
alert('Message too long, keep it under 256 characters.');
return;
}
var settings = [];
if (document.getElementById('blockDeletionCheckbox').checked) {
settings.push('blockDeletion');
}
if (document.getElementById('requireFileCheckbox').checked) {
settings.push('requireThreadFile');
}
if (document.getElementById('disableIdsCheckbox').checked) {
settings.push('disableIds');
}
if (document.getElementById('allowCodeCheckbox').checked) {
settings.push('allowCode');
}
if (document.getElementById('early404Checkbox').checked) {
settings.push('early404');
}
if (document.getElementById('uniquePostsCheckbox').checked) {
settings.push('uniquePosts');
}
if (document.getElementById('uniqueFilesCheckbox').checked) {
settings.push('uniqueFiles');
}
if (document.getElementById('unindexCheckbox').checked) {
settings.push('unindex');
}
if (document.getElementById('forceAnonymityCheckbox').checked) {
settings.push('forceAnonymity');
}
if (document.getElementById('textBoardCheckbox').checked) {
settings.push('textBoard');
}
var typedTags = document.getElementById('tagsField').value.split(',');
var combo = document.getElementById('captchaModeComboBox');
var locationCombo = document.getElementById('locationComboBox');
apiRequest(
'setBoardSettings',
{
boardName : typedName,
captchaMode : combo.options[combo.selectedIndex].value,
boardMessage : typedMessage,
autoCaptchaLimit : typedAutoCaptcha,
locationFlagMode : locationCombo.options[locationCombo.selectedIndex].value,
hourlyThreadLimit : typedHourlyLimit,
tags : typedTags,
anonymousName : typedAnonymousName,
boardDescription : typedDescription,
boardUri : boardIdentifier,
settings : settings,
autoSageLimit : typedAutoSage,
maxThreadCount : typedThreadLimit,
maxFileSizeMB : typedFileSize,
acceptedMimes : typedTypedMimes,
maxFiles : typedFileLimit,
}, function requestComplete(status, data) {
if (status === 'ok') {
location.reload(true);
} else {
alert(status + ': ' + JSON.stringify(data));
}
});
}
function processVolunteerCell(cell) {
var button = cell.getElementsByClassName('removeJsButton')[0];
button.style.display = 'inline';
cell.getElementsByClassName('removeFormButton')[0].style.display = 'none';
button.onclick = function() {
setVolunteer(cell.getElementsByClassName('userIdentifier')[0].value, false);
};
}
function addVolunteer() {
setVolunteer(document.getElementById('addVolunteerFieldLogin').value.trim(),
true, function(error) {
if (error) {
alert(error);
} else {
document.getElementById('addVolunteerFieldLogin').value = '';
}
});
}
function setVolunteersDiv(volunteers) {
var volunteersDiv = document.getElementById('volunteersDiv');
while (volunteersDiv.firstChild) {
volunteersDiv.removeChild(volunteersDiv.firstChild);
}
for (var i = 0; i < volunteers.length; i++) {
var cell = document.createElement('form');
cell.innerHTML = volunteerCellTemplate;
cell.getElementsByClassName('userIdentifier')[0].setAttribute('value',
volunteers[i]);
cell.getElementsByClassName('userLabel')[0].innerHTML = volunteers[i];
cell.getElementsByClassName('boardIdentifier')[0].setAttribute('value',
boardIdentifier);
processVolunteerCell(cell);
volunteersDiv.appendChild(cell);
}
}
function refreshVolunteers() {
localRequest('/boardManagement.js?json=1&boardUri=' + boardIdentifier,
function gotData(error, data) {
if (error) {
alert(error);
} else {
var parsedData = JSON.parse(data);
setVolunteersDiv(parsedData.volunteers || []);
}
});
}
function setVolunteer(user, add, callback) {
apiRequest('setVolunteer', {
login : user,
add : add,
boardUri : boardIdentifier
}, function requestComplete(status, data) {
if (status === 'ok') {
if (callback) {
callback();
}
refreshVolunteers();
} else {
alert(status + ': ' + JSON.stringify(data));
}
});
}
function transferBoard() {
apiRequest('transferBoardOwnership', {
login : document.getElementById('transferBoardFieldLogin').value.trim(),
boardUri : boardIdentifier
}, function requestComplete(status, data) {
if (status === 'ok') {
window.location.pathname = '/' + boardIdentifier + '/';
} else {
alert(status + ': ' + JSON.stringify(data));
}
});
}
function deleteBoard() {
apiRequest('deleteBoard', {
boardUri : boardIdentifier,
confirmDeletion : document.getElementById('confirmDelCheckbox').checked
}, function requestComplete(status, data) {
if (status === 'ok') {
window.location.pathname = '/';
} else {
alert(status + ': ' + JSON.stringify(data));
}
});
} |
import _ from 'lodash';
import Promise from 'bluebird';
import db from '../models';
import { NotFoundError } from '../components/errors';
export function list(req, res, next) {
db.ProductGroup.findAll()
.map(group =>
Promise.all([group.countProducts(), group.toJSON()]).spread(
(productCount, productGroup) => ({ ...productGroup, productCount })
)
)
.then(res.json.bind(res))
.catch(next);
}
export function create(req, res, next) {
db.ProductGroup.create({
...req.body
})
.then(role => {
res.status(201).json(role);
})
.catch(next);
}
export function update(req, res, next) {
const { id } = req.params;
db.ProductGroup.update(req.body, {
where: { id },
returning: true,
fields: _.without(Object.keys(req.body), 'id')
})
.spread((count, roles) => {
if (!count) throw new NotFoundError();
res.json(roles[0]);
})
.catch(next);
}
export function destroy(req, res, next) {
const { id } = req.params;
db.ProductGroup.destroy({
where: { id }
})
.then(count => {
if (!count) throw new NotFoundError();
res.status(204).send();
})
.catch(next);
}
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import { later } from '@ember/runloop';
import { A as emberA } from '@ember/array';
import { Promise } from 'rsvp';
import {
click,
find,
findAll,
render,
triggerEvent,
triggerKeyEvent,
waitUntil
} from '@ember/test-helpers';
module('select-box (activating options)', function (hooks) {
setupRenderingTest(hooks);
function waitForReset() {
return waitUntil(() => new Promise((resolve) => later(resolve, 1000)));
}
test('mouseenter activates options', async function (assert) {
assert.expect(7);
await render(hbs`
<SelectBox as |sb|>
<sb.Option @value={{1}}>One</sb.Option>
<sb.Option @value={{2}}>Two</sb.Option>
</SelectBox>
`);
const box = find('.select-box');
const one = findAll('.select-box__option')[0];
const two = findAll('.select-box__option')[1];
assert
.dom('.select-box__option[aria-current="true"]')
.doesNotExist('precondition, there are no active options');
await triggerEvent(one, 'mouseenter');
assert
.dom(one)
.hasAttribute(
'aria-current',
'true',
'mousing over an option gives it an active attribute'
);
assert.ok(
one.getAttribute('id').match(/select-box-el-\d+/),
'active option has an id with a numeric part'
);
assert
.dom(box)
.hasAttribute(
'aria-activedescendant',
one.id,
'the select box has the correct active descendant id'
);
await triggerEvent(two, 'mouseenter');
assert
.dom(box)
.hasAttribute(
'aria-activedescendant',
two.getAttribute('id'),
'the select box active descendant id is updated'
);
// mousing over another option moves the active attribute
assert.dom(one).hasAttribute('aria-current', 'false');
assert.dom(two).hasAttribute('aria-current', 'true');
});
test('activating by index via the api', async function (assert) {
assert.expect(2);
this.handleActivate = (value, sb) => {
assert.equal(
value,
'foo',
'activating an option sends an action with the value'
);
assert.equal(typeof sb, 'object', 'sends the api');
};
await render(hbs`
<SelectBox as |sb|>
<sb.Option @value="foo" @onActivate={{this.handleActivate}} />
<button
type="button"
{{on "click" (fn sb.activateOptionAtIndex 0)}}
>
Activate foo
</button>
</SelectBox>
`);
await click('button');
});
test('activating by value via the api', async function (assert) {
assert.expect(4);
let activated = 0;
this.handleActivate = (value, sb) => {
assert.equal(
value,
'bar',
'activating an option sends an action with the value'
);
assert.equal(typeof sb, 'object', 'sends the api');
activated++;
};
await render(hbs`
<SelectBox as |sb|>
<sb.Option @value="foo" @onActivate={{this.handleActivate}} />
<sb.Option @value="bar" @onActivate={{this.handleActivate}} />
<sb.Option @value="bar" @onActivate={{this.handleActivate}} />
<sb.Option @value="baz" @onActivate={{this.handleActivate}} />
<button type="button" {{on "click" (fn sb.activateOptionForValue "bar")}}>Activate bar</button>
</SelectBox>
`);
await click('button');
assert.equal(
activated,
1,
'onActivate only fires once (for the first matching option)'
);
assert
.dom('.select-box__option[aria-current="true"]')
.exists({ count: 1 }, 'only one matching option is activated');
});
test('activation boundaries', async function (assert) {
assert.expect(8);
// We specifically must use keydown not keyup, because
// this allows us (or the user of the addon) to preventDefault on
// the event. Thereby stopping the page from scrolling when trying
// to navigate.
// Also note that we don't cycle through the options when reaching
// the beginning or end boundaries, because we want to mimic as closely
// as possible native select boxes.
this.handlePressDown = (e, sb) => sb.activateNextOption();
this.handlePressUp = (e, sb) => sb.activatePreviousOption();
await render(hbs`
<SelectBox
@onPressDown={{this.handlePressDown}}
@onPressUp={{this.handlePressUp}} as |sb|
>
<sb.Option @value={{1}}>One</sb.Option>
<sb.Option @value={{2}}>Two</sb.Option>
<sb.Option @value={{3}}>Three</sb.Option>
</SelectBox>
`);
assert
.dom('.select-box__option[aria-current="true"]')
.doesNotExist('precondition: nothing active');
await triggerKeyEvent('.select-box', 'keydown', 40); // Down
assert.dom('.select-box__option[aria-current="true"]').hasText('One');
await triggerKeyEvent('.select-box', 'keydown', 40); // Down
assert.dom('.select-box__option[aria-current="true"]').hasText('Two');
await triggerKeyEvent('.select-box', 'keydown', 40); // Down
assert.dom('.select-box__option[aria-current="true"]').hasText('Three');
await triggerKeyEvent('.select-box', 'keydown', 40); // Down
assert
.dom('.select-box__option[aria-current="true"]')
.hasText(
'Three',
'does not cycle back to the beginning when reaching the end'
);
await triggerKeyEvent('.select-box', 'keydown', 38); // Up
assert.dom('.select-box__option[aria-current="true"]').hasText('Two');
await triggerKeyEvent('.select-box', 'keydown', 38); // Up
assert.dom('.select-box__option[aria-current="true"]').hasText('One');
await triggerKeyEvent('.select-box', 'keydown', 38); // Up
assert
.dom('.select-box__option[aria-current="true"]')
.hasText(
'One',
'does not cycle back to the end when reaching the beginning'
);
});
test('cycling through options by repeating characters', async function (assert) {
assert.expect(9);
this.handlePressKey = (e, sb) => sb.activateOptionForKeyCode(e.keyCode);
await render(hbs`
<SelectBox @onPressKey={{this.handlePressKey}} as |sb|>
<sb.Option @value="A1">A 1</sb.Option>
<sb.Option @value="A2">A 2</sb.Option>
<sb.Option @value="BA1">BA 1</sb.Option>
<sb.Option @value="A3">A 3</sb.Option>
</SelectBox>
`);
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 1');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 2');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 3');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 1');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 2');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 3');
await waitForReset();
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 1');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 2');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 3');
});
test('cycling through options containing repeating chars', async function (assert) {
assert.expect(3);
this.handlePressKey = (e, sb) => sb.activateOptionForKeyCode(e.keyCode);
await render(hbs`
<SelectBox @onPressKey={{this.handlePressKey}} as |sb|>
<sb.Option @value="AAA1">AAA 1</sb.Option>
<sb.Option @value="AA2">AA 2</sb.Option>
<sb.Option @value="A3">A 3</sb.Option>
</SelectBox>
`);
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('AAA 1');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('AA 2');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('A 3');
});
test('jumping to an option (reset timer)', async function (assert) {
assert.expect(4);
this.handlePressKey = (e, sb) => sb.activateOptionForKeyCode(e.keyCode);
await render(hbs`
<SelectBox @onPressKey={{this.handlePressKey}} as |sb|>
<sb.Option @value="foo">Foo</sb.Option>
<sb.Option @value="bar">Bar</sb.Option>
<sb.Option @value="baz">Baz</sb.Option>
</SelectBox>
`);
await triggerKeyEvent('.select-box', 'keypress', 66); // b
assert.dom('.select-box__option[aria-current="true"]').hasText('Bar');
await triggerKeyEvent('.select-box', 'keypress', 65); // a
assert.dom('.select-box__option[aria-current="true"]').hasText('Bar');
await triggerKeyEvent('.select-box', 'keypress', 90); // z
assert.dom('.select-box__option[aria-current="true"]').hasText('Baz');
await waitForReset();
await triggerKeyEvent('.select-box', 'keypress', 70); // f
assert.dom('.select-box__option[aria-current="true"]').hasText('Foo');
});
test('jumping to an option (numeric)', async function (assert) {
assert.expect(1);
this.handlePressKey = (e, sb) => sb.activateOptionForKeyCode(e.keyCode);
await render(hbs`
<SelectBox @onPressKey={{this.handlePressKey}} as |sb|>
<sb.Option @value={{1980}}>1980</sb.Option>
<sb.Option @value={{1981}}>1981</sb.Option>
<sb.Option @value={{1982}}>1982</sb.Option>
<sb.Option @value={{1983}}>1983</sb.Option>
<sb.Option @value={{1984}}>1984</sb.Option>
<sb.Option @value={{1985}}>1985</sb.Option>
</SelectBox>
`);
await triggerKeyEvent('.select-box', 'keypress', 49); // 1
await triggerKeyEvent('.select-box', 'keypress', 57); // 9
await triggerKeyEvent('.select-box', 'keypress', 56); // 8
await triggerKeyEvent('.select-box', 'keypress', 51); // 3
assert.dom('.select-box__option[aria-current="true"]').hasText('1983');
});
test('jumping to an option (dodgy chars)', async function (assert) {
assert.expect(1);
this.handlePressKey = (e, sb) => sb.activateOptionForKeyCode(e.keyCode);
await render(hbs`
<SelectBox @onPressKey={{this.handlePressKey}} as |sb|>
<sb.Option @value={{1}}>Fred S</sb.Option>
<sb.Option @value={{2}}>Fred S[</sb.Option>
</SelectBox>
`);
await triggerKeyEvent('.select-box', 'keypress', 70); // f
await triggerKeyEvent('.select-box', 'keypress', 82); // r
await triggerKeyEvent('.select-box', 'keypress', 69); // e
await triggerKeyEvent('.select-box', 'keypress', 68); // d
await triggerKeyEvent('.select-box', 'keypress', 32); // space
await triggerKeyEvent('.select-box', 'keypress', 83); // s
await triggerKeyEvent('.select-box', 'keypress', 91); // [
assert
.dom('.select-box__option[aria-current="true"]')
.hasText(
'Fred S[',
"jumps to the matching option (regexp doesn't blow up)"
);
});
test('jumping to an option (same-char regression)', async function (assert) {
assert.expect(1);
this.handlePressKey = (e, sb) => sb.activateOptionForKeyCode(e.keyCode);
await render(hbs`
<SelectBox @onPressKey={{this.handlePressKey}} as |sb|>
<sb.Option @value={{1}}>Fred</sb.Option>
<sb.Option @value={{2}}>Reggie</sb.Option>
<sb.Option @value={{3}}>Geoffrey</sb.Option>
</SelectBox>
`);
await triggerKeyEvent('.select-box', 'keypress', 71); // g
await triggerKeyEvent('.select-box', 'keypress', 69); // e
await triggerKeyEvent('.select-box', 'keypress', 79); // o
await triggerKeyEvent('.select-box', 'keypress', 70); // f
await triggerKeyEvent('.select-box', 'keypress', 70); // f (for fred)
await triggerKeyEvent('.select-box', 'keypress', 82); // r (for reggie)
assert
.dom('.select-box__option[aria-current="true"]')
.hasText(
'Geoffrey',
"does not start 'cycle through' behaviour, just because the same letter was typed"
);
});
test('jumping to an option (collapsing whitespace)', async function (assert) {
assert.expect(1);
this.handlePressKey = (e, sb) => sb.activateOptionForKeyCode(e.keyCode);
await render(hbs`
<SelectBox @onPressKey={{this.handlePressKey}} as |sb|>
<sb.Option @value={{1}}> foo </sb.Option>
<sb.Option @value={{2}}> bar baz </sb.Option>
<sb.Option @value={{3}}> qux </sb.Option>
</SelectBox>
`);
await triggerKeyEvent('.select-box', 'keypress', 66); // b
await triggerKeyEvent('.select-box', 'keypress', 65); // a
await triggerKeyEvent('.select-box', 'keypress', 82); // r
await triggerKeyEvent('.select-box', 'keypress', 32); // space
await triggerKeyEvent('.select-box', 'keypress', 65); // s
assert
.dom('.select-box__option[aria-current="true"]')
.hasText('bar baz', 'jumps to the matching option');
});
test('active option element id infinite rendering', async function (assert) {
assert.expect(0);
const item1 = { name: 'item 1' };
const item2 = { name: 'item 2' };
const item3 = { name: 'item 3' };
this.items = emberA([item1, item2, item3]);
this.handleActivateOption = (item) => this.items.removeObject(item);
await render(hbs`
<SelectBox as |sb|>
{{#each this.items as |item|}}
<sb.Option
@value={{item}}
@onActivate={{this.handleActivateOption}}
>
{{item.name}}
</sb.Option>
{{/each}}
</SelectBox>
`);
await triggerEvent('.select-box__option:nth-child(2)', 'mouseenter');
});
test('activating - nothing to activate', async function (assert) {
assert.expect(0);
this.handleReady = (sb) => sb.activateNextOption();
await render(hbs`<SelectBox @onReady={{this.handleReady}} />`);
});
test('activating focusable options', async function (assert) {
assert.expect(2);
let sb;
this.handleReady = (api) => (sb = api);
await render(hbs`
<SelectBox @onReady={{this.handleReady}} as |sb|>
<sb.Option @value={{1}}>One</sb.Option>
<sb.Option @value={{2}} tabindex="0">Two</sb.Option>
</SelectBox>
`);
const one = find('.select-box__option:nth-child(1)');
const two = find('.select-box__option:nth-child(2)');
sb.activateOptionForValue(1);
assert
.dom(one)
.isNotFocused(
'activating an option does not focus it by default (because they are just divs) ' +
'and focus is managed by aria activedescendant'
);
sb.activateOptionForValue(2);
assert
.dom(two)
.isFocused('activating an option that is focusable focuses it');
});
});
|
(function($) {
$(function() {
$('.sort-block__icon').on('click', function() {
$(this).toggleClass('sort-block__icon_desc');
});
});
})(jQuery); |
// Generated by CoffeeScript 1.12.2
(function() {
var Q, _, api, call_api, config, https, publishResource, querystring, transformation_string, update_resources_access_mode, utils,
slice = [].slice;
_ = require("lodash");
config = require("./config");
if (config().upload_prefix && config().upload_prefix.slice(0, 5) === 'http:') {
https = require('http');
} else {
https = require('https');
}
utils = require("./utils");
querystring = require("querystring");
Q = require('q');
api = module.exports;
call_api = function(method, uri, params, callback, options) {
var api_key, api_secret, api_url, cloud_name, cloudinary, deferred, handle_response, query_params, ref, ref1, ref2, ref3, ref4, ref5, request, request_options;
deferred = Q.defer();
cloudinary = (ref = (ref1 = options["upload_prefix"]) != null ? ref1 : config("upload_prefix")) != null ? ref : "https://api.cloudinary.com";
cloud_name = (function() {
var ref3;
if ((ref2 = (ref3 = options["cloud_name"]) != null ? ref3 : config("cloud_name")) != null) {
return ref2;
} else {
throw "Must supply cloud_name";
}
})();
api_key = (function() {
var ref4;
if ((ref3 = (ref4 = options["api_key"]) != null ? ref4 : config("api_key")) != null) {
return ref3;
} else {
throw "Must supply api_key";
}
})();
api_secret = (function() {
var ref5;
if ((ref4 = (ref5 = options["api_secret"]) != null ? ref5 : config("api_secret")) != null) {
return ref4;
} else {
throw "Must supply api_secret";
}
})();
api_url = [cloudinary, "v1_1", cloud_name].concat(uri).join("/");
query_params = querystring.stringify(params);
if (method === "get") {
api_url += "?" + query_params;
}
request_options = require('url').parse(api_url);
request_options = _.extend(request_options, {
method: method.toUpperCase(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': utils.getUserAgent()
},
auth: api_key + ":" + api_secret
});
if (options.agent != null) {
request_options.agent = options.agent;
}
if (method !== "get") {
request_options.headers['Content-Length'] = Buffer.byteLength(query_params);
}
handle_response = function(res) {
var buffer, err_obj, error;
if (_.includes([200, 400, 401, 403, 404, 409, 420, 500], res.statusCode)) {
buffer = "";
error = false;
res.on("data", function(d) {
return buffer += d;
});
res.on("end", function() {
var e, result;
if (error) {
return;
}
try {
result = JSON.parse(buffer);
} catch (error1) {
e = error1;
result = {
error: {
message: "Server return invalid JSON response. Status Code " + res.statusCode
}
};
}
if (result["error"]) {
result["error"]["http_code"] = res.statusCode;
} else {
result["rate_limit_allowed"] = parseInt(res.headers["x-featureratelimit-limit"]);
result["rate_limit_reset_at"] = new Date(res.headers["x-featureratelimit-reset"]);
result["rate_limit_remaining"] = parseInt(res.headers["x-featureratelimit-remaining"]);
}
if (result.error) {
deferred.reject(result);
} else {
deferred.resolve(result);
}
return typeof callback === "function" ? callback(result) : void 0;
});
return res.on("error", function(e) {
var err_obj;
error = true;
err_obj = {
error: {
message: e,
http_code: res.statusCode
}
};
deferred.reject(err_obj.error);
return typeof callback === "function" ? callback(err_obj) : void 0;
});
} else {
err_obj = {
error: {
message: "Server returned unexpected status code - " + res.statusCode,
http_code: res.statusCode
}
};
deferred.reject(err_obj.error);
return typeof callback === "function" ? callback(err_obj) : void 0;
}
};
request = https.request(request_options, handle_response);
request.on("error", function(e) {
return typeof callback === "function" ? callback({
error: e
}) : void 0;
});
request.setTimeout((ref5 = options["timeout"]) != null ? ref5 : 60000);
if (method !== "get") {
request.write(query_params);
}
request.end();
return deferred.promise;
};
transformation_string = function(transformation) {
if (_.isString(transformation)) {
return transformation;
} else {
return utils.generate_transformation_string(_.extend({}, transformation));
}
};
exports.ping = function(callback, options) {
if (options == null) {
options = {};
}
return call_api("get", ["ping"], {}, callback, options);
};
exports.usage = function(callback, options) {
if (options == null) {
options = {};
}
return call_api("get", ["usage"], {}, callback, options);
};
exports.resource_types = function(callback, options) {
if (options == null) {
options = {};
}
return call_api("get", ["resources"], {}, callback, options);
};
exports.resources = function(callback, options) {
var ref, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = options["type"];
uri = ["resources", resource_type];
if (type != null) {
uri.push(type);
}
if ((options.start_at != null) && Object.prototype.toString.call(options.start_at) === '[object Date]') {
options.start_at = options.start_at.toUTCString();
}
return call_api("get", uri, api.only(options, "next_cursor", "max_results", "prefix", "tags", "context", "direction", "moderations", "start_at"), callback, options);
};
exports.resources_by_tag = function(tag, callback, options) {
var ref, resource_type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
uri = ["resources", resource_type, "tags", tag];
return call_api("get", uri, api.only(options, "next_cursor", "max_results", "tags", "context", "direction", "moderations"), callback, options);
};
exports.resources_by_context = function(key, value, callback, options) {
var params, ref, resource_type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
uri = ["resources", resource_type, "context"];
params = api.only(options, "next_cursor", "max_results", "tags", "context", "direction", "moderations");
params.key = key;
if (value != null) {
params.value = value;
}
return call_api("get", uri, params, callback, options);
};
exports.resources_by_moderation = function(kind, status, callback, options) {
var ref, resource_type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
uri = ["resources", resource_type, "moderations", kind, status];
return call_api("get", uri, api.only(options, "next_cursor", "max_results", "tags", "context", "direction", "moderations"), callback, options);
};
exports.resources_by_ids = function(public_ids, callback, options) {
var params, ref, ref1, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = (ref1 = options["type"]) != null ? ref1 : "upload";
uri = ["resources", resource_type, type];
params = api.only(options, "tags", "context", "moderations");
params["public_ids[]"] = public_ids;
return call_api("get", uri, params, callback, options);
};
exports.resource = function(public_id, callback, options) {
var ref, ref1, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = (ref1 = options["type"]) != null ? ref1 : "upload";
uri = ["resources", resource_type, type, public_id];
return call_api("get", uri, api.only(options, "exif", "colors", "faces", "image_metadata", "pages", "phash", "coordinates", "max_results"), callback, options);
};
exports.restore = function(public_ids, callback, options) {
var ref, ref1, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = (ref1 = options["type"]) != null ? ref1 : "upload";
uri = ["resources", resource_type, type, "restore"];
return call_api("post", uri, {
public_ids: public_ids
}, callback, options);
};
exports.update = function(public_id, callback, options) {
var params, ref, ref1, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = (ref1 = options["type"]) != null ? ref1 : "upload";
uri = ["resources", resource_type, type, public_id];
params = utils.updateable_resource_params(options);
if (options.moderation_status != null) {
params.moderation_status = options.moderation_status;
}
return call_api("post", uri, params, callback, options);
};
exports.delete_resources = function(public_ids, callback, options) {
var ref, ref1, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = (ref1 = options["type"]) != null ? ref1 : "upload";
uri = ["resources", resource_type, type];
return call_api("delete", uri, _.extend({
"public_ids[]": public_ids
}, api.only(options, "keep_original", "invalidate")), callback, options);
};
exports.delete_resources_by_prefix = function(prefix, callback, options) {
var ref, ref1, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = (ref1 = options["type"]) != null ? ref1 : "upload";
uri = ["resources", resource_type, type];
return call_api("delete", uri, _.extend({
prefix: prefix
}, api.only(options, "keep_original", "next_cursor", "invalidate")), callback, options);
};
exports.delete_resources_by_tag = function(tag, callback, options) {
var ref, resource_type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
uri = ["resources", resource_type, "tags", tag];
return call_api("delete", uri, api.only(options, "keep_original", "next_cursor", "invalidate"), callback, options);
};
exports.delete_all_resources = function(callback, options) {
var ref, ref1, resource_type, type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
type = (ref1 = options["type"]) != null ? ref1 : "upload";
uri = ["resources", resource_type, type];
return call_api("delete", uri, _.extend({
all: true
}, api.only(options, "keep_original", "next_cursor", "invalidate")), callback, options);
};
exports.delete_derived_resources = function(derived_resource_ids, callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["derived_resources"];
return call_api("delete", uri, {
"derived_resource_ids[]": derived_resource_ids
}, callback, options);
};
exports.tags = function(callback, options) {
var ref, resource_type, uri;
if (options == null) {
options = {};
}
resource_type = (ref = options["resource_type"]) != null ? ref : "image";
uri = ["tags", resource_type];
return call_api("get", uri, api.only(options, "next_cursor", "max_results", "prefix"), callback, options);
};
exports.transformations = function(callback, options) {
if (options == null) {
options = {};
}
return call_api("get", ["transformations"], api.only(options, "next_cursor", "max_results"), callback, options);
};
exports.transformation = function(transformation, callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["transformations", transformation_string(transformation)];
return call_api("get", uri, api.only(options, "next_cursor", "max_results"), callback, options);
};
exports.delete_transformation = function(transformation, callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["transformations", transformation_string(transformation)];
return call_api("delete", uri, {}, callback, options);
};
exports.update_transformation = function(transformation, updates, callback, options) {
var params, uri;
if (options == null) {
options = {};
}
uri = ["transformations", transformation_string(transformation)];
params = api.only(updates, "allowed_for_strict");
if (updates.unsafe_update != null) {
params.unsafe_update = transformation_string(updates.unsafe_update);
}
return call_api("put", uri, params, callback, options);
};
exports.create_transformation = function(name, definition, callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["transformations", name];
return call_api("post", uri, {
transformation: transformation_string(definition)
}, callback, options);
};
exports.upload_presets = function(callback, options) {
if (options == null) {
options = {};
}
return call_api("get", ["upload_presets"], api.only(options, "next_cursor", "max_results"), callback, options);
};
exports.upload_preset = function(name, callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["upload_presets", name];
return call_api("get", uri, {}, callback, options);
};
exports.delete_upload_preset = function(name, callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["upload_presets", name];
return call_api("delete", uri, {}, callback, options);
};
exports.update_upload_preset = function(name, callback, options) {
var params, uri;
if (options == null) {
options = {};
}
uri = ["upload_presets", name];
params = utils.merge(utils.clear_blank(utils.build_upload_params(options)), api.only(options, "unsigned", "disallow_public_id"));
return call_api("put", uri, params, callback, options);
};
exports.create_upload_preset = function(callback, options) {
var params, uri;
if (options == null) {
options = {};
}
uri = ["upload_presets"];
params = utils.merge(utils.clear_blank(utils.build_upload_params(options)), api.only(options, "name", "unsigned", "disallow_public_id"));
return call_api("post", uri, params, callback, options);
};
exports.root_folders = function(callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["folders"];
return call_api("get", uri, {}, callback, options);
};
exports.sub_folders = function(path, callback, options) {
var uri;
if (options == null) {
options = {};
}
uri = ["folders", path];
return call_api("get", uri, {}, callback, options);
};
exports.upload_mappings = function(callback, options) {
var params;
if (options == null) {
options = {};
}
params = api.only(options, "next_cursor", "max_results");
return call_api("get", "upload_mappings", params, callback, options);
};
exports.upload_mapping = function(name, callback, options) {
if (name == null) {
name = null;
}
if (options == null) {
options = {};
}
return call_api("get", 'upload_mappings', {
folder: name
}, callback, options);
};
exports.delete_upload_mapping = function(name, callback, options) {
if (options == null) {
options = {};
}
return call_api("delete", 'upload_mappings', {
folder: name
}, callback, options);
};
exports.update_upload_mapping = function(name, callback, options) {
var params;
if (options == null) {
options = {};
}
params = api.only(options, "template");
params["folder"] = name;
return call_api("put", 'upload_mappings', params, callback, options);
};
exports.create_upload_mapping = function(name, callback, options) {
var params;
if (options == null) {
options = {};
}
params = api.only(options, "template");
params["folder"] = name;
return call_api("post", 'upload_mappings', params, callback, options);
};
publishResource = function(byKey, value, callback, options) {
var params, ref, resource_type, uri;
if (options == null) {
options = {};
}
params = api.only(options, "invalidate", "overwrite");
params[byKey] = value;
resource_type = (ref = options.resource_type) != null ? ref : "image";
uri = ["resources", resource_type, "publish_resources"];
options = _.extend({
resource_type: resource_type
}, options);
return call_api("post", uri, params, callback, options);
};
exports.publish_by_prefix = function(prefix, callback, options) {
if (options == null) {
options = {};
}
return publishResource("prefix", prefix, callback, options);
};
exports.publish_by_tag = function(tag, callback, options) {
if (options == null) {
options = {};
}
return publishResource("tag", tag, callback, options);
};
exports.publish_by_ids = function(public_ids, callback, options) {
if (options == null) {
options = {};
}
return publishResource("public_ids", public_ids, callback, options);
};
exports.list_streaming_profiles = function(callback, options) {
if (options == null) {
options = {};
}
return call_api("get", "streaming_profiles", {}, callback, options);
};
exports.get_streaming_profile = function(name, callback, options) {
if (options == null) {
options = {};
}
return call_api("get", "streaming_profiles/" + name, {}, callback, options);
};
exports.delete_streaming_profile = function(name, callback, options) {
if (options == null) {
options = {};
}
return call_api("delete", "streaming_profiles/" + name, {}, callback, options);
};
exports.update_streaming_profile = function(name, callback, options) {
var params;
if (options == null) {
options = {};
}
params = utils.build_streaming_profiles_param(options);
return call_api("put", "streaming_profiles/" + name, params, callback, options);
};
exports.create_streaming_profile = function(name, callback, options) {
var params;
if (options == null) {
options = {};
}
params = utils.build_streaming_profiles_param(options);
params["name"] = name;
return call_api("post", 'streaming_profiles', params, callback, options);
};
update_resources_access_mode = function(access_mode, by_key, value, callback, options) {
var params, ref, ref1, resource_type, type;
if (options == null) {
options = {};
}
resource_type = (ref = options.resource_type) != null ? ref : "image";
type = (ref1 = options.type) != null ? ref1 : "upload";
params = {
access_mode: access_mode
};
params[by_key] = value;
return call_api("post", "resources/" + resource_type + "/" + type + "/update_access_mode", params, callback, options);
};
exports.update_resources_access_mode_by_prefix = function(access_mode, prefix, callback, options) {
if (options == null) {
options = {};
}
return update_resources_access_mode(access_mode, "prefix", prefix, callback, options);
};
exports.update_resources_access_mode_by_tag = function(access_mode, tag, callback, options) {
if (options == null) {
options = {};
}
return update_resources_access_mode(access_mode, "tag", tag, callback, options);
};
exports.update_resources_access_mode_by_ids = function(access_mode, ids, callback, options) {
if (options == null) {
options = {};
}
return update_resources_access_mode(access_mode, "public_ids[]", ids, callback, options);
};
exports.only = function() {
var hash, i, key, keys, len, result;
hash = arguments[0], keys = 2 <= arguments.length ? slice.call(arguments, 1) : [];
result = {};
for (i = 0, len = keys.length; i < len; i++) {
key = keys[i];
if (hash[key] != null) {
result[key] = hash[key];
}
}
return result;
};
}).call(this);
//# sourceMappingURL=api.js.map
|
'use strict';
describe('Controller: MemberEditCtrl', function() {
beforeEach(module('ProtractorMeetupApp', 'ControllerTestHelper'));
beforeEach(inject(function(jasmineMatchers) {
this.addMatchers(jasmineMatchers);
}));
var MemberEditCtrl, scope, createController, fake;
beforeEach(inject(function($controller, $rootScope, $routeParams, fakeResource) {
fake = fakeResource;
createController = function(memberId) {
$routeParams.memberId = memberId;
scope = $rootScope.$new();
MemberEditCtrl = $controller('MemberEditCtrl', {
$scope: scope
});
};
}));
it('should create a new member', function() {
fake.member.whenCreate().returns({id: 1});
// Given that you load the controller to create a new member.
createController('new');
// When you save.
scope.save();
// Then ensure a new member was created.
expect(fake.member).toHaveBeenCreated();
});
it('should update an existing member', function() {
fake.member.whenGetById().returnsDefault();
fake.member.whenUpdate().returns();
// Given that load an existing member.
createController(321);
fake.flush();
// When you save.
scope.item.name = 'updated name';
scope.save();
// When ensure the member was updated.
expect(fake.member).toHaveBeenRequested();
expect(fake.member).toHaveBeenUpdated({name: 'updated name'});
});
});
|
/**
* @description dev
* @author minfive
* @date 2017-03-23, 23:27:18
* @lastModify minfive
* @lastDate 2017-03-26, 23:08:22
* @github https://github.com/Mrminfive
*/
const
path = require('path'),
chalk = require('chalk'),
opn = require('opn'),
webpackServer = require('webpack-dev-server');
const
config = require('../config'),
webpackConfig = require('./webpack.dev.config.js');
let { webpackCompile } = require('./util');
// 配置环境变量
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV);
const port = process.env.PORT || config.dev.port;
const compiler = webpackCompile(webpackConfig, null, () => {
const url = `http://localhost:${port}`;
console.log(chalk.yellow(`\n\nStarting server on ${url}`));
opn(url);
});
const server = new webpackServer(compiler, {
stats: {
colors: true
},
contentBase: config.dev.assetsRoot,
staticOptions: {
redirect: false
},
proxy: config.dev.proxy
});
server.listen(port, () => {
console.log(chalk.green('dev server was opening.'));
}); |
/**
* Module dependencies.
*/
var db = require('../../config/sequelize');
var md5 = require('MD5');
var moment = require('moment');
var async = require('async');
var validator = require('validator');
var mailer = require('../lib/mailer');
exports.session = function(req, res, next) {
var token = req.headers.token;
if(token !== "" && token !== null && typeof token !== "undefined") {
db.UserSession.find({where: {sessionToken: token}}).success(function(session) {
if(session && (session.expiryDate === null || moment(session.expiryDate).unix() > moment().unix() ) ){
db.User.find({where: {id: session.UserId}}).success(function(user) {
req.user = user;
next();
}).error(function() {
next();
});
}
else {
next();
}
}).error(function() {
next();
});
}
else {
next();
}
};
/**
* Logout
*/
exports.signout = function(req, res) {
// req.logout();
return res.jsonp({
error: '',
code: 'OK'
});
};
exports.failed = function(req, res) {
return res.status(400).send({
error: "Woops, wrong email or password!",
code: "INVALID_CREDENTIAL"
});
};
exports.auth = function(req, res) {
var email = req.body.email;
var password = req.body.password;
var deviceType = req.body.deviceType;
var deviceToken = req.body.deviceToken;
db.User.find({ where: { email: email, status: 'ACTIVE' }}).success(function(user) {
if (!user) {
return res.status(401).send({
error: 'Woops, wrong email or password.',
code: 'INVALID_CREDENTIAL'
});
}
else if(user.facebookId !== "" && user.facebookId !== null && typeof user.facebookId !== "undefined") {
return res.status(401).send({
error: 'This account is created by Facebook account.',
code: 'INVALID_CREDENTIAL'
});
}
else if (!user.authenticate(password)) {
return res.status(401).send({
error: 'Woops, wrong email or password.',
code: 'INVALID_CREDENTIAL'
});
}
else if(deviceType && deviceType != "IOS" && deviceType != "ANDROID") {
return res.status(401).send({
error: 'Invalid Device type.',
code: 'INVALID_DEVICE_TYPE'
});
}
else {
console.log('Login (local) : { id: ' + user.id + ', email: ' + user.email + ' }');
db.sequelize.query('DELETE FROM UserSessions WHERE UserId = ' + user.id)
.then(function(users) {
var token = db.UserSession.createSession(user.id);
if(deviceToken) {
db.UserDevice.addDevice({
type: deviceType,
token: deviceToken,
UserId: user.id
});
}
return res.send({
error: '',
code: 'OK',
token: token,
user: user.json()
});
}, function(err) {
console.log(err);
});
}
}).error(function(err){
return res.status(400).send({
error: 'Unexpected error.',
code: 'UNEXPECTED_ERROR'
});
});
};
exports.update = function(req, res) {
if(!req.body.firstname) {
if(req.body.type == 'SRS') {
return res.status(400).send({
error: 'Please enter business name.',
code: 'EMPTY_FIRSTNAME'
});
}
else {
return res.status(400).send({
error: 'Please enter first name.',
code: 'EMPTY_FIRSTNAME'
});
}
}
if(req.body.type != 'SRS' && !req.body.lastname) {
return res.status(400).send({
error: 'Please enter last name.',
code: 'EMPTY_LASTNAME'
});
}
if(req.body.password && req.body.password.length < 6) {
return res.status(400).send({
error: 'Passwords must be at least 6 charactors.',
code: 'INVALID_PASSWORD'
});
}
req.user.firstname = req.body.firstname;
req.user.lastname = req.body.lastname;
req.user.address = req.body.address;
req.user.photo = req.body.photo;
req.user.phone = req.body.phone;
if(req.body.password) {
req.user.salt = req.user.makeSalt();
req.user.hashedPassword = req.user.encryptPassword(req.body.password, req.user.salt);
}
if(req.user.type == 'DRIVER') {
req.user.braintreeCustomerId = req.body.braintreeCustomerId;
}
req.user.save().success(function(){
return res.send({
error: '',
code: 'OK',
user: req.user.json()
});
}).error(function(err){
console.log(err);
return res.status(400).send({
error: "Unexpected error.",
code: "UNEXPECTED_ERROR"
});
});
};
exports.updateStatus = function(req, res) {
var onlineStatus = req.body.status;
if(onlineStatus != "BUSY" && onlineStatus != "ONLINE" && onlineStatus != "OFFLINE" && onlineStatus != "AWAY") {
return res.status(400).send({
error: 'Invalid status code.',
code: 'INVALID_STATUS'
});
}
req.user.onlineStatus = onlineStatus;
req.user.save()
.success(function() {
return res.send({
error: '',
code: 'OK'
});
})
.error(function(err) {
console.log(err);
return res.status(400).send({
error: "Unexpected error.",
code: "UNEXPECTED_ERROR"
});
});
};
exports.updateLocation = function(req, res) {
var latitude = req.body.latitude;
var longitude = req.body.longitude;
req.user.latitude = latitude;
req.user.longitude = longitude;
req.user.save()
.success(function() {
return res.send({
error: '',
code: 'OK'
});
})
.error(function(err) {
console.log(err);
return res.status(400).send({
error: "Unexpected error.",
code: "UNEXPECTED_ERROR"
});
});
};
exports.getLocation = function(req, res) {
return res.send({
error: "",
code: "",
location: {
latitude: req.profile.latitude,
longitude: req.profile.longitude
}
});
};
/**
* Forget password
*/
exports.requestForget = function(req, res) {
db.User.find({where:{email:req.query.email}})
.then(function(user) {
if(!user) {
return res.status(400).send({
error: 'Email address does not exist.',
code: 'INVALID_EMAIL'
});
}
else if(user.facebookId !== "" && user.facebookId !== null) {
return res.status(400).send({
error: 'User account with this email address seems to be created with Open ID.',
code: 'INVALID_EMAIL'
});
}
else {
user.token = md5(Date.now());
user.tokenExpiry = new Date((new Date()).getTime() + 2 * 60 * 60 * 1000); //expire in 2 hours
user.save().success(function() {
mailer.email_forget_password(user);
return res.send({
error: '',
code: 'OK'
});
})
.error(function(err) {
console.log(err);
return res.status(400).send({
error: "Unexpected error.",
code: 'UNEXPECTED_ERROR'
});
});
}
});
};
exports.verifyForget = function(req, res) {
db.User.find({where:{token:req.body.token}})
.then(function(user) {
if(!user) {
return res.status(400).send({
error: 'Invalid token specified.',
code: 'INVALID_TOKEN'
});
}
else if(user.tokenExpiry.getTime() <= new Date().getTime()) {
return res.status(400).send({
error: 'Token has expired. Please try again.',
code: 'EXPIRED_TOKEN'
});
}
else {
user.token = '';
user.tokenExpiry = null;
user.save()
.success(function() {
var token = db.UserSession.createSession(user.id);
return res.send({
error: '',
code: 'OK',
token: token,
user: user.json()
});
});
}
});
};
/**
* Send User
*/
exports.me = function(req, res) {
res.jsonp({
error: '',
code: 'OK',
user: req.user.json()
});
};
exports.user = function(req, res, next, id) {
db.User.find({where : { id: id}}).success ( function(user) {
if(!user) return next(new Error("Failed to load User " + id));
req.profile = user;
next();
}).error(function(err) {
next(err);
});
};
exports.userStats = function(req, res) {
db.sequelize.query("SELECT (select count(*) from `Users` where `type` = 'driver' and `status` = 'ACTIVE' and onlineStatus = 'BUSY') as 'active',(select count(*) from `Users` where `type` = 'driver' and `status` = 'ACTIVE' and onlineStatus = 'ONLINE') as 'available'")
.then(function(info) {
return res.status(200).send({
error: "",
code: 'OK',
stats: {
active: info[0].active,
available: info[0].available
}
});
}, function(err) {
console.log(err);
return res.status(400).send({
error: "Unexpected error.",
code: 'UNEXPECTED_ERROR'
});
});
}; |
kitchen_replace_list = [
{
"name_jp": "\u30cd\u30b3\u306e\u8d77\u4e0a\u304c\u308a\u8853\u3010\u5c0f\u3011",
"name": "Felyne Riser (Lo)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u8d77\u4e0a\u304c\u308a\u8853\u3010\u5927\u3011",
"name": "Felyne Riser (Hi)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u8d77\u4e0a\u308a\u8853\u3010\u5c0f\u3011",
"name": "Felyne Riser (Lo)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u8d77\u4e0a\u308a\u8853\u3010\u5927\u3011",
"name": "Felyne Riser (Hi)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u6bdb\u3065\u304f\u308d\u3044\u4e0a\u624b",
"name": "Felyne Groomer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u30de\u30bf\u30bf\u30d3\u7206\u7834\u8853",
"name": "Felyne Blaster"
},
{
"name_jp": "\u30cd\u30b3\u306e\u9632\u5fa1\u8853\u3010\u5c0f\u3011",
"name": "Felyne Defender (Lo)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u9632\u5fa1\u8853\u3010\u5927\u3011",
"name": "Felyne Defender (Hi)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u8abf\u5408\u8853\u3010\u5c0f\u3011",
"name": "Felyne Combiner (Lo)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u8abf\u5408\u8853\u3010\u5927\u3011",
"name": "Felyne Combiner (Hi)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u5f31\u3044\u306e\u6765\u3044\uff01",
"name": "Felyne Weakener"
},
{
"name_jp": "\u30cd\u30b3\u306e\u618e\u307e\u308c\u4e0a\u624b",
"name": "Felyne Provoker"
},
{
"name_jp": "\u30cd\u30b3\u306e\u5831\u916c\u91d1\u4fdd\u967a",
"name": "Felyne Insurance"
},
{
"name_jp": "\u30cd\u30b3\u306e\u304b\u304b\u3063\u3066\u3053\u3044",
"name": "Felyne Gamechanger"
},
{
"name_jp": "\u30cd\u30b3\u306e\u3053\u3084\u3057\u7389\u9054\u4eba",
"name": "Felyne Dungmaster"
},
{
"name_jp": "\u30cd\u30b3\u306e\u30aa\u30c8\u30e2\u6307\u5c0e\u8853",
"name": "Felyne Trainer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u306f\u308a\u3064\u304d\u8d85\u4eba",
"name": "Felyne Cliffhanger"
},
{
"name_jp": "\u30cd\u30b3\u306e\u89e3\u4f53\u8853\u3010\u5c0f\u3011",
"name": "Felyne Carver (Lo)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u89e3\u4f53\u8853\u3010\u5927\u3011",
"name": "Felyne Carver (Hi)"
},
{
"name_jp": "\u30cd\u30b3\u306e\u306f\u3058\u304b\u308c\u4e0a\u624b",
"name": "Felyne Deflector"
},
{
"name_jp": "\u30cd\u30b3\u306e\u7279\u6b8a\u653b\u6483\u8853",
"name": "Felyne Specialist"
},
{
"name_jp": "\u30cd\u30b3\u306e\u706b\u5c5e\u6027\u5f97\u610f",
"name": "Felyne Firestarter"
},
{
"name_jp": "\u30cd\u30b3\u306e\u6c34\u5c5e\u6027\u5f97\u610f",
"name": "Felyne Waterbearer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u96f7\u5c5e\u6027\u5f97\u610f",
"name": "Felyne Thundercaller"
},
{
"name_jp": "\u30cd\u30b3\u306e\u6c37\u5c5e\u6027\u5f97\u610f",
"name": "Felyne Icebreaker"
},
{
"name_jp": "\u30cd\u30b3\u306e\u9f8d\u5c5e\u6027\u5f97\u610f",
"name": "Felyne Dragonslayer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u3059\u308a\u306c\u3051\u8853",
"name": "Felyne Slider"
},
{
"name_jp": "\u30cd\u30b3\u306e\u3075\u3093\u3070\u308a\u8853",
"name": "Felyne Feet"
},
{
"name_jp": "\u30cd\u30b3\u306e\u5343\u91cc\u773c\u306e\u8853",
"name": "Felyne Oracle"
},
{
"name_jp": "\u30cd\u30b3\u306e\u79d8\u5883\u63a2\u7d22\u8853",
"name": "Felyne Explorer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u9053\u5177\u5039\u7d04\u8853",
"name": "Felyne Woodsman"
},
{
"name_jp": "\u30cd\u30b3\u306e\u904b\u642c\u306e\u9244\u4eba",
"name": "Felyne Strongcat"
},
{
"name_jp": "\u30cd\u30b3\u306e\u904b\u642c\u306e\u8d85\u4eba",
"name": "Felyne Supercat"
},
{
"name_jp": "\u30cd\u30b3\u306e\u77ed\u671f\u50ac\u7720\u8853",
"name": "Felyne Booster"
},
{
"name_jp": "\u30cd\u30b3\u306e\u89e3\u4f53\u306e\u9244\u4eba",
"name": "Felyne Supercarver"
},
{
"name_jp": "\u30cd\u30b3\u306e\u30b4\u30ea\u62bc\u3057\u8853",
"name": "Felyne Bulldozer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u8abf\u67fb\u5831\u544a\u8853",
"name": "Felyne Reporter"
},
{
"name_jp": "\u30cd\u30b3\u306e\u65c5\u56e3\u5949\u4ed5\u8853",
"name": "Felyne Caravaneer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u66b4\u308c\u6483\u3061",
"name": "Felyne Temper"
},
{
"name_jp": "\u30cd\u30b3\u306e\u53d7\u3051\u8eab\u8853",
"name": "Felyne Acrobat"
},
{
"name_jp": "\u30cd\u30b3\u306e\u91e3\u308a\u4e0a\u624b",
"name": "Felyne Fisher"
},
{
"name_jp": "\u30cd\u30b3\u306e\u4e57\u308a\u4e0a\u624b",
"name": "Felyne Rider"
},
{
"name_jp": "\u30cd\u30b3\u306e\u304a\u307e\u3051\u8853",
"name": "Felyne Foodie"
},
{
"name_jp": "\u30cd\u30b3\u306e\u624b\u914d\u4e0a\u624b",
"name": "Felyne Supplier"
},
{
"name_jp": "\u30cd\u30b3\u306e\u30ab\u30ea\u30b9\u30de",
"name": "Felyne Charisma"
},
{
"name_jp": "\u30cd\u30b3\u306e\u706b\u4e8b\u5834\u529b",
"name": "Felyne Heroics"
},
{
"name_jp": "\u62db\u304d\u30cd\u30b3\u306e\u60aa\u904b",
"name": "Unlucky Cat"
},
{
"name_jp": "\u62db\u304d\u30cd\u30b3\u306e\u91d1\u904b",
"name": "Crazy Lucky Cat"
},
{
"name_jp": "\u62db\u304d\u30cd\u30b3\u306e\u5e78\u904b",
"name": "Lucky Cat"
},
{
"name_jp": "\u62db\u304d\u30cd\u30b3\u306e\u6fc0\u904b",
"name": "Ultra Lucky Cat"
},
{
"name_jp": "\u30cd\u30b3\u306e\u7814\u78e8\u8853",
"name": "Felyne Polisher"
},
{
"name_jp": "\u30cd\u30b3\u306e\uff2b\uff2f\u8853",
"name": "Felyne Slugger"
},
{
"name_jp": "\u30cd\u30b3\u306e\u5c04\u6483\u8853",
"name": "Felyne Sharpshooter"
},
{
"name_jp": "\u30cd\u30b3\u306e\u7832\u6483\u8853",
"name": "Felyne Bombardier"
},
{
"name_jp": "\u30cd\u30b3\u306e\u9003\u8d70\u8853",
"name": "Felyne Escape Artist"
},
{
"name_jp": "\u30cd\u30b3\u306e\u3059\u308a\u629c\u3051\u8853",
"name": "Felyne Escape Artist"
},
{
"name_jp": "\u30cd\u30b3\u306e\u4e0d\u7720\u8853",
"name": "Felyne Insomniac"
},
{
"name_jp": "\u30cd\u30b3\u306e\u30c9\u6839\u6027",
"name": "Felyne Moxie"
},
{
"name_jp": "\u30cd\u30b3\u306e\u533b\u7642\u8853",
"name": "Felyne Medic"
},
{
"name_jp": "\u30cd\u30b3\u306e\u6295\u64f2\u8853",
"name": "Felyne Hurler"
},
{
"name_jp": "\u30cd\u30b3\u306e\u8e74\u811a\u8853",
"name": "Felyne Kickboxer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u5439\u594f\u8853",
"name": "Felyne Hornblower"
},
{
"name_jp": "\u30cd\u30b3\u306e\u9577\u9774\u8853",
"name": "Felyne Fur Coating"
},
{
"name_jp": "\u30cd\u30b3\u306e\u63a2\u7d22\u8853",
"name": "Felyne Ecologist"
},
{
"name_jp": "\u30cd\u30b3\u306e\u63a1\u53d6\u8853",
"name": "Felyne Gatherer"
},
{
"name_jp": "\u30cd\u30b3\u306e\u7740\u5730\u8853",
"name": "Felyne Lander"
},
{
"name_jp": "\u30cd\u30b3\u306e\u706b\u85ac\u8853",
"name": "Felyne Pyro"
},
{
"name_jp": "\u30cd\u30b3\u306e\u4f11\u61a9\u8853",
"name": "Cool Cat"
},
{
"name_jp": "\u30cd\u30b3\u306e\u62f3\u95d8\u8853",
"name": "Felyne Fighter"
},
{
"name_jp": "\u30cd\u30b3\u306e\u63db\u7b97\u8853",
"name": "Felyne Exchanger"
},
{
"name_jp": "\u30cd\u30b3\u306e\u4f53\u8853",
"name": "Felyne Black Belt"
},
{
"name_jp": "\u30cd\u30b3\u306e\u80c6\u529b",
"name": "Felyne Courage"
}
];
|
'use strict';
//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
//Then define the init function for starting up the application
angular.element(document).ready(function() {
if (window.location.hash === '#_=_') window.location.hash = '#!';
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
}); |
angular.module('investHouseAdmin.services')
.factory('generalConfigurationService', ['$http', '$rootScope', function($http, $rootScope) {
var generalSetting = {};
generalSetting.loadInformation = function() {
return $http({
url: $rootScope.apiLink + 'api/generalSettings/get',
method: "GET"
});
}
generalSetting.saveConfigData = function(configData) {
return $http({
url: $rootScope.apiLink + 'api/GeneralSettings/save',
method: "POST",
data: configData
});
}
return generalSetting;
}]); |
import Diamond from './diamond.js'
describe('Make diamond function', () => {
var diamond = new Diamond();
it('test letter A', function() {
const result = "A\n";
expect(diamond.makeDiamond('A')).toEqual(result);
});
it('test letter C', function() {
const result = [" A ",
" B B ",
"C C",
" B B ",
" A "].join("\n") + "\n";
expect(diamond.makeDiamond('C')).toEqual(result);
});
it('test letter E', function() {
const result = [" A ",
" B B ",
" C C ",
" D D ",
"E E",
" D D ",
" C C ",
" B B ",
" A "].join("\n") + "\n";
expect(diamond.makeDiamond('E')).toEqual(result);
});
});
|
if (typeof(console) == 'undefined') {
window.console = console = {
'log': function() {},
'info': function() {},
'warn': function() {},
'error': function() {}
};
}
var xn = {};
xn.config = {
'fancyOptions': {
'transitionIn' : 'fade',
'transitionOut' : 'fade',
'autoDimensions' : false,
'autoScale' : false,
'centerOnScroll' : false,
'overlayColor' : '#000',
'overlayOpacity' : 0.75,
'overlayShow' : true,
'scrolling' : 'no',
'showNavArrows' : false,
'width' : '600px',
'height' : 'auto',
'padding' : 20,
'modal' : true,
'speedIn' : 350,
'speedOut' : 350,
'onStart' : function(obj) {
if ($(obj).attr('data-selected') === '') {
return false;
}
},
'onComplete' : function() {
$('#fancybox-close').show();
xn.helper.stylize('#fancybox-inner');
xn.helper.fancyformify('#fancybox-inner');
$(document).unbind('keydown.fb').bind('keydown.fb', function(e) {
if (e.keyCode == 27) {
e.preventDefault();
$.fancybox.close();
} else if ((e.keyCode == 37 || e.keyCode == 39) && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA') {
e.preventDefault();
$.fancybox[ e.keyCode == 37 ? 'prev' : 'next']();
}
});
},
'onClosed' : function(obj) {
location.href = location.href;
/*
if ($(obj).hasClass('no-update')) {
} else if ($(obj).hasClass('reload-update')) {
location.href = location.href;
} else {
$('.grid-container').load(location.href, function() {
xn.helper.stylize($(this));
});
}
*/
}
}
};
xn.helper = {
createUrl: function(uri) {
return xn.config.baseUrl + 'index.php/' + uri;
},
dataUrl: function(uri) {
return xn.config.baseUrl + 'data/' + uri;
},
themeUrl: function(uri) {
return xn.config.baseUrl + 'themes/default/' + uri;
},
/* Move footer to always on bottom. ps: put this after stylize */
resize: function(evt) {
var windowHeight = $('body').innerHeight();
var footer = $('#layout-footer');
footer.css('height', 'auto');
var layoutHeight = $('#layout-body').outerHeight();
if (windowHeight > layoutHeight) {
var footerHeight = windowHeight - layoutHeight;
footer.height(footerHeight);
}
$(".layout-flexible .fifths").css ("width", function () {
return "" + ($(this).parent().width() / 5) + "px";
});
$(".layout-flexible .quarter").css ("width", function () {
return "" + ($(this).parent().width() / 4) + "px";
});
$(".layout-flexible .thirds").css ("width", function () {
return "" + ($(this).parent().width() / 3) + "px";
});
$(".layout-flexible .half").css ("width", function () {
return "" + ($(this).parent().width() / 2) + "px";
});
$(".layout-flexible .auto").css ("width", function () {
var allwidth = 0;
$(this).siblings().each(function(i){
console.log ($(this).width ());
allwidth += $(this).width ();
});
return "" + ($(this).parent().width() - allwidth) + "px";
});
},
stylize: function(selector) {
if (typeof(selector) == 'undefined') {
selector = 'body';
}
/* Add common odd, even, first, last and hover */
$(selector).find("*").hover(function () {
$(this).addClass("hover");
}, function () {
$(this).removeClass("hover");
$(this).removeClass('pressed');
}).focus(function() {
$(this).addClass('focus');
}).blur(function() {
$(this).removeClass('focus');
}).mousedown(function(){
$(this).addClass('pressed');
});
$(selector).find(".tab a:first-child").addClass("first");
$(selector).find(".tab a:last-child").addClass("last");
$(selector).find("input").addClass(function () {
return $(this).attr("type").toLowerCase();
});
$(selector).find("select").addClass("select");
$(selector).find("select[multiple]").addClass("multiple");
$(selector).find("table > tr:nth-child(odd),ul > li:nth-child(odd), ol > li:nth-child(odd), .list > .comment:nth-child(odd)").addClass("odd");
$(selector).find("table > tr:nth-child(even),ul > li:nth-child(even), ol > li:nth-child(even), .list > .comment:nth-child(even)").addClass("even");
$(selector).find("ul > li:first-child, ol > li:first-child, .list > .comment:first-child, div > .button:first-child").addClass("first");
$(selector).find("ul > li:last-child, ol > li:last-child, .list > .comment:last-child, div > .button:last-child").addClass("last");
$(selector).find("[class^=blocks_] > div.block:first-child").addClass("first");
$(selector).find("[class^=blocks_] > div.block:last-child").addClass("last");
$(selector).find("[class^=grid] tr").removeClass("first last even odd");
$(selector).find("[class^=grid] tr:first-child").addClass ("first");
$(selector).find("[class^=grid] tr:last-child").addClass ("last");
$(selector).find("[class^=grid] tr:nth-child(odd)").addClass ("even");
$(selector).find("[class^=grid] tr:nth-child(even)").addClass ("odd");
$(selector).find("[class^=grid] tr:first-child td:first-child").addClass ("first");
$(selector).find("[class^=grid] tr:first-child td:last-child").addClass ("last");
$(selector).find("[class^=grid] tr:first-child td:nth-child(odd)").addClass ("even");
$(selector).find("[class^=grid] tr:first-child td:nth-child(even)").addClass ("odd");
$(selector).find("input[type='text'], input[type='password'], input[type='checkbox'], input[type='radio'], textarea").uniform();
$(selector).find("a[title!=''], img[title!=''], div[title!='']").tooltip();
/* Self add button class based on it's content */
$(selector).find(".button").wrapInner ("<span />");
$(selector).find(".button > span").addClass(function (){
return "" + $(this).text().toLowerCase();
});
$(selector).find(".top-nav li").addClass(function (){
return "icn-" + $(this).children("a").text().toLowerCase();
});
$(selector).find('input.date').dateinput({
lang: 'id',
format: 'dd/mm/yyyy',
selectors: true,
min: '1970-01-01',
yearRange: [-50, 50],
offset: [3, 0],
speed: 'fast',
change: function(evt) {
try {
var isoDate = this.getValue('yyyy-mm-dd');
var input = $(this.getInput());
var hidden = input.parent().find('.hidden-val');
hidden.val(isoDate);
} catch(e) {}
}
});
$(selector).find(".layout-flexible > div").wrapInner ("<div class='wrap' />");
/* HTML5 Input's Placeholder for older browser */
// $(selector).find('[placeholder]').focus(function() {
// var input = $(this);
// if (input.val() == input.attr('placeholder')) {
// input.val('');
// input.removeClass('placeholder');
// }
// }).blur(function() {
// var input = $(this);
// if (input.val() === '' || input.val() == input.attr('placeholder')) {
// input.addClass('placeholder');
// input.val(input.attr('placeholder'));
// }
// }).blur();
// $(selector).find('[placeholder]').parents('form').submit(function() {
// $(this).find('[placeholder]').each(function() {
// var input = $(this);
// if (input.val() == input.attr('placeholder')) {
// input.val('');
// }
// });
// });
$(selector).find('input.number').keypress(function(evt, a) {
if (!(evt.charCode >= 48 && evt.charCode <= 57) && evt.charCode != 13) {
evt.preventDefault();
}
});
$(selector).find('input.phone_number').keypress(function(evt, a) {
if (!(evt.charCode >= 48 && evt.charCode <= 57) && evt.charCode != 13 && evt.charCode != 43) {
evt.preventDefault();
}
});
$(selector).find('input.regex-val').keypress(function(evt, a) {
s = evt.which | evt.charCode | evt.keyCode;
if (s == 8 || s == 46 || s == 37 || s == 38 || s == 39 || s == 40 || s == 9) {
return true;
}
var str = $(this).val() + String.fromCharCode(evt.charCode);
var reg = new RegExp($(this).attr('data-regex'));
var s = str.search(reg);
if (s == -1) {
evt.preventDefault();
return false;
}
});
$(selector).find('.cancel').click(function(evt) {
if ($(this).parents('#fancybox-inner').length > 0) {
evt.preventDefault();
$.fancybox.close();
return false;
}
});
$(selector).find('a.mass-action').each(function() {
$(this).attr('data-href', $(this).attr('href'));
}).click(function(evt) {
var href = $(this).attr('data-href');
var selectedList = [];
$('table.grid').find('tr.grid_row *[checked]').parents('tr').each(function(index, node) {
if (selectedList[0] != $(node).attr('data-ref')) {
selectedList.push($(node).attr('data-ref'));
}
});
$(this).attr('data-selected', selectedList.join(','));
$(this).attr('href', href + '/' + selectedList.join(','));
if (selectedList.join(',') === '') {
$.fancybox('<div class="error">No selected record!</div>');
evt.preventDefault();
return false;
}
return true;
});
$(selector).find("a.msgbox").fancybox (xn.config.fancyOptions);
try {
var ciprofiler = $('#codeigniter_profiler');
ciprofiler.detach();
$(selector).find("#profiler_btn").click(function(evt) {
$.fancybox('<div id="complete_profiler" style="width: 800px; height: 400px; overflow: auto;"></div>', {
'width': 853,
'height': 510,
'scrolling': 'none',
'overlayColor': '#001',
'overlayOpacity': 0.75,
'centerOnScroll': true,
'onComplete': function() {
ciprofiler.appendTo($('#complete_profiler'));
},
'onClosed': function () {
$('#complete_profiler').remove();
}
});
return evt.preventDefault();
});
} catch (e) {}
$.fancybox.resize ();
$.fancybox.center ();
},
labelize: function(selector) {
if (typeof(selector) == 'undefined') {
selector = 'body';
}
var width = 0;
$(selector).find('label').each(function() {
if (width < $(this).width()) {
width = $(this).width();
}
});
$(selector).find('label').width(width);
},
fancyformify: function(selector) {
if (typeof(selector) == 'undefined') {
selector = 'body';
}
$(selector).find('form.ajaxform').ajaxForm ({
target: '#fancybox-inner',
beforeSubmit: function(arr, $form, options) {
},
success: function (value) {
if (value === true || value == 'true') {
$.fancybox.close();
} else {
xn.helper.stylize(selector);
xn.helper.fancyformify(selector);
}
},
error: function() {
}
});
}
};
$.tools.dateinput.localize("id", {
months: 'Januari,Februari,Maret,April,May,June,July,August,September,October,November,December',
shortMonths: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec',
days: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday',
shortDays: 'Mgg,Sen,Sel,Rab,Kam,Jum,Sab'
});
$(function() {
$('script[data-xn-config]').each(function() {
var x = '[{' + $(this).attr('data-xn-config') + '}]';
$.extend(xn.config, eval(x)[0]);
});
var loading = $('<div id="loading"></div>');
$('body').prepend(loading);
loading.bind("ajaxStart", function(){
$(this).css({
'left': ($(window).width() - loading.width()) / 2,
'top': ($(window).height() - loading.height()) / 2
}).show();
}).bind("ajaxStop", function(){
$(this).hide();
});
$('.submenu').width($('.submenu .container').width());
$('.error, .warn, .info').addClass("pop-message").wrapInner('<div class="content"><div class="text"></div><a href="#" class="close">x</a></div>');
$('.close').click (function () {
$(this).parent().fadeOut("fast");
return false;
});
// Detect browser for "racist" animation :P
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_explorer = navigator.userAgent.indexOf('MSIE') > -1;
var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
var is_opera = navigator.userAgent.indexOf("Presto") > -1;
$('#layout.layout.login').wrapInner('<div class="cloud4"><div class="cloud5"><div class="cloud6"></div></div></div>');
if (is_chrome) {
$("body").addClass ("chrome");
} else {
$('#layout.layout.login').wrapInner('<div class="cloud1"><div class="cloud2"><div class="cloud3"></div></div></div>');
if (is_safari) {
$("body").addClass ("safari");
} else if (is_firefox) {
$("body").addClass ("firefox");
} else if (is_opera) {
$("body").addClass ("opera");
} else {
$("body").addClass ("other");
}
}
$('body').css("opacity", "1");
$('#layout').fadeIn('slow');
xn.helper.stylize('body');
$(window).resize(function () {
xn.helper.resize();
});
xn.helper.resize();
});
var konami = "38,38,40,40,37,39,37,39,66,65".split(',');
var keyIndex = 0;
$(document).keydown(function(ev) {
if (konami[keyIndex] == ev.keyCode) keyIndex++; else keyIndex = 0;
if (keyIndex == konami.length) {
$.fancybox('<div id="konamicode" style="width: 853px; height: 510px;"></div>', {
'width': 853,
'height': 510,
'scrolling': 'none',
'overlayColor': '#000000',
'overlayOpacity': 0.75,
'centerOnScroll': true,
'onComplete': function() {
},
'onClosed': function () {
$('.even').addClass ('rotate2');
$('.odd').addClass ('rotate-2');
$('#konamicode').remove ();
}
});
keyIndex = 0;
}
});
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[\-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date();
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "dd/mm/yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",
xinixDate: "ddd, mmm d yyyy",
xinixTime: "h:MM:ss TT"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
}; |
import { getUrlParam,renderData,getMenuList } from './common';
$(function () {
getMenuList();//根据角色获取左侧栏手风琴列表
var roles = getUrlParam('roles');
$('.linkUrl').each(function(index,ele){
var url = $(this).attr('href') + '?roles=' + roles;
$(this).attr('href',url);
});
}); |
define(function(require) {
'use strict';
var Backbone = require('lib/backbone'),
$ = require('lib/jquery'),
BuildTable = require('lib/cubetable'),
TablePView;
TablePView = Backbone.View.extend({
el: '.JpreivewTable',
events: {
'click .preview-table th span': 'sortData'
},
initialize: function() {
Backbone.on('fillPreviewTable', this.JSON2HTML, this);
},
render:function(){
this.$el.html(this.toHtml());
return this;
},
sortData: function(e) {
var $currentEl = $(e.currentTarget);
this.drawChart.sort($currentEl.attr("code"));
this.render();
},
JSON2HTML: function(data) {
this.drawChart = new BuildTable();
this.drawChart.CreateTable(data);
this.render();
},
toHtml: function() {
var datasort = this.drawChart.sort();
var sortClass1 = "";
if (!$.isEmptyObject(datasort)) {
if (datasort.code == this.drawChart.RowCode()) {
sortClass1 = datasort.ifasc ? "up" : "down";
}
}
var str1 = "<table class='preview-table table table-bordered table-striped' cellspacing='0' cellpadding='0' width='100%'><thead><tr class='tr-title table-th-bg'>";
str1 += "<th style='text-align:center;'><strong>" + this.drawChart.getCaption() + "</strong><span class='" + sortClass1 + "' code='" + this.drawChart.RowCode() + "'></span></th>";
var collist = this.drawChart.getColList();
var rowlist = this.drawChart.getRowList();
var datatb = this.drawChart.getDataTable();
var memolist = this.drawChart.getMemoList();
var iftu = this.drawChart.setTu();
if (iftu) {
str1 += "<th> </th>";
}
for (var i = 0; i < collist.length; i++) {
if (collist[i]["ifhide"] != true) {
var sortClass2 = "",
redClass = "";
if (!$.isEmptyObject(datasort)) {
if (datasort.code == collist[i]["code"]) {
sortClass2 = datasort.ifasc ? "up" : "down";
}
}
if (collist[i]["ifjisuan"]) {
redClass = "red";
}
str1 += "<th class='" + redClass + "'>";
if (this.drawChart.ColCode() == "zb") {
var unitStr = "";
if (collist[i]["unitname"] != "") {
unitStr = "(" + collist[i]["unitname"] + ")";
}
str1 += "<strong>" + collist[i]["cname"] + unitStr + "</strong>";
} else {
str1 += "<strong>" + collist[i]["cname"] + "</strong>";
}
str1 += "<span class='" + sortClass2 + "' code='" + collist[i]["code"] + "'></span></th>";
}
}
str1 += "</tr>";
if (iftu) {
str1 += "<tr><th></th><th></th>";
for (var i = 0; i < collist.length; i++) {
if (collist[i]["ifhide"] != true) {
var c1 = "checked='checked'";
if (collist[i]["ifchecked"] != true) {
c1 = "";
}
str1 += "<th><input class='colCheckbox' code='" + collist[i]["code"] + "' type='checkbox' " + c1 + " /></th>";
}
}
str1 += "</tr>";
}
str1 += "</thead><tbody>";
for (var i = 0; i < rowlist.length; i++) {
if (rowlist[i]["ifhide"] == true) {
continue;
}
var redClass2 = "";
if (rowlist[i]["ifjisuan"]) {
redClass2 = "red";
}
str1 += "<tr><td class='" + redClass2 + "'>";
if (this.drawChart.RowCode() == "zb") {
var unitStr = "";
if (rowlist[i]["unitname"] != "") {
unitStr = "(" + rowlist[i]["unitname"] + ")";
}
str1 += rowlist[i]["cname"] + unitStr + "</td>";
} else {
str1 += rowlist[i]["cname"] + "</td>";
}
if (iftu) {
var c1 = "checked='checked'";
if (rowlist[i]["ifchecked"] != true) {
c1 = "";
}
str1 += "<td><input class='rowCheckbox' code='" + rowlist[i]["code"] + "' type='checkbox' " + c1 + " /></td>";
}
var dr1 = datatb[rowlist[i]["id"]];
if (dr1 != null || dr1 != undefined) {
for (var j = 0; j < dr1.length; j++) {
if (collist[j]["ifhide"] != true) {
var selClass = "";
if (collist[j]["ifchecked"] && rowlist[i]["ifchecked"]) {
selClass = "l t";
} else if (collist[j]["ifchecked"] && !rowlist[i]["ifchecked"]) {
selClass = "t";
} else if (!collist[j]["ifchecked"] && rowlist[i]["ifchecked"]) {
selClass = "l";
}
if (rowlist[i]["ifjisuan"] || collist[j]["ifjisuan"]) {
selClass += " red";
}
//单位错误标红
/*if(dr1[j]["ifuniterr"]){
selClass += " red";
}*/
var t = "";
if (dr1[j]["memo"] && dr1[j]["memo"] != "") {
selClass += " rote";
t = dr1[j]["memo"];
}
str1 += "<td align='right' class='" + selClass + "' title='" + t + "'>" + dr1[j]["strdata"] + "</td>";
}
}
} else {
for (var j = 0; j < collist.length; j++) {
str1 += "<td></td>";
}
}
str1 += "</tr>";
}
str1 += "</table>";
if (memolist.length > 0) {
var expshow = "<div class='expShow'><div class='zhu'>注:</div><div class='explist'>";
if (memolist.length == 1) {
expshow += '<dl><dd>' + memolist[0] + '</dd></dl>';
} else {
for (var i = 0; i < memolist.length; i++) {
expshow += '<dl><dt>' + (i + 1) + '.</dt><dd>' + memolist[i] + '</dd></dl>';
}
}
expshow += "</div></div>";
$(".table-container").next().remove();
$(".table-container").after(expshow);
} else {
$(".table-container").next().remove();
}
return str1;
}
});
return TablePView;
}); |
var logdir = require('../');
var test = require('tap').test;
var fs = require('fs');
var path = require('path');
var through = require('through');
var os = require('os');
var mkdirp = require('mkdirp');
var tmpdir = path.join(os.tmpDir(), 'logdir-test', String(Math.random()));
mkdirp.sync(tmpdir);
var ld = logdir(tmpdir);
var a = ld.createWriteStream('a');
var b = ld.createWriteStream('b');
test('setup', function (t) {
var xs = [ 'aaa', 'bbb', 'AAA', 'ccc', 'BBB', 'CCC', 'ddd', 'DDD' ];
(function shift () {
if (xs.length === 0) return t.end();
var x = xs.shift();
if (x.toUpperCase() === x) a.write(x + '\n')
else b.write(x + '\n')
setTimeout(shift, 25);
})();
});
test('slice', function (t) {
t.plan(1);
var lines = [];
ld.open([ 'a', 'b' ]).slice(-5).pipe(through(write, end));
function write (line) {
lines.push(line);
}
function end () {
t.deepEqual(lines.map(function (line) {
return line.replace(/^\S+\s\d+ /, '');
}), [ 'ccc\n', 'BBB\n', 'CCC\n', 'ddd\n', 'DDD\n' ]);
}
});
test('follow', function (t) {
t.plan(1);
var lines = [];
var s = ld.open([ 'a', 'b' ]).follow(-5);
s.pipe(through(write, end));
function write (line) {
lines.push(line);
if (lines.length === 5) {
t.deepEqual(
lines.map(strip),
[ 'ccc\n', 'BBB\n', 'CCC\n', 'ddd\n', 'DDD\n' ]
);
a.write('xyz\n');
setTimeout(function () { b.write('XYZ\n') }, 50);
setTimeout(function () { s.close() }, 50);
}
}
function end () {
t.deepEqual(
lines.slice(-2).map(strip),
[ 'xyz\n', 'XYZ\n' ]
);
}
});
test('teardown', function (t) {
a.end();
b.end();
t.end();
});
function strip (line) {
return line.replace(/^\S+\s\d+ /, '');
}
|
export default function SocialAuthController($state, $cookies, Auth) {
"ngInject";
var token = $cookies.get('social-authentication');
Auth.loginWithToken(token, false).then(function () {
$cookies.remove('social-authentication');
Auth.authorize(true);
}, function () {
$state.go('social-register', {'success': 'false'});
});
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// Depends on jsonlint.js from https://github.com/zaach/jsonlint
// declare global: jsonlint
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.registerHelper("lint", "gherkin", function(text) {
var found = [];
var parser = new Gherkin.Parser();
try { parser.parse(text, new Gherkin.TokenMatcher('en')); }
catch (e) {
for (var err in e.errors){
err = e.errors[err];
var loc = err.location;
found.push({
from: CodeMirror.Pos(loc.line - 1, loc.column),
to: CodeMirror.Pos(loc.line - 1, loc.column),
message: err.message
});
}
}
return found;
});
});
|
import styled from 'styled-components';
import * as defaultTheme from './default-theme';
import themeProp from '../utils/theme';
import { fontSizeSm, borderRadius } from '../utils/defaultTheme';
import arrowPlacement from './arrowPlacement';
const {
zIndexTooltip,
tooltipMaxWidth,
tooltipBg,
tooltipOpacity,
tooltipPaddingX,
tooltipPaddingY,
tooltipMargin,
tooltipColor
} = defaultTheme;
const StytledTooltip = styled.div`
position: absolute;
z-index: ${themeProp('zIndexTooltip', zIndexTooltip)};
display: block;
margin: ${themeProp('tooltipMargin', tooltipMargin)};
background-color: ${themeProp('tooltipBg', tooltipBg)};
opacity: ${themeProp('tooltipOpacity', tooltipOpacity)};
font-size: ${themeProp('fontSizeSm', fontSizeSm)};
border-radius: ${themeProp('borderRadius', borderRadius)};
div:first-child {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
${props => arrowPlacement(props)};
div:last-child {
max-width: ${themeProp('tooltipMaxWidth', tooltipMaxWidth)};
padding: ${themeProp('tooltipPaddingY', tooltipPaddingY)}
${themeProp('tooltipPaddingX', tooltipPaddingX)};
color: ${themeProp('tooltipColor', tooltipColor)};
text-align: center;
}
`;
export default StytledTooltip;
|
const express = require( 'express' ),
router = express.Router(),
models = require( './../models/' ),
utils = require( './../utils/' ),
bodyParser = require( 'body-parser' ),
fs = require( 'fs' ),
log = require( './../utils/log' )
router.use( bodyParser.json() )
router.use( bodyParser.urlencoded( { 'extended' : false } ) )
router.get( '/', ( req, res ) => res.render( 'administration/logger' ) )
router.post( '/getLog', ( req, res ) => {
var basePathLog = process.env.BASE_PATH_LOG,
baseNameLog = process.env.BASE_NAME_LOG,
data = req.body
var month = 5,
year = 2016
var filename = baseNameLog
.replace( 'year', year )
.replace( 'month', month ),
pathLog = basePathLog + filename
fs.readFile( pathLog, 'utf8', function ( error, content ) {
if ( error ) console.log( error )
var data = JSON.parse( content )
return res.json( data )
} )
} )
module.exports = router
|
export class AgendaDay {
constructor(day, agenda, totalRooms) {
this.day = day;
this.agenda = agenda;
this.totalRooms = totalRooms;
}
} |
'use strict';
describe('bb.version module', function() {
beforeEach(module('bb.version'));
describe('app-version directive', function() {
it('should print current version', function() {
module(function($provide) {
$provide.value('version', 'TEST_VER');
});
inject(function($compile, $rootScope) {
var element = $compile('<span app-version></span>')($rootScope);
expect(element.text()).toEqual('TEST_VER');
});
});
});
});
|
(angular => {
'use strict';
angular.module('tubular.services')
.controller('GenericPopupController', [
'$rootScope',
'$scope',
'$uibModalInstance',
'model',
'gridScope',
function (
$rootScope,
$scope,
$uibModalInstance,
model,
gridScope) {
$scope.Model = model;
$scope.savePopup = (innerModel, forceUpdate) => {
innerModel = innerModel || $scope.Model;
// If we have nothing to save and it's not a new record, just close
if (!forceUpdate && !innerModel.$isNew && !innerModel.$hasChanges()) {
$scope.closePopup();
return null;
}
return gridScope.saveRow(innerModel, forceUpdate).then(() => $uibModalInstance.close());
};
$scope.closePopup = () => {
if (angular.isDefined($scope.Model.revertChanges)) {
$scope.Model.revertChanges();
}
$uibModalInstance.close();
};
$scope.onSave = () => {
$scope.closePopup();
gridScope.retrieveData();
};
}
]);
})(angular); |
import React from 'react';
import ReactDOM from 'react-dom';
class DoneButton extends React.Component
{
render()
{
if(this.props.enabled)
{
return (
<h4><a onClick={this.props.onClick}>Done</a></h4>
);
}
else
{
var disabledStyles =
{
color: '#666666'
};
return (
<h4 style={disabledStyles}>Done</h4>
);
}
}
}
export default DoneButton |
'use strict';
objectToDisplay = objectToDisplay || {};
QUnit = QUnit || {};
var core_test_object = {
myHTML : "<a href='http://example.com'>Things and Stuff</a>",
text : "<a href='http://example.com'>This should just be text and not an element</a>",
myOtherObj : {
innerObject1 : "WOO 1 Object",
innerObject2 : "tcejbO 2 OOW"
},
whatwasthatbuttonsupposedtosay : "Test",
doiknow : true,
buttonnamingoptions : ["Thingy", "Tap", "Press", "Click", "Hit", "Smack", "Push", "Just use the button"],
somecustomdata : { data: "this is custom data", title : "This should be bold"}
};
QUnit.test("CORE: Text", function (assert) {
objectToDisplay.fillElement(document.getElementById("container"), core_test_object);
assert.equal(document.getElementById("textTest").children.length, 0);
assert.equal(document.getElementById("textTest").textContent, "<a href='http://example.com'>This should just be text and not an element</a>");
});
QUnit.test("CORE: Text - Handlers Removed", function (assert) {
assert.throws(function () {
objectToDisplay.fillElement(document.getElementById("container"), core_test_object, {useDefaultHandlers: false});
}, new Error("No handlers are defined."), "With no handlers there should be an error");
});
QUnit.test("CORE: HTML", function (assert) {
objectToDisplay.fillElement(document.getElementById("container"), core_test_object);
assert.equal(document.getElementById("htmlTest").children.length, 1);
assert.equal(document.getElementById("htmlTest").children[0].href, "http://example.com/");
});
QUnit.test("CORE: Nested", function (assert) {
objectToDisplay.fillElement(document.getElementById("container"), core_test_object);
assert.equal(document.getElementById("n_e_e1").textContent, "WOO 1 Object");
assert.equal(document.getElementById("n_e_e2").textContent, "tcejbO 2 OOW");
});
QUnit.test("CORE: Custom Handler Element(input[type=button])", function (assert) {
var handlers = [];
handlers.push({
desirablenessOf : function (el) {
if (el.tagName === "INPUT") {
if (el.type === "button") {
return 5;
} else if (el.type === "checkbox") {
return 5;
}
}
},
handle : function (el, d) {
if (el.type === "button") {
el.value = d;
} else if (el.type === "checkbox") {
el.checked = d;
}
}
});
objectToDisplay.fillElement(document.getElementById("container"), core_test_object, { handlers : handlers});
assert.equal(document.querySelector('input[data-display="whatwasthatbuttonsupposedtosay"]').value, "Test");
});
QUnit.test("CORE: Custom Handler Element(input[type=checkbox])", function (assert) {
var handlers = [];
handlers.push({
desirablenessOf : function (el) {
if (el.tagName === "INPUT") {
if (el.type === "button") {
return 5;
} else if (el.type === "checkbox") {
return 5;
}
}
},
handle : function (el, d) {
if (el.type === "button") {
el.value = d;
} else if (el.type === "checkbox") {
el.checked = d;
}
}
});
objectToDisplay.fillElement(document.getElementById("container"), core_test_object, { handlers : handlers});
assert.equal(document.querySelector('input[data-display="doiknow"]').checked, true);
});
QUnit.test("CORE: Custom Handler Element(select)", function (assert) {
var handlers = [];
handlers.push({
desirablenessOf : function (el) {
if (el.tagName === "SELECT") {
return 25;
}
},
handle : function (el, d) {
d.forEach(function (e) {
var o = document.createElement("option");
o.value = e;
el.appendChild(o);
});
}
});
objectToDisplay.fillElement(document.getElementById("container"), core_test_object, { handlers : handlers});
assert.equal(document.querySelector('select[data-display="buttonnamingoptions"]').children.length, 8);
});
QUnit.test("CORE: Custom Handler Type(simpleCustom)", function (assert) {
var handlers = [];
handlers.push({
desirablenessOf : function (el) {
if (el.dataset.displayType === "simpleCustom") {
return 10;
}
},
handle : function (el, d) {
var b = document.createElement("B");
b.textContent = d.title;
el.textContent = d.data;
el.insertBefore(b, el.firstChild);
}
});
objectToDisplay.fillElement(document.getElementById("container"), core_test_object, { handlers : handlers});
assert.equal(document.querySelector('span[data-display-type="simpleCustom"]').children.length, 1);
assert.equal(document.querySelector('span[data-display-type="simpleCustom"]').children[0].textContent, "This should be bold");
assert.equal(document.querySelector('span[data-display-type="simpleCustom"]').innerHTML, "<b>This should be bold</b>this is custom data");
});
QUnit.test("IGNORE: (OFF) Element Not Found", function (assert) {
assert.throws(function () {
objectToDisplay.fillElement(document.getElementById("container"), core_test_object, { ignoreMissing : false});
}, new Error("Property \"thisismissing\" was not found!"), "Element not found throws if not ignored");
});
QUnit.test("ObjectMappingFunction: Set", function (assert) {
objectToDisplay.fillElement(document.getElementById("container"), core_test_object,
{ objectMappingFunction : function (obj, req) {
if (req === "thisdoesntactualmapautomatically") {
return obj.doiknow;
} else {
return undefined;
}
}
});
assert.equal(document.getElementById("htmlTest").textContent, "");
assert.equal(document.querySelector('span[data-display="thisdoesntactualmapautomatically"]').textContent, "true");
}); |
'use strict';
angular.module('stickyApp')
.factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) {
var currentUser = {};
if($cookieStore.get('token')) {
currentUser = User.get();
}
return {
/**
* Authenticate user and save token
*
* @param {Object} user - login info
* @param {Function} callback - optional
* @return {Promise}
*/
login: function(user, callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.post('/auth/local', {
email: user.email,
password: user.password
}).
success(function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
deferred.resolve(data);
return cb();
}).
error(function(err) {
this.logout();
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
/**
* Delete access token and user info
*
* @param {Function}
*/
logout: function() {
$cookieStore.remove('token');
currentUser = {};
},
/**
* Create a new user
*
* @param {Object} user - user info
* @param {Function} callback - optional
* @return {Promise}
*/
createUser: function(user, callback) {
var cb = callback || angular.noop;
return User.save(user,
function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
return cb(user);
},
function(err) {
this.logout();
return cb(err);
}.bind(this)).$promise;
},
/**
* Change password
*
* @param {String} oldPassword
* @param {String} newPassword
* @param {Function} callback - optional
* @return {Promise}
*/
changePassword: function(oldPassword, newPassword, callback) {
var cb = callback || angular.noop;
return User.changePassword({ id: currentUser._id }, {
oldPassword: oldPassword,
newPassword: newPassword
}, function(user) {
return cb(user);
}, function(err) {
return cb(err);
}).$promise;
},
/**
* Gets all available info on authenticated user
*
* @return {Object} user
*/
getCurrentUser: function() {
return currentUser;
},
/**
* Check if a user is logged in
*
* @return {Boolean}
*/
isLoggedIn: function() {
return currentUser.hasOwnProperty('role');
},
/**
* Waits for currentUser to resolve before checking if user is logged in
*/
isLoggedInAsync: function(cb) {
if(currentUser.hasOwnProperty('$promise')) {
currentUser.$promise.then(function() {
cb(true);
}).catch(function() {
cb(false);
});
} else if(currentUser.hasOwnProperty('role')) {
cb(true);
} else {
cb(false);
}
},
/**
* Check if a user is an admin
*
* @return {Boolean}
*/
isAdmin: function() {
return currentUser.role === 'admin';
},
/**
* Get auth token
*/
getToken: function() {
return $cookieStore.get('token');
}
};
});
|
describe('jqLite', function() {
var scope, a, b, c;
beforeEach(module(provideLog));
beforeEach(function() {
a = jqLite('<div>A</div>')[0];
b = jqLite('<div>B</div>')[0];
c = jqLite('<div>C</div>')[0];
});
beforeEach(inject(function($rootScope) {
scope = $rootScope;
this.addMatchers({
toJqEqual: function(expected) {
var msg = "Unequal length";
this.message = function() {return msg;};
var value = this.actual && expected && this.actual.length == expected.length;
for (var i = 0; value && i < expected.length; i++) {
var actual = jqLite(this.actual[i])[0];
var expect = jqLite(expected[i])[0];
value = value && equals(expect, actual);
msg = "Not equal at index: " + i
+ " - Expected: " + expect
+ " - Actual: " + actual;
}
return value;
}
});
}));
afterEach(function() {
dealoc(a);
dealoc(b);
dealoc(c);
});
it('should be jqLite when jqLiteMode is on, otherwise jQuery', function() {
expect(jqLite).toBe(_jqLiteMode ? JQLite : _jQuery);
});
describe('construction', function() {
it('should allow construction with text node', function() {
var text = a.firstChild;
var selected = jqLite(text);
expect(selected.length).toEqual(1);
expect(selected[0]).toEqual(text);
});
it('should allow construction with html', function() {
var nodes = jqLite('<div>1</div><span>2</span>');
expect(nodes[0].parentNode).toBeDefined();
expect(nodes[0].parentNode.nodeType).toBe(11); /** Document Fragment **/;
expect(nodes[0].parentNode).toBe(nodes[1].parentNode);
expect(nodes.length).toEqual(2);
expect(nodes[0].innerHTML).toEqual('1');
expect(nodes[1].innerHTML).toEqual('2');
});
it('should allow creation of comment tags', function() {
var nodes = jqLite('<!-- foo -->');
expect(nodes.length).toBe(1);
expect(nodes[0].nodeType).toBe(8);
});
it('should allow creation of script tags', function() {
var nodes = jqLite('<script></script>');
expect(nodes.length).toBe(1);
expect(nodes[0].tagName.toUpperCase()).toBe('SCRIPT');
});
it('should wrap document fragment', function() {
var fragment = jqLite(document.createDocumentFragment());
expect(fragment.length).toBe(1);
expect(fragment[0].nodeType).toBe(11);
});
});
describe('inheritedData', function() {
it('should retrieve data attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('myData', 'abc');
expect(element.inheritedData('myData')).toBe('abc');
dealoc(element);
});
it('should walk up the dom to find data', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('myData', 'abc');
expect(deepChild.inheritedData('myData')).toBe('abc');
dealoc(element);
});
it('should return undefined when no data was found', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
expect(deepChild.inheritedData('myData')).toBeFalsy();
dealoc(element);
});
it('should work with the child html element instead if the current element is the document obj',
function() {
var item = {},
doc = jqLite(document),
html = doc.find('html');
html.data('item', item);
expect(doc.inheritedData('item')).toBe(item);
expect(html.inheritedData('item')).toBe(item);
dealoc(doc);
}
);
it('should return null values', function () {
var ul = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>'),
li = ul.find('li'),
b = li.find('b');
ul.data('foo', 'bar');
li.data('foo', null);
expect(b.inheritedData('foo')).toBe(null);
expect(li.inheritedData('foo')).toBe(null);
expect(ul.inheritedData('foo')).toBe('bar');
dealoc(ul);
});
});
describe('scope', function() {
it('should retrieve scope attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('$scope', scope);
expect(element.scope()).toBe(scope);
dealoc(element);
});
it('should retrieve scope attached to the html element if its requested on the document',
function() {
var doc = jqLite(document),
html = doc.find('html'),
scope = {};
html.data('$scope', scope);
expect(doc.scope()).toBe(scope);
expect(html.scope()).toBe(scope);
dealoc(doc);
});
it('should walk up the dom to find scope', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('$scope', scope);
expect(deepChild.scope()).toBe(scope);
dealoc(element);
});
it('should return undefined when no scope was found', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
expect(deepChild.scope()).toBeFalsy();
dealoc(element);
});
});
describe('injector', function() {
it('should retrieve injector attached to the current element or its parent', function() {
var template = jqLite('<div><span></span></div>'),
span = template.children().eq(0),
injector = angular.bootstrap(template);
expect(span.injector()).toBe(injector);
dealoc(template);
});
it('should retrieve injector attached to the html element if its requested on document',
function() {
var doc = jqLite(document),
html = doc.find('html'),
injector = {};
html.data('$injector', injector);
expect(doc.injector()).toBe(injector);
expect(html.injector()).toBe(injector);
dealoc(doc);
});
it('should do nothing with a noncompiled template', function() {
var template = jqLite('<div><span></span></div>');
expect(template.injector()).toBeUndefined();
dealoc(template);
});
});
describe('controller', function() {
it('should retrieve controller attached to the current element or its parent', function() {
var div = jqLite('<div><span></span></div>'),
span = div.find('span');
div.data('$ngControllerController', 'ngController');
span.data('$otherController', 'other');
expect(span.controller()).toBe('ngController');
expect(span.controller('ngController')).toBe('ngController');
expect(span.controller('other')).toBe('other');
expect(div.controller()).toBe('ngController');
expect(div.controller('ngController')).toBe('ngController');
expect(div.controller('other')).toBe(undefined);
dealoc(div);
});
});
describe('data', function() {
it('should set and get and remove data', function() {
var selected = jqLite([a, b, c]);
expect(selected.data('prop')).toBeUndefined();
expect(selected.data('prop', 'value')).toBe(selected);
expect(selected.data('prop')).toBe('value');
expect(jqLite(a).data('prop')).toBe('value');
expect(jqLite(b).data('prop')).toBe('value');
expect(jqLite(c).data('prop')).toBe('value');
jqLite(a).data('prop', 'new value');
expect(jqLite(a).data('prop')).toBe('new value');
expect(selected.data('prop')).toBe('new value');
expect(jqLite(b).data('prop')).toBe('value');
expect(jqLite(c).data('prop')).toBe('value');
expect(selected.removeData('prop')).toBe(selected);
expect(jqLite(a).data('prop')).toBeUndefined();
expect(jqLite(b).data('prop')).toBeUndefined();
expect(jqLite(c).data('prop')).toBeUndefined();
});
it('should only remove the specified value when providing a property name to removeData', function () {
var selected = jqLite(a);
expect(selected.data('prop1')).toBeUndefined();
selected.data('prop1', 'value');
selected.data('prop2', 'doublevalue');
expect(selected.data('prop1')).toBe('value');
expect(selected.data('prop2')).toBe('doublevalue');
selected.removeData('prop1');
expect(selected.data('prop1')).toBeUndefined();
expect(selected.data('prop2')).toBe('doublevalue');
selected.removeData('prop2');
});
it('should emit $destroy event if element removed via remove()', function() {
var log = '';
var element = jqLite(a);
element.on('$destroy', function() {log+= 'destroy;';});
element.remove();
expect(log).toEqual('destroy;');
});
it('should emit $destroy event if an element is removed via html()', inject(function(log) {
var element = jqLite('<div><span>x</span></div>');
element.find('span').on('$destroy', log.fn('destroyed'));
element.html('');
expect(element.html()).toBe('');
expect(log).toEqual('destroyed');
}));
it('should retrieve all data if called without params', function() {
var element = jqLite(a);
expect(element.data()).toEqual({});
element.data('foo', 'bar');
expect(element.data()).toEqual({foo: 'bar'});
element.data().baz = 'xxx';
expect(element.data()).toEqual({foo: 'bar', baz: 'xxx'});
});
it('should create a new data object if called without args', function() {
var element = jqLite(a),
data = element.data();
expect(data).toEqual({});
element.data('foo', 'bar');
expect(data).toEqual({foo: 'bar'});
});
it('should create a new data object if called with a single object arg', function() {
var element = jqLite(a),
newData = {foo: 'bar'};
element.data(newData);
expect(element.data()).toEqual({foo: 'bar'});
expect(element.data()).not.toBe(newData); // create a copy
});
it('should merge existing data object with a new one if called with a single object arg',
function() {
var element = jqLite(a);
element.data('existing', 'val');
expect(element.data()).toEqual({existing: 'val'});
var oldData = element.data(),
newData = {meLike: 'turtles', 'youLike': 'carrots'};
expect(element.data(newData)).toBe(element);
expect(element.data()).toEqual({meLike: 'turtles', youLike: 'carrots', existing: 'val'});
expect(element.data()).toBe(oldData); // merge into the old object
});
describe('data cleanup', function() {
it('should remove data on element removal', function() {
var div = jqLite('<div><span>text</span></div>'),
span = div.find('span');
span.data('name', 'angular');
span.remove();
expect(span.data('name')).toBeUndefined();
});
it('should remove event listeners on element removal', function() {
var div = jqLite('<div><span>text</span></div>'),
span = div.find('span'),
log = '';
span.on('click', function() { log+= 'click;'});
browserTrigger(span);
expect(log).toEqual('click;');
span.remove();
browserTrigger(span);
expect(log).toEqual('click;');
});
});
});
describe('attr', function() {
it('should read write and remove attr', function() {
var selector = jqLite([a, b]);
expect(selector.attr('prop', 'value')).toEqual(selector);
expect(jqLite(a).attr('prop')).toEqual('value');
expect(jqLite(b).attr('prop')).toEqual('value');
expect(selector.attr({'prop': 'new value'})).toEqual(selector);
expect(jqLite(a).attr('prop')).toEqual('new value');
expect(jqLite(b).attr('prop')).toEqual('new value');
jqLite(b).attr({'prop': 'new value 2'});
expect(jqLite(selector).attr('prop')).toEqual('new value');
expect(jqLite(b).attr('prop')).toEqual('new value 2');
selector.removeAttr('prop');
expect(jqLite(a).attr('prop')).toBeFalsy();
expect(jqLite(b).attr('prop')).toBeFalsy();
});
it('should read boolean attributes as strings', function() {
var select = jqLite('<select>');
expect(select.attr('multiple')).toBeUndefined();
expect(jqLite('<select multiple>').attr('multiple')).toBe('multiple');
expect(jqLite('<select multiple="">').attr('multiple')).toBe('multiple');
expect(jqLite('<select multiple="x">').attr('multiple')).toBe('multiple');
});
it('should add/remove boolean attributes', function() {
var select = jqLite('<select>');
select.attr('multiple', false);
expect(select.attr('multiple')).toBeUndefined();
select.attr('multiple', true);
expect(select.attr('multiple')).toBe('multiple');
});
it('should normalize the case of boolean attributes', function() {
var input = jqLite('<input readonly>');
expect(input.attr('readonly')).toBe('readonly');
expect(input.attr('readOnly')).toBe('readonly');
expect(input.attr('READONLY')).toBe('readonly');
input.attr('readonly', false);
// attr('readonly') fails in jQuery 1.6.4, so we have to bypass it
//expect(input.attr('readOnly')).toBeUndefined();
//expect(input.attr('readonly')).toBeUndefined();
if (msie < 9) {
expect(input[0].getAttribute('readonly')).toBe('');
} else {
expect(input[0].getAttribute('readonly')).toBe(null);
}
//expect('readOnly' in input[0].attributes).toBe(false);
input.attr('readOnly', 'READonly');
expect(input.attr('readonly')).toBe('readonly');
expect(input.attr('readOnly')).toBe('readonly');
});
it('should return undefined for non-existing attributes', function() {
var elm = jqLite('<div class="any">a</div>');
expect(elm.attr('non-existing')).toBeUndefined();
});
it('should return undefined for non-existing attributes on input', function() {
var elm = jqLite('<input>');
expect(elm.attr('readonly')).toBeUndefined();
expect(elm.attr('readOnly')).toBeUndefined();
expect(elm.attr('disabled')).toBeUndefined();
});
});
describe('prop', function() {
it('should read element property', function() {
var elm = jqLite('<div class="foo">a</div>');
expect(elm.prop('className')).toBe('foo');
});
it('should set element property to a value', function() {
var elm = jqLite('<div class="foo">a</div>');
elm.prop('className', 'bar');
expect(elm[0].className).toBe('bar');
expect(elm.prop('className')).toBe('bar');
});
it('should set boolean element property', function() {
var elm = jqLite('<input type="checkbox">');
expect(elm.prop('checked')).toBe(false);
elm.prop('checked', true);
expect(elm.prop('checked')).toBe(true);
elm.prop('checked', '');
expect(elm.prop('checked')).toBe(false);
elm.prop('checked', 'lala');
expect(elm.prop('checked')).toBe(true);
elm.prop('checked', null);
expect(elm.prop('checked')).toBe(false);
});
});
describe('class', function() {
describe('hasClass', function() {
it('should check class', function() {
var selector = jqLite([a, b]);
expect(selector.hasClass('abc')).toEqual(false);
});
it('should make sure that partial class is not checked as a subset', function() {
var selector = jqLite([a, b]);
selector.addClass('a');
selector.addClass('b');
selector.addClass('c');
expect(selector.addClass('abc')).toEqual(selector);
expect(selector.removeClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
expect(jqLite(a).hasClass('a')).toEqual(true);
expect(jqLite(a).hasClass('b')).toEqual(true);
expect(jqLite(a).hasClass('c')).toEqual(true);
});
});
describe('addClass', function() {
it('should allow adding of class', function() {
var selector = jqLite([a, b]);
expect(selector.addClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
});
it('should ignore falsy values', function() {
var jqA = jqLite(a);
expect(jqA[0].className).toBe('');
jqA.addClass(undefined);
expect(jqA[0].className).toBe('');
jqA.addClass(null);
expect(jqA[0].className).toBe('');
jqA.addClass(false);
expect(jqA[0].className).toBe('');
});
it('should allow multiple classes to be added in a single string', function() {
var jqA = jqLite(a);
expect(a.className).toBe('');
jqA.addClass('foo bar baz');
expect(a.className).toBe('foo bar baz');
});
it('should not add duplicate classes', function() {
var jqA = jqLite(a);
expect(a.className).toBe('');
a.className = 'foo';
jqA.addClass('foo');
expect(a.className).toBe('foo');
jqA.addClass('bar foo baz');
expect(a.className).toBe('foo bar baz');
});
});
describe('toggleClass', function() {
it('should allow toggling of class', function() {
var selector = jqLite([a, b]);
expect(selector.toggleClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
expect(selector.toggleClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
expect(selector.toggleClass('abc'), true).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
expect(selector.toggleClass('abc'), false).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
});
});
describe('removeClass', function() {
it('should allow removal of class', function() {
var selector = jqLite([a, b]);
expect(selector.addClass('abc')).toEqual(selector);
expect(selector.removeClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
});
it('should correctly remove middle class', function() {
var element = jqLite('<div class="foo bar baz"></div>');
expect(element.hasClass('bar')).toBe(true);
element.removeClass('bar');
expect(element.hasClass('foo')).toBe(true);
expect(element.hasClass('bar')).toBe(false);
expect(element.hasClass('baz')).toBe(true);
});
it('should remove multiple classes specified as one string', function() {
var jqA = jqLite(a);
a.className = 'foo bar baz';
jqA.removeClass('foo baz noexistent');
expect(a.className).toBe('bar');
});
});
});
describe('css', function() {
it('should set and read css', function() {
var selector = jqLite([a, b]);
expect(selector.css('margin', '1px')).toEqual(selector);
expect(jqLite(a).css('margin')).toEqual('1px');
expect(jqLite(b).css('margin')).toEqual('1px');
expect(selector.css({'margin': '2px'})).toEqual(selector);
expect(jqLite(a).css('margin')).toEqual('2px');
expect(jqLite(b).css('margin')).toEqual('2px');
jqLite(b).css({'margin': '3px'});
expect(jqLite(selector).css('margin')).toEqual('2px');
expect(jqLite(a).css('margin')).toEqual('2px');
expect(jqLite(b).css('margin')).toEqual('3px');
selector.css('margin', '');
if (msie <= 8) {
expect(jqLite(a).css('margin')).toBe('auto');
expect(jqLite(b).css('margin')).toBe('auto');
} else {
expect(jqLite(a).css('margin')).toBeFalsy();
expect(jqLite(b).css('margin')).toBeFalsy();
}
});
it('should set a bunch of css properties specified via an object', function() {
if (msie <= 8) {
expect(jqLite(a).css('margin')).toBe('auto');
expect(jqLite(a).css('padding')).toBe('0px');
expect(jqLite(a).css('border')).toBeUndefined();
} else {
expect(jqLite(a).css('margin')).toBeFalsy();
expect(jqLite(a).css('padding')).toBeFalsy();
expect(jqLite(a).css('border')).toBeFalsy();
}
jqLite(a).css({'margin': '1px', 'padding': '2px', 'border': ''});
expect(jqLite(a).css('margin')).toBe('1px');
expect(jqLite(a).css('padding')).toBe('2px');
expect(jqLite(a).css('border')).toBeFalsy();
});
it('should correctly handle dash-separated and camelCased properties', function() {
var jqA = jqLite(a);
expect(jqA.css('z-index')).toBeOneOf('', 'auto');
expect(jqA.css('zIndex')).toBeOneOf('', 'auto');
jqA.css({'zIndex':5});
expect(jqA.css('z-index')).toBeOneOf('5', 5);
expect(jqA.css('zIndex')).toBeOneOf('5', 5);
jqA.css({'z-index':7});
expect(jqA.css('z-index')).toBeOneOf('7', 7);
expect(jqA.css('zIndex')).toBeOneOf('7', 7);
});
});
describe('text', function() {
it('should return null on empty', function() {
expect(jqLite().length).toEqual(0);
expect(jqLite().text()).toEqual('');
});
it('should read/write value', function() {
var element = jqLite('<div>ab</div><span>c</span>');
expect(element.length).toEqual(2);
expect(element[0].innerHTML).toEqual('ab');
expect(element[1].innerHTML).toEqual('c');
expect(element.text()).toEqual('abc');
expect(element.text('xyz') == element).toBeTruthy();
expect(element.text()).toEqual('xyzxyz');
});
});
describe('val', function() {
it('should read, write value', function() {
var input = jqLite('<input type="text"/>');
expect(input.val('abc')).toEqual(input);
expect(input[0].value).toEqual('abc');
expect(input.val()).toEqual('abc');
});
it('should get an array of selected elements from a multi select', function () {
expect(jqLite(
'<select multiple>' +
'<option selected>test 1</option>' +
'<option selected>test 2</option>' +
'</select>').val()).toEqual(['test 1', 'test 2']);
expect(jqLite(
'<select multiple>' +
'<option selected>test 1</option>' +
'<option>test 2</option>' +
'</select>').val()).toEqual(['test 1']);
expect(jqLite(
'<select multiple>' +
'<option>test 1</option>' +
'<option>test 2</option>' +
'</select>').val()).toEqual(null);
});
});
describe('html', function() {
it('should return null on empty', function() {
expect(jqLite().length).toEqual(0);
expect(jqLite().html()).toEqual(null);
});
it('should read/write value', function() {
var element = jqLite('<div>abc</div>');
expect(element.length).toEqual(1);
expect(element[0].innerHTML).toEqual('abc');
expect(element.html()).toEqual('abc');
expect(element.html('xyz') == element).toBeTruthy();
expect(element.html()).toEqual('xyz');
});
});
describe('on', function() {
it('should bind to window on hashchange', function() {
if (jqLite.fn) return; // don't run in jQuery
var eventFn;
var window = {
document: {},
location: {},
alert: noop,
setInterval: noop,
length:10, // pretend you are an array
addEventListener: function(type, fn){
expect(type).toEqual('hashchange');
eventFn = fn;
},
removeEventListener: noop,
attachEvent: function(type, fn){
expect(type).toEqual('onhashchange');
eventFn = fn;
},
detachEvent: noop
};
var log;
var jWindow = jqLite(window).on('hashchange', function() {
log = 'works!';
});
eventFn({type: 'hashchange'});
expect(log).toEqual('works!');
dealoc(jWindow);
});
it('should bind to all elements and return functions', function() {
var selected = jqLite([a, b]);
var log = '';
expect(selected.on('click', function() {
log += 'click on: ' + jqLite(this).text() + ';';
})).toEqual(selected);
browserTrigger(a, 'click');
expect(log).toEqual('click on: A;');
browserTrigger(b, 'click');
expect(log).toEqual('click on: A;click on: B;');
});
it('should bind to all events separated by space', function() {
var elm = jqLite(a),
callback = jasmine.createSpy('callback');
elm.on('click keypress', callback);
elm.on('click', callback);
browserTrigger(a, 'click');
expect(callback).toHaveBeenCalled();
expect(callback.callCount).toBe(2);
callback.reset();
browserTrigger(a, 'keypress');
expect(callback).toHaveBeenCalled();
expect(callback.callCount).toBe(1);
});
it('should set event.target on IE', function() {
var elm = jqLite(a);
elm.on('click', function(event) {
expect(event.target).toBe(a);
});
browserTrigger(a, 'click');
});
it('should have event.isDefaultPrevented method', function() {
jqLite(a).on('click', function(e) {
expect(function() {
expect(e.isDefaultPrevented()).toBe(false);
e.preventDefault();
expect(e.isDefaultPrevented()).toBe(true);
}).not.toThrow();
});
browserTrigger(a, 'click');
});
describe('mouseenter-mouseleave', function() {
var root, parent, sibling, child, log;
beforeEach(function() {
log = '';
root = jqLite('<div>root<p>parent<span>child</span></p><ul></ul></div>');
parent = root.find('p');
sibling = root.find('ul');
child = parent.find('span');
parent.on('mouseenter', function() { log += 'parentEnter;'; });
parent.on('mouseleave', function() { log += 'parentLeave;'; });
child.on('mouseenter', function() { log += 'childEnter;'; });
child.on('mouseleave', function() { log += 'childLeave;'; });
});
afterEach(function() {
dealoc(root);
});
it('should fire mouseenter when coming from outside the browser window', function() {
if (window.jQuery) return;
var browserMoveTrigger = function(from, to){
var fireEvent = function(type, element, relatedTarget){
var msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
if (msie < 9){
var evnt = document.createEventObject();
evnt.srcElement = element;
evnt.relatedTarget = relatedTarget;
element.fireEvent('on' + type, evnt);
return;
};
var evnt = document.createEvent('MouseEvents'),
originalPreventDefault = evnt.preventDefault,
appWindow = window,
fakeProcessDefault = true,
finalProcessDefault;
evnt.preventDefault = function() {
fakeProcessDefault = false;
return originalPreventDefault.apply(evnt, arguments);
};
var x = 0, y = 0;
evnt.initMouseEvent(type, true, true, window, 0, x, y, x, y, false, false,
false, false, 0, relatedTarget);
element.dispatchEvent(evnt);
};
fireEvent('mouseout', from[0], to[0]);
fireEvent('mouseover', to[0], from[0]);
};
browserMoveTrigger(root, parent);
expect(log).toEqual('parentEnter;');
browserMoveTrigger(parent, child);
expect(log).toEqual('parentEnter;childEnter;');
browserMoveTrigger(child, parent);
expect(log).toEqual('parentEnter;childEnter;childLeave;');
browserMoveTrigger(parent, root);
expect(log).toEqual('parentEnter;childEnter;childLeave;parentLeave;');
});
});
// Only run this test for jqLite and not normal jQuery
if ( _jqLiteMode ) {
it('should throw an error if eventData or a selector is passed', function() {
var elm = jqLite(a),
anObj = {},
aString = '',
aValue = 45,
callback = function() {};
expect(function() {
elm.on('click', anObj, callback);
}).toThrowMatching(/\[jqLite\:onargs\]/);
expect(function() {
elm.on('click', null, aString, callback);
}).toThrowMatching(/\[jqLite\:onargs\]/);
expect(function() {
elm.on('click', aValue, callback);
}).toThrowMatching(/\[jqLite\:onargs\]/);
});
}
});
describe('off', function() {
it('should do nothing when no listener was registered with bound', function() {
var aElem = jqLite(a);
aElem.off();
aElem.off('click');
aElem.off('click', function() {});
});
it('should do nothing when a specific listener was not registered', function () {
var aElem = jqLite(a);
aElem.on('click', function() {});
aElem.off('mouseenter', function() {});
});
it('should deregister all listeners', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off();
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister listeners for specific type', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off('click');
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
mouseoverSpy.reset();
aElem.off('mouseover');
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister all listeners for types separated by spaces', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off('click mouseover');
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister specific listener', function() {
var aElem = jqLite(a),
clickSpy1 = jasmine.createSpy('click1'),
clickSpy2 = jasmine.createSpy('click2');
aElem.on('click', clickSpy1);
aElem.on('click', clickSpy2);
browserTrigger(a, 'click');
expect(clickSpy1).toHaveBeenCalledOnce();
expect(clickSpy2).toHaveBeenCalledOnce();
clickSpy1.reset();
clickSpy2.reset();
aElem.off('click', clickSpy1);
browserTrigger(a, 'click');
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).toHaveBeenCalledOnce();
clickSpy2.reset();
aElem.off('click', clickSpy2);
browserTrigger(a, 'click');
expect(clickSpy2).not.toHaveBeenCalled();
});
it('should deregister specific listener for multiple types separated by spaces', function() {
var aElem = jqLite(a),
masterSpy = jasmine.createSpy('master'),
extraSpy = jasmine.createSpy('extra');
aElem.on('click', masterSpy);
aElem.on('click', extraSpy);
aElem.on('mouseover', masterSpy);
browserTrigger(a, 'click');
browserTrigger(a, 'mouseover');
expect(masterSpy.callCount).toBe(2);
expect(extraSpy).toHaveBeenCalledOnce();
masterSpy.reset();
extraSpy.reset();
aElem.off('click mouseover', masterSpy);
browserTrigger(a, 'click');
browserTrigger(a, 'mouseover');
expect(masterSpy).not.toHaveBeenCalled();
expect(extraSpy).toHaveBeenCalledOnce();
});
// Only run this test for jqLite and not normal jQuery
if ( _jqLiteMode ) {
it('should throw an error if a selector is passed', function () {
var aElem = jqLite(a);
aElem.on('click', noop);
expect(function () {
aElem.off('click', noop, '.test');
}).toThrowMatching(/\[jqLite:offargs\]/);
});
}
});
describe('replaceWith', function() {
it('should replaceWith', function() {
var root = jqLite('<div>').html('before-<div></div>after');
var div = root.find('div');
expect(div.replaceWith('<span>span-</span><b>bold-</b>')).toEqual(div);
expect(root.text()).toEqual('before-span-bold-after');
});
it('should replaceWith text', function() {
var root = jqLite('<div>').html('before-<div></div>after');
var div = root.find('div');
expect(div.replaceWith('text-')).toEqual(div);
expect(root.text()).toEqual('before-text-after');
});
});
describe('children', function() {
it('should only select element nodes', function() {
var root = jqLite('<div><!-- some comment -->before-<div></div>after-<span></span>');
var div = root.find('div');
var span = root.find('span');
expect(root.children()).toJqEqual([div, span]);
});
});
describe('contents', function() {
it('should select all types child nodes', function() {
var root = jqLite('<div><!-- some comment -->before-<div></div>after-<span></span></div>');
var contents = root.contents();
expect(contents.length).toEqual(5);
expect(contents[0].data).toEqual(' some comment ');
expect(contents[1].data).toEqual('before-');
});
});
describe('append', function() {
it('should append', function() {
var root = jqLite('<div>');
expect(root.append('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>');
});
it('should append text', function() {
var root = jqLite('<div>');
expect(root.append('text')).toEqual(root);
expect(root.html()).toEqual('text');
});
it('should append to document fragment', function() {
var root = jqLite(document.createDocumentFragment());
expect(root.append('<p>foo</p>')).toBe(root);
expect(root.children().length).toBe(1);
});
it('should not append anything if parent node is not of type element or docfrag', function() {
var root = jqLite('<p>some text node</p>').contents();
expect(root.append('<p>foo</p>')).toBe(root);
expect(root.children().length).toBe(0);
});
});
describe('wrap', function() {
it('should wrap text node', function() {
var root = jqLite('<div>A<a>B</a>C</div>');
var text = root.contents();
expect(text.wrap("<span>")[0]).toBe(text[0]);
expect(root.find('span').text()).toEqual('A<a>B</a>C');
});
it('should wrap free text node', function() {
var root = jqLite('<div>A<a>B</a>C</div>');
var text = root.contents();
text.remove();
expect(root.text()).toBe('');
text.wrap("<span>");
expect(text.parent().text()).toEqual('A<a>B</a>C');
});
});
describe('prepend', function() {
it('should prepend to empty', function() {
var root = jqLite('<div>');
expect(root.prepend('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>');
});
it('should prepend to content', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>text');
});
it('should prepend text to content', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend('abc')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('abctext');
});
it('should prepend array to empty in the right order', function() {
var root = jqLite('<div>');
expect(root.prepend([a, b, c])).toBe(root);
expect(sortedHtml(root)).
toBe('<div><div>A</div><div>B</div><div>C</div></div>');
});
it('should prepend array to content in the right order', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend([a, b, c])).toBe(root);
expect(sortedHtml(root)).
toBe('<div><div>A</div><div>B</div><div>C</div>text</div>');
});
});
describe('remove', function() {
it('should remove', function() {
var root = jqLite('<div><span>abc</span></div>');
var span = root.find('span');
expect(span.remove()).toEqual(span);
expect(root.html()).toEqual('');
});
});
describe('after', function() {
it('should after', function() {
var root = jqLite('<div><span></span></div>');
var span = root.find('span');
expect(span.after('<i></i><b></b>')).toEqual(span);
expect(root.html().toLowerCase()).toEqual('<span></span><i></i><b></b>');
});
it('should allow taking text', function() {
var root = jqLite('<div><span></span></div>');
var span = root.find('span');
span.after('abc');
expect(root.html().toLowerCase()).toEqual('<span></span>abc');
});
});
describe('parent', function() {
it('should return parent or an empty set when no parent', function() {
var parent = jqLite('<div><p>abc</p></div>'),
child = parent.find('p');
expect(parent.parent()).toBeTruthy();
expect(parent.parent().length).toEqual(0);
expect(child.parent().length).toBe(1);
expect(child.parent()[0]).toBe(parent[0]);
});
it('should return empty set when no parent', function() {
var element = jqLite('<div>abc</div>');
expect(element.parent()).toBeTruthy();
expect(element.parent().length).toEqual(0);
});
it('should return empty jqLite object when parent is a document fragment', function() {
//this is quite unfortunate but jQuery 1.5.1 behaves this way
var fragment = document.createDocumentFragment(),
child = jqLite('<p>foo</p>');
fragment.appendChild(child[0]);
expect(child[0].parentNode).toBe(fragment);
expect(child.parent().length).toBe(0);
});
});
describe('next', function() {
it('should return next sibling', function() {
var element = jqLite('<div><b>b</b><i>i</i></div>');
var b = element.find('b');
var i = element.find('i');
expect(b.next()).toJqEqual([i]);
});
it('should ignore non-element siblings', function() {
var element = jqLite('<div><b>b</b>TextNode<!-- comment node --><i>i</i></div>');
var b = element.find('b');
var i = element.find('i');
expect(b.next()).toJqEqual([i]);
});
});
describe('find', function() {
it('should find child by name', function() {
var root = jqLite('<div><div>text</div></div>');
var innerDiv = root.find('div');
expect(innerDiv.length).toEqual(1);
expect(innerDiv.html()).toEqual('text');
});
});
describe('eq', function() {
it('should select the nth element ', function() {
var element = jqLite('<div><span>aa</span></div><div><span>bb</span></div>');
expect(element.find('span').eq(0).html()).toBe('aa');
expect(element.find('span').eq(-1).html()).toBe('bb');
expect(element.find('span').eq(20).length).toBe(0);
});
});
describe('triggerHandler', function() {
it('should trigger all registered handlers for an event', function() {
var element = jqLite('<span>poke</span>'),
pokeSpy = jasmine.createSpy('poke'),
clickSpy1 = jasmine.createSpy('clickSpy1'),
clickSpy2 = jasmine.createSpy('clickSpy2');
element.on('poke', pokeSpy);
element.on('click', clickSpy1);
element.on('click', clickSpy2);
expect(pokeSpy).not.toHaveBeenCalled();
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).not.toHaveBeenCalled();
element.triggerHandler('poke');
expect(pokeSpy).toHaveBeenCalledOnce();
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).not.toHaveBeenCalled();
element.triggerHandler('click');
expect(clickSpy1).toHaveBeenCalledOnce();
expect(clickSpy2).toHaveBeenCalledOnce();
});
it('should pass in a dummy event', function() {
// we need the event to have at least preventDefault because angular will call it on
// all anchors with no href automatically
var element = jqLite('<a>poke</a>'),
pokeSpy = jasmine.createSpy('poke'),
event;
element.on('click', pokeSpy);
element.triggerHandler('click');
event = pokeSpy.mostRecentCall.args[0];
expect(event.preventDefault).toBeDefined();
});
});
describe('camelCase', function() {
it('should leave non-dashed strings alone', function() {
expect(camelCase('foo')).toBe('foo');
expect(camelCase('')).toBe('');
expect(camelCase('fooBar')).toBe('fooBar');
});
it('should covert dash-separated strings to camelCase', function() {
expect(camelCase('foo-bar')).toBe('fooBar');
expect(camelCase('foo-bar-baz')).toBe('fooBarBaz');
expect(camelCase('foo:bar_baz')).toBe('fooBarBaz');
});
it('should covert browser specific css properties', function() {
expect(camelCase('-moz-foo-bar')).toBe('MozFooBar');
expect(camelCase('-webkit-foo-bar')).toBe('webkitFooBar');
expect(camelCase('-webkit-foo-bar')).toBe('webkitFooBar');
})
});
});
|
'use strict';
(function() {
// Create challenge Controller Spec
describe('Create challenge Controller Tests', function() {
// Initialize global variables
var CreateChallengeController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Create challenge controller.
CreateChallengeController = $controller('CreateChallengeController', {
$scope: scope
});
}));
it('Should do some controller test', inject(function() {
// The test logic
// ...
}));
});
}()); |
var keystone = require('../index.js'),
Types = require('../lib/fieldTypes'),
request = require('supertest'),
demand = require('must'),
async = require('async'),
getExpressApp = require('./helpers/getExpressApp'),
removeModel = require('./helpers/removeModel');
describe('List "track" option', function () {
var app = getExpressApp(),
userModelName = 'User',
testModelName = 'Test',
User,
Test,
dummyUser1,
dummyUser2,
post;
before(function(done) {
var tasks = [];
// in case model names were previously used and not cleaned up
removeModel(userModelName);
removeModel(testModelName);
// define user model
keystone.set('user model', userModelName);
User = keystone.List(userModelName);
User.add({
name: { type: String, required: true, index: true }
});
User.register();
function getItem(id, done) {
if (id) {
Test.model.findById(id).exec(function(err, found) {
if (err)
throw err;
if (!found) {
throw new Error('test document not found')
}
item = found;
done(item);
});
} else {
item = new Test.model();
done(item);
}
}
// route to simulate use of updateHandler()
app.post('/using-update-handler/:id?', function(req, res) {
getItem(req.params.id, function(item) {
req.user = req.params.id ? dummyUser2 : dummyUser1;
var updateHandler = item.getUpdateHandler(req);
updateHandler.process(req.body, function(err, data) {
if (err) {
res.send('BAD');
} else {
res.send('GOOD');
}
});
});
});
// route to simulate use of .save()
app.post('/using-save/:id?', function(req, res) {
getItem(req.params.id, function(item) {
item._req_user = req.params.id ? dummyUser2 : dummyUser1;
item.set(req.body);
item.save(function(err, data) {
if (err) {
res.send('BAD');
} else {
res.send('GOOD');
}
});
});
});
// tasks to cleanup test User collection and add dummy users
tasks.push(function(done) {
User.model.remove({}, function(err) {
if (err) {
throw new err;
}
done();
});
});
tasks.push(function(done) {
dummyUser1 = new User.model({
'name': 'John Doe'
}).save(function(err, data) {
if (err) {
throw new err;
}
dummyUser1 = data;
done();
});
});
tasks.push(function(done) {
dummyUser2 = new User.model({
'name': 'Jane Doe'
}).save(function(err, data) {
if (err) {
throw new err;
}
dummyUser2 = data;
done();
});
});
async.series(tasks, function(err) {
if (err) {
throw new err;
}
done();
});
});
describe('when "track" option is not valid', function () {
afterEach(function() {
removeModel(testModelName);
});
it('should throw an error if "track" is not a boolean or an object', function () {
function badList() {
Test = keystone.List(testModelName, { track: 'bad setting' });
Test.add({ name: { type: String } });
Test.register();
}
badList.must.throw(/"track" must be a boolean or an object/);
});
it('should throw an error if "track" fields are not booleans or strings', function () {
function badList() {
Test = keystone.List(testModelName, { track: { createdBy: 5 } });
Test.add({ name: { type: String } });
Test.register();
}
badList.must.throw(/must be a boolean or a string/);
});
it('should throw an error if "track" has an invalid field name', function () {
function badList() {
Test = keystone.List(testModelName, { track: { createdAt: true, badfield: true } });
Test.add({ name: { type: String } });
Test.register();
}
badList.must.throw(/valid field options are/);
});
it('should not register the plugin if all fields are false', function() {
Test = keystone.List(testModelName, {
track: { createdAt: false, createdBy: false, updatedAt: false, updatedBy: false }
});
Test.add({ name: { type: String } });
Test.register();
demand(Test.field('createdAt')).be.undefined();
demand(Test.field('createdBy')).be.undefined();
demand(Test.field('updatedAt')).be.undefined();
demand(Test.field('updatedBy')).be.undefined();
});
});
describe('when "track" option is set to true', function() {
describe('using updateHandler()', function () {
before(function() {
Test = keystone.List(testModelName, { track: true });
Test.add({ name: { type: String } });
Test.schema.post('save', function() {
post = this;
});
Test.register();
});
after(function(done) {
// post test cleanup
Test.model.remove({}, function(err) {
if (err) {
throw new err;
}
removeModel(testModelName);
done();
});
});
it('should have all the default fields', function () {
demand(Test.field('createdAt')).be.an.object();
demand(Test.field('createdBy')).be.an.object();
demand(Test.field('updatedAt')).be.an.object();
demand(Test.field('updatedBy')).be.an.object();
demand(Test.field('createdAt').type).be('datetime');
demand(Test.field('createdBy').type).be('relationship');
demand(Test.field('updatedAt').type).be('datetime');
demand(Test.field('updatedBy').type).be('relationship');
});
it('should updated all fields when adding a document', function(done) {
request(app)
.post('/using-update-handler')
.send({ name: 'test1' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test1');
demand(post.get('createdBy').toString()).be(dummyUser1.get('id'));
demand(post.get('updatedBy').toString()).be(dummyUser1.get('id'));
post.get('createdAt').must.be.a.date();
post.get('updatedAt').must.be.a.date();
demand(post.get('createdAt')).equal(post.get('updatedAt'));
done();
});
});
it('should updated "updatedAt/updatedBy" when modifying a document', function(done) {
request(app)
.post('/using-update-handler/' + post.get('id'))
.send({ name: 'test2' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test2');
demand(post.get('createdBy').toString()).be(dummyUser1.get('id'));
demand(post.get('updatedBy').toString()).be(dummyUser2.get('id'));
post.get('createdAt').must.be.a.date();
post.get('updatedAt').must.be.a.date();
demand(post.get('updatedAt')).be.after(post.get('createdAt'));
done();
});
});
});
describe('using .save()', function () {
before(function() {
Test = keystone.List(testModelName, { track: true });
Test.add({ name: { type: String } });
Test.schema.post('save', function() {
post = this;
});
Test.register();
});
after(function(done) {
// post test cleanup
Test.model.remove({}, function(err) {
if (err) {
throw new err;
}
removeModel(testModelName);
done();
});
});
it('should have all the default fields', function () {
demand(Test.field('createdAt')).be.an.object();
demand(Test.field('createdBy')).be.an.object();
demand(Test.field('updatedAt')).be.an.object();
demand(Test.field('updatedBy')).be.an.object();
demand(Test.field('createdAt').type).be('datetime');
demand(Test.field('createdBy').type).be('relationship');
demand(Test.field('updatedAt').type).be('datetime');
demand(Test.field('updatedBy').type).be('relationship');
});
it('should updated all fields when adding a document', function(done) {
request(app)
.post('/using-save')
.send({ name: 'test1' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test1');
demand(post.get('createdBy').toString()).be(dummyUser1.get('id'));
demand(post.get('updatedBy').toString()).be(dummyUser1.get('id'));
post.get('createdAt').must.be.a.date();
post.get('updatedAt').must.be.a.date();
demand(post.get('createdAt')).equal(post.get('updatedAt'));
done();
});
});
it('should updated "updatedAt/updatedBy" when modifying a document', function(done) {
request(app)
.post('/using-save/' + post._id)
.send({ name: 'test2' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test2');
demand(post.get('createdBy').toString()).be(dummyUser1.get('id'));
demand(post.get('updatedBy').toString()).be(dummyUser2.get('id'));
post.get('createdAt').must.be.a.date();
post.get('updatedAt').must.be.a.date();
demand(post.get('updatedAt')).be.after(post.get('createdAt'));
done();
});
});
});
});
describe('when "track" option fields are selectively enabled', function() {
var previousUpdatedAt;
describe('using updateHandler()', function() {
before(function() {
Test = keystone.List(testModelName, {
track: { updatedAt: true, updatedBy: true }
});
Test.add({ name: { type: String } });
Test.schema.post('save', function() {
post = this;
});
Test.register();
});
after(function(done) {
// post test cleanup
Test.model.remove({}, function(err) {
if (err) {
throw new err;
}
removeModel(testModelName);
done();
});
});
it('should have all the default fields', function () {
demand(Test.field('createdAt')).be.undefined();
demand(Test.field('createdBy')).be.undefined();
demand(Test.field('updatedAt')).be.an.object();
demand(Test.field('updatedBy')).be.an.object();
demand(Test.field('updatedAt').type).be('datetime');
demand(Test.field('updatedBy').type).be('relationship');
});
it('should updated all enabled fields when adding a document', function(done) {
request(app)
.post('/using-update-handler')
.send({ name: 'test1' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test1');
demand(post.get('updatedBy').toString()).be(dummyUser1.get('id'));
post.get('updatedAt').must.be.a.date();
previousUpdatedAt = post.get('updatedAt');
done();
});
});
it('should updated "updatedAt/updatedBy" when modifying a document', function(done) {
request(app)
.post('/using-update-handler/' + post._id)
.send({ name: 'test2' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test2');
demand(post.get('updatedBy').toString()).be(dummyUser2.get('id'));
post.get('updatedAt').must.be.a.date();
demand(post.get('updatedAt')).be.after(previousUpdatedAt);
done();
});
});
});
describe('using .save()', function() {
before(function() {
Test = keystone.List(testModelName, {
track: { updatedAt: true, updatedBy: true }
});
Test.add({ name: { type: String } });
Test.schema.post('save', function() {
post = this;
});
Test.register();
});
after(function(done) {
// post test cleanup
Test.model.remove({}, function(err) {
if (err) {
throw new err;
}
removeModel(testModelName);
done();
});
});
it('should have all the default fields', function () {
demand(Test.field('createdAt')).be.undefined();
demand(Test.field('createdBy')).be.undefined();
demand(Test.field('updatedAt')).be.an.object();
demand(Test.field('updatedBy')).be.an.object();
demand(Test.field('updatedAt').type).be('datetime');
demand(Test.field('updatedBy').type).be('relationship');
});
it('should updated all enabled fields when adding a document', function(done) {
request(app)
.post('/using-save')
.send({ name: 'test1' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test1');
demand(post.get('updatedBy').toString()).be(dummyUser1.get('id'));
post.get('updatedAt').must.be.a.date();
previousUpdatedAt = post.get('updatedAt');
done();
});
});
it('should updated "updatedAt/updatedBy" when modifying a document', function(done) {
request(app)
.post('/using-save/' + post._id)
.send({ name: 'test2' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test2');
demand(post.get('updatedBy').toString()).be(dummyUser2.get('id'));
post.get('updatedAt').must.be.a.date();
demand(post.get('updatedAt')).be.after(previousUpdatedAt);
done();
});
});
});
});
describe('when "track" option has custom field names', function () {
var previousUpdatedAt;
describe('using updateHandler()', function() {
before(function() {
Test = keystone.List(testModelName, {
track: {
createdAt: 'customCreatedAt',
createdBy: 'customCreatedBy',
updatedAt: 'customUpdatedAt',
updatedBy: 'customUpdatedBy'
}
});
Test.add({ name: { type: String } });
Test.schema.post('save', function() {
post = this;
});
Test.register();
});
after(function(done) {
// post test cleanup
Test.model.remove({}, function(err) {
if (err) {
throw new err;
}
removeModel(testModelName);
done();
});
});
it('should no have any of the default fields', function () {
demand(Test.field('createdAt')).be.undefined();
demand(Test.field('createdBy')).be.undefined();
demand(Test.field('updatedAt')).be.undefined();
demand(Test.field('updatedBy')).be.undefined();
});
it('should have all the custom fields', function () {
demand(Test.field('customCreatedAt')).be.an.object();
demand(Test.field('customCreatedBy')).be.an.object();
demand(Test.field('customUpdatedAt')).be.an.object();
demand(Test.field('customUpdatedBy')).be.an.object();
demand(Test.field('customCreatedAt').type).be('datetime');
demand(Test.field('customCreatedBy').type).be('relationship');
demand(Test.field('customUpdatedAt').type).be('datetime');
demand(Test.field('customUpdatedBy').type).be('relationship');
});
it('should updated all custom fields when adding a document', function(done) {
request(app)
.post('/using-update-handler')
.send({ name: 'test1' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test1');
demand(post['customCreatedBy'].toString()).be(dummyUser1.get('id'));
demand(post['customUpdatedBy'].toString()).be(dummyUser1.get('id'));
post['customCreatedAt'].must.be.a.date();
post['customUpdatedAt'].must.be.a.date();
demand(post['customCreatedAt']).equal(post['customUpdatedAt']);
done();
});
});
it('should updated "UpdatedAt/UpdatedBy" custom when modifying a document', function(done) {
request(app)
.post('/using-update-handler/' + post._id)
.send({ name: 'test2' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test2');
demand(post['customUpdatedBy'].toString()).be(dummyUser2.get('id'));
post['customUpdatedAt'].must.be.a.date();
demand(post['customUpdatedAt']).be.after(post['customCreatedAt']);
done();
});
});
});
describe('using save()', function() {
before(function() {
Test = keystone.List(testModelName, {
track: {
createdAt: 'customCreatedAt',
createdBy: 'customCreatedBy',
updatedAt: 'customUpdatedAt',
updatedBy: 'customUpdatedBy'
}
});
Test.add({ name: { type: String } });
Test.schema.post('save', function() {
post = this;
});
Test.register();
});
after(function(done) {
// post test cleanup
Test.model.remove({}, function(err) {
if (err) {
throw new err;
}
removeModel(testModelName);
done();
});
});
it('should no have any of the default fields', function () {
demand(Test.field('createdAt')).be.undefined();
demand(Test.field('createdBy')).be.undefined();
demand(Test.field('updatedAt')).be.undefined();
demand(Test.field('updatedBy')).be.undefined();
});
it('should have all the custom fields', function () {
demand(Test.field('customCreatedAt')).be.an.object();
demand(Test.field('customCreatedBy')).be.an.object();
demand(Test.field('customUpdatedAt')).be.an.object();
demand(Test.field('customUpdatedBy')).be.an.object();
demand(Test.field('customCreatedAt').type).be('datetime');
demand(Test.field('customCreatedBy').type).be('relationship');
demand(Test.field('customUpdatedAt').type).be('datetime');
demand(Test.field('customUpdatedBy').type).be('relationship');
});
it('should updated all custom fields when adding a document', function(done) {
request(app)
.post('/using-save')
.send({ name: 'test1' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test1');
demand(post['customCreatedBy'].toString()).be(dummyUser1.get('id'));
demand(post['customUpdatedBy'].toString()).be(dummyUser1.get('id'));
post['customCreatedAt'].must.be.a.date();
post['customUpdatedAt'].must.be.a.date();
demand(post['customCreatedAt']).equal(post['customUpdatedAt']);
done();
});
});
it('should updated "UpdatedAt/UpdatedBy" custom when modifying a document', function(done) {
request(app)
.post('/using-save/' + post._id)
.send({ name: 'test2' })
.expect('GOOD')
.end(function(err, res){
if (err) {
return done(err);
}
demand(post.get('name')).be('test2');
demand(post['customUpdatedBy'].toString()).be(dummyUser2.get('id'));
post['customUpdatedAt'].must.be.a.date();
demand(post['customUpdatedAt']).be.after(post['customCreatedAt']);
done();
});
});
});
});
});
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import FacetValueList from '../components/FacetValueList';
import ModeLink from '../components/ModeLink';
import { changeFacetMode } from '../actions/search';
class FacetPanel extends Component {
constructor(props) {
super(props);
this.modeCallback = this.modeCallback.bind(this);
}
modeCallback() {
const { dispatch } = this.props;
const updatedMode = this.props.mode === 'list'
? 'chart'
: 'list';
dispatch(changeFacetMode(updatedMode));
}
render() {
const { filters } = this.props;
return (
<div className="facet-panel-inner">
<div className="facet-panel-body">
{this.props.mode === 'list' &&
<FacetValueList
facetType={this.props.facetType}
values={this.props.values}
activeFilters={filters[this.props.facetType]}
callback={this.props.callback}
/>
}
{this.props.mode === 'chart' &&
<img src="http://placehold.it/320x200.png" role="presentation"></img>
}
</div>
<div className="facet-panel-footer">
<ModeLink mode={this.props.mode} onClickCallback={this.modeCallback}/>
</div>
</div>
);
}
}
FacetPanel.propTypes = {
facetType: PropTypes.string.isRequired,
values: PropTypes.array.isRequired,
callback: PropTypes.func.isRequired
}
function mapStateToProps(state) {
return {
mode: state.filter.uiMode,
filters: state.filter.activeFiltersByType
}
}
export default connect(mapStateToProps)(FacetPanel);
|
/**
* Created by chenjianjun on 16/2/26.
*/
var env=require("../config");
var type=env.Thinky.type;
// 婚礼租车
/*
{
"success": true,
"message": null,
"data": [
{
"id": 232,
"createTime": "2016-01-21 19:46:13",
"updateTime": "2016-01-28 16:57:50",
"operater": 1,
"isUsed": 1,
"title": "新款大众帕萨特",
"description": "超出范围限制请联系客服!我们会更具你的用车时间、用车路线的不同,给你一个最优惠的价格(备注:大型节假日不享受此价格:元旦、五一、十一、春节)",
"parameter": "范围:重庆主城内环范围以内|\r\n时间:用车时间5小时|\r\n里程:60公里以内|\r\n带驾驶员:是|\r\n油费:包含|\r\n清洗费:包含",
"content": "内容发送到发送到发送到发送到发生的",
"supplierId": 6,
"levelId": 9,
"modelsId": 4,
"brandId": 6,
"carNature": 1,
"coverUrlWeb": "http://img.jsbn.com/weddingCar/20160121/14533767734205907_375x245.jpg",
"coverUrlWx": "http://img.jsbn.com/weddingCar/20160121/14533767734289714_375x245.jpg",
"coverUrlApp": "http://img.jsbn.com/weddingCar/20160121/14533767734247487_375x245.jpg",
"marketPrice": 550.0,
"rentalPrice": 500.0,
"pcDetailImages": null,
"appDetailImages": null,
"wxDetailImages": null,
"position": "car_list",
"weight": 5
}
],
"code": 200,
"count": 3
}
* */
const Car = env.Thinky.createModel('car', {
// Id
id: type.number(),
// 创建时间
createTime: type.date(),
// 修改时间
updateTime: type.date(),
// 操作员
operater: type.number(),
// 是否有效 有效0:无效 1:有效
isUsed: type.number(),
// 标题
title: type.string(),
// 描述
description: type.string(),
// 汽车参数
parameter: type.string(),
// 富文本内容
content: type.string(),
// 供应商ID
supplierId: type.number(),
// 档次id
levelId: type.number(),
// 品牌id
brandId: type.number(),
// 型号id
modelsId: type.number(),
// 婚车类型
carNature: type.number(),
// web封面图片地址
coverUrlWeb: type.string(),
// 微信封面图片地址
coverUrlWx: type.string(),
// APP封面图片地址
coverUrlApp: type.string(),
// 市场价
marketPrice: type.number(),
// 租赁价
rentalPrice: type.number(),
/************************************start************************************/
// TODO 本身是json对象,以字符串形式表现
// web详细图片集
pcDetailImages: type.string(),
// app详细图片集
appDetailImages: type.string(),
// 微信详细图片集
wxDetailImages: type.string(),
/************************************end*************************************/
// 资源位置
position: type.string(),
// 权重
weight: type.number()
})
Car.ensureIndex('weight');
module.exports=Car;
|
$(function(){
$("#header-nav").load("header.html");
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:e53f63296897f4be839da6c2dd78fb17db764ed4145d0c8ac8eee94e3567bbaa
size 53308
|
/*
* This is heavily based on gulp-mvb with slight modifications
*
* @link <https://github.com/dennisreimann/gulp-mvb>
*/
(function() {
'use strict';
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var extend = require('util-extend');
var marked = require('marked');
var through = require('through2');
var yamlFront = require('yaml-front-matter');
var moment = require('moment');
var highlightjs = require('highlight.js');
module.exports = (function() {
var err = function(message) {
throw new PluginError('ardentlink', message);
};
var findArticles = function(globs) {
return globs.reduce(function(list, pattern) {
return list.concat(glob.sync(pattern));
}, []);
};
var loadArticles = function(globs, permalink) {
var files = findArticles(globs);
var prev_article;
return files.map(function(file) {
var article = loadArticle(file, permalink);
if (!article.date) {
return article;
}
if (prev_article) {
prev_article.next_article = article;
}
article.previous_article = prev_article;
prev_article = article;
return article;
});
};
var loadArticle = function(file_path, permalink) {
var input = fs.readFileSync(file_path);
var article = yamlFront.loadFront(input);
var file_name = path.basename(file_path);
var file_info = file_name.match(/(\d{4}-\d{2}-\d{2})-(.*)\./);
if (file_info) {
if (!article.id) article.id = file_info[2];
if (!article.date) article.date = new Date(file_info[1]);
article.date = moment(article.date);
article.date_human = article.date.format('MMMM Do Y');
} else {
article.id = file_name.replace('.md', '');
if (!article.date) article.date = null;
}
article.file_name = file_name;
article.permalink = permalink(article);
article.content = marked(article.__content, {
smartypants: true
});
delete article.__content;
var more = /<!-- more -->/i;
var desc = article.content.match(more);
if (desc && desc.index) {
article.content = article.content.replace(more, '<div id="more"></div>');
if (!article.description) {
article.description = desc.input
.substring(0, desc.index)
.replace(/(<([^>]+)>)/ig, "")
.trim();
}
}
return article;
};
return function(options) {
if (!options.glob) { err('Missing glob option'); }
if (!options.template) { err('Missing template option'); }
if (typeof(options.permalink) != "function") { err('Missing permalink function'); }
if (!Array.isArray(options.glob)) { options.glob = [options.glob]; }
var highlight = function(code, lang, d) {
if (!lang) {
return highlightjs.highlightAuto(code).value;
}
return highlightjs.highlight(lang, code).value;
};
marked.setOptions({ highlight: highlight });
var globs = options.glob;
var template = fs.readFileSync(options.template);
var permalink = options.permalink;
var articles = loadArticles(globs, permalink).reverse();
var map = articles.reduce(function(mapped, article) {
mapped[article.file_name] = article;
return mapped;
}, {});
return through.obj(function(file, unused, callback) {
var article = map[path.basename(file.path)];
if (!file.data) { file.data = {}; }
file.data.articles = articles.filter(function(article) {
return !!article.date;
});
if (article) {
file.data = extend(file.data, article);
file.path = path.join(file.base, article.permalink + 'index.html');
file.contents = template;
}
callback(null, file);
});
};
})();
})();
|
import constants from '../../extra/constants';
import httpRequest from '../../extra/http-request';
export const TOGGLE_CART = 'TOGGLE_CART';
export const CLOSE_CART = 'CLOSE_CART';
export const ADD_PRODUCT = 'ADD_PRODUCT';
export const SET_PACKAGES = 'SET_PACKAGES';
export const ADD_PACKAGE = 'ADD_PACKAGE';
export const DELETE_ITEM = 'DELETE_ITEM';
export const SELECT_PERIOD = 'SELECT_PERIOD';
export const SET_CART = 'SET_CART';
export const ITEM_DELETED = 'ITEM_DELETED';
export function toggleCart() {
return { type: TOGGLE_CART };
}
export function closeCart() {
return { type: CLOSE_CART };
}
export function addProduct(item, category) {
return {
type: ADD_PRODUCT,
payload: {
item,
category,
},
};
}
export function addPackage(item, packageData) {
return {
type: ADD_PACKAGE,
payload: {
item,
packageData,
},
};
}
export function setPackages(productId, packages) {
return {
type: SET_PACKAGES,
payload: { productId, packages },
};
}
export function deleteItem(item) {
return {
type: DELETE_ITEM,
payload: item,
};
}
export function selectPeriod(item, selected) {
return {
type: SELECT_PERIOD,
payload: {
item,
selected,
},
};
}
export function setCart(data) {
return {
type: SET_CART,
payload: data,
};
}
export function itemDeleted() {
return { type: ITEM_DELETED };
}
export function fetchPackages(itemId, productId) {
return async (dispatch) => {
const url = `${constants.urls.API_MOCKS}/packages/${productId}`;
const { data: { results } } = await httpRequest('GET', url);
dispatch(setPackages(itemId, results));
};
}
export function fetchCart() {
return async (dispatch) => {
const url = `${constants.urls.API_CART}/carts/${constants.urls.API_CART_ID}`;
const { data } = await httpRequest('GET', url);
dispatch(setCart(data));
};
}
export function deleteItemFromBackend(itemId) {
return async (dispatch) => {
const url = `${constants.urls.API_CART}/carts/${constants.urls.API_CART_ID}/items/${itemId}`;
httpRequest('DELETE', url);
dispatch(itemDeleted());
};
}
|
// listen to a firebase and populate links and highlights
var Firebase = require("firebase");
var tweets = require('tweets');
var ayb = new Firebase("https://your-firebase.firebaseio.com/");
ayb.authWithCustomToken("FIREBASE_AUTH_TOKEN", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Login Succeeded!");
}
});
var stream = new tweets({
consumer_key: 'TWITTER_CONSUMER_KEY',
consumer_secret: 'TWITTER_CONSUMER_SECRET',
access_token: 'TWITTER_ACCESS_TOKEN',
access_token_secret: 'TWITTER_ACCESS_TOKEN_SECRET'
});
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var users = [];
var screen_names = [];
var last;
var updateStream = debounce(function(){
var tre = /^@?(\w){1,15}$/;
if(users.length){
var follow = users
.filter(function(str){
return str.match(tre);
})
.slice(0,5000)
.join(',')
if(last === follow)
return console.log("not re-following ", last = follow);
console.log("TWITTER, follow = " + follow);
stream.filter({follow: follow});
} else {
if(last === ' ac')
return console.log("not re-following ", last = ' ac');
console.log("TWITTER, track = adventureclub");
stream.filter({track: 'adventureclub'});
}
}, 2000) // this is more to avoid multiple updates from FB (which probably doesn't happen)
ayb.child('users').on('value', function (snapshot) {
users = [];// = Object.keys(snapshot.val() || {});
screen_names = []
snapshot.forEach(function(d){
var u = d.val();
if(u.id_str) users.push(u.id_str)
if(u.handle) screen_names.push(u.handle)
})
updateStream();
// console.log(users.join(','))
})
stream.on('error',function(){
console.log("tweets error", e);
})
stream.on('reconnect', function(reconnect){
console.log("reconnect", reconnect)
if(reconnect.type == 'rate-limit'){
// do something to reduce your requests to the api
}
});
stream.on('tweet', function(tweet){
return;
console.log(tweet.user.screen_name, tweet.text);
try{
var user = tweet.user.screen_name;
if(tracking(user)){
tweet.entities.user_mentions.forEach(function(mention){
var user2 = mention.screen_name;
if(tracking(user2)){
console.log("FOUND: ", user, user2);
ayb
.child('links')
.child(user + ' ' + user2)
.set(+ new Date)
}
})
}
} catch (e){
console.log("lolwat", e)
}
});
function tracking(screen_name){
return screen_names.indexOf(screen_name) > -1
}
// DEV
function populate(){
var u1 = randomUser(),
u2 = randomUser();
if(u1 && u2 && u1 !== u2){
ayb
.child('links')
.child(u1 + ' ' + u2)
.set(+ new Date)
}
setTimeout(populate, Math.random() * 10000)
}
// populate();
function randomUser(){
return screen_names[
Math.floor(Math.random()*screen_names.length)
]
} |
module.exports = {
// Port server listens on
"port" : "8080",
// The slash command shown in help text, e.g., /stuart
"slash_command" : "panda",
// The Bot Persona
"name" : "PandaMan",
"emoji" : ":panda_face:",
// The Slack host
//
// Careful! Don't include the token with your slack_host value
"slack_host" : "https://hooks.slack.com/services/FIXME/FIXME/FIXME",
"slack_token" : "FIXME"
};
|
// var request = require('supertest');
var expect = require('chai').expect;
var sinon = require('sinon');
var Exp = require('../../../server/exps/models/Exp');
var app = require('../../../server/app.js');
var request = require('supertest')(app);
var exampleUser = require('../../../dummyData/exampleUsers.json')[0];
var dummyData = require('../../../dummyData/normalizedDummyData.json');
var mongoose = require('mongoose');
describe('The Experiment Router', function () {
var userId, expId, dummyExp;
beforeEach(function(done){
//setup dummy exp
var keys = Object.keys(dummyData.experiments);
dummyExp = dummyData['experiments'][keys[0]];
dummyExp._id = mongoose.Types.ObjectId();
//have to set up the user.
request
.post('/users/')
.send(exampleUser)
.end(function(err, res) {
userId = res.body.googleId;
done();
});
});
afterEach(function(done){
//remove dummy exp
request
.delete('/' + userId + '/experiments'+ dummyExp._id)
.end(function(err, res) {
request
//remove dummy user
.delete('/users/' + userId)
.end(function(err) {
done(err);});
});
});
describe('/users/:userId/experiments/', function () {
it('adds an exp on post', function (done) {
request
.post('/users/'+userId+'/experiments/')
.send({experiments : [dummyExp]})
.expect(200)
.end(function (err, res) {
if (err) { return done(err); }
else return done();
});
});
it('returns all experiments on get', function (done) {
request
.get('/users/'+userId+'/experiments/')
.expect(200)
.expect(function(res){
if(Array.isArray(res.body)){
return done();
}
})
.end(function (err, res) {
if (err) return done(err);
});
});
it('returns previously created experiments on GET', function (done) {
request
//create new exp
.post('/users/' + userId + '/experiments/')
.send({experiments : [dummyExp]})
.end(function(err, res) {
request
//get exps
.get('/users/' + userId + '/experiments/'+ dummyExp._id)
.expect(200)
.expect(function(res){
//ensure that id from above matches
if(res.body._id === dummyExp._id){
return done();
} else {
throw 'No experiments';
}
})
.end(function (err, res) {
done(err);
});
});
});
});
describe('/users/:userId/experiments/:expId', function () {
it('responds to DELETE requests at', function (done) {
request
.post('/users/' + userId + '/experiments/')
.send({experiments : [dummyExp]})
.end(function(err, res) {
request
.delete('/users/' + userId + '/experiments/' + dummyExp._id)
.expect(200, 'removed exp', done);
});
});
it('actually deletes Exp document from DB', function(done){
Exp.findOne({_id : dummyExp._id}, function (err, exp) {
expect(exp).to.eql(null);
done();
});
});
it('responds to GET requests at `/users/:userId/experiments/:expId`', function (done) {
request
.post('/users/' + userId + '/experiments/')
.send({experiments : [dummyExp]})
.end(function(err, res) {
request
.get('/users/' + userId + '/experiments/'+ dummyExp._id)
.expect(200)
.expect(function(res){
if(res.body.name === dummyExp.name) {
return done();
}
})
.end(function (err, res) {
if (err) return done(err);
});
});
});
it('should tell us when the exp dosent exist', function (done) {
//ask for fake exp
request
.get('/users/'+ userId + '/experiments/'+mongoose.Types.ObjectId())
.expect(204, done);
});
});
});
// request
// .post('/users/')
// .send(exampleUser)
// .end(function(err, res) {
// userId = res.body.googleId;
// done();
// });
|
exports.geojson =
/**
* This function outputs a GeoJSON FeatureCollection (compatible with
* OpenLayers). JSONP requests are supported as well.
*
* @author Volker Mische
*/
function(head, req) {
var row, out, sep = '\n';
// Send the same Content-Type as CouchDB would
if (req.headers.Accept.indexOf('application/json')!=-1) {
start({"headers":{"Content-Type" : "application/json"}});
}
else {
start({"headers":{"Content-Type" : "text/plain"}});
}
if ('callback' in req.query) {
send(req.query['callback'] + "(");
}
send('{"type": "FeatureCollection", "features":[');
while (row = getRow()) {
out = JSON.stringify({type: "Feature", geometry: row.geometry,
properties: row.value});
send(sep + out);
sep = ',\n';
}
send("]}");
if ('callback' in req.query) {
send(")");
}
};
exports.kml =
/**
* A list function that transforms a spatial view result set into a KML feed.
*
* @author Benjamin Erb
*/
function(head, req) {
var row, out, sep = '\n';
start({"headers":{"Content-Type" : "application/vnd.google-earth.kml+xml"}});
send('<?xml version="1.0" encoding="UTF-8"?>\n');
send('<kml xmlns="http://www.opengis.net/kml/2.2">\n');
send('<Document>\n');
send('<name>GeoCouch Result - KML Feed</name>\n');
while (row = getRow()) {
if(row.geometry){
send('\t<Placemark>');
send('<name>'+row.id+'</name>');
send('<Point><coordinates>'+row.geometry.coordinates[0]+','+row.geometry.coordinates[1]+',0</coordinates></Point>');
send('</Placemark>\n');
}
}
send('</Document>\n');
send('</kml>\n');
};
exports['knn-clustering'] =
/**
* A clustering algorithm that clusters object based on their proximity, producing k distinct clusters.
*/
function(head, req) {
start({"code": 501,"headers":{"Content-Type" : "text/plain"}});
//TODO: implement kNN clustering list
}
exports['proximity-clustering'] =
/**
* A clustering algorithm that clusters object based on their proximity, using a threshold value.
*/
function(head, req) {
var g = require('vendor/clustering/ProximityCluster'),
row,
threshold =100;
start({"headers":{"Content-Type" : "application/json"}});
if ('callback' in req.query) send(req.query['callback'] + "(");
if('threshold' in req.query){ threshold = req.query.threshold;}
var pc = new g.PointCluster(parseInt(threshold));
while (row = getRow()) {
pc.addToClosestCluster(row.value);
}
send(JSON.stringify({"rows":pc.getClusters()}));
if ('callback' in req.query) send(")");
};
exports.radius =
/**
* This will take the centroid of the bbox parameter and a supplied radius
* parameter in meters and filter the rectangularly shaped bounding box
* result set by circular radius.
*
* @author Max Ogden
*/
function(head, req) {
var gju = require('vendor/geojson-js-utils/geojson-utils'),
row,
out,
radius = req.query.radius,
bbox = JSON.parse("[" + req.query.bbox + "]"),
center = gju.rectangleCentroid({
"type": "Polygon",
"coordinates": [[[bbox[0], bbox[1]], [bbox[2], bbox[3]]]]
}),
callback = req.query.callback,
circle = gju.drawCircle(radius, center),
startedOutput = false;
if (req.headers.Accept.indexOf('application/json') != -1)
start({"headers":{"Content-Type" : "application/json"}});
else
start({"headers":{"Content-Type" : "text/plain"}});
if ('callback' in req.query) send(req.query['callback'] + "(");
send('{"type": "FeatureCollection", "features":[');
while (row = getRow()) {
if (gju.pointInPolygon(row.geometry, circle)) {
if (startedOutput) send(",\n");
out = '{"type": "Feature", "geometry": ' + JSON.stringify(row.geometry) +
', "properties": ' + JSON.stringify(row.value) + '}';
send(out);
startedOutput = true;
}
}
send("\n]};");
if ('callback' in req.query) send(")");
};
|
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io, global) {
/**
* Expose constructor.
*
* @api public
*/
exports.XHR = XHR;
/**
* XHR constructor
*
* @costructor
* @api public
*/
function XHR(socket) {
if (!socket) return;
io.Transport.apply(this, arguments);
this.sendBuffer = [];
};
/**
* Inherits from Transport.
*/
io.util.inherit(XHR, io.Transport);
/**
* Establish a connection
*
* @returns {Transport}
* @api public
*/
XHR.prototype.open = function () {
this.socket.setBuffer(false);
this.onOpen();
this.get();
// we need to make sure the request succeeds since we have no indication
// whether the request opened or not until it succeeded.
this.setCloseTimeout();
return this;
};
/**
* Check if we need to send data to the Socket.IO server, if we have data in our
* buffer we encode it and forward it to the `post` method.
*
* @api private
*/
XHR.prototype.payload = function (payload) {
var msgs = [];
for (var i = 0, l = payload.length; i < l; i++) {
msgs.push(io.parser.encodePacket(payload[i]));
}
this.send(io.parser.encodePayload(msgs));
};
/**
* Send data to the Socket.IO server.
*
* @param data The message
* @returns {Transport}
* @api public
*/
XHR.prototype.send = function (data) {
this.post(data);
return this;
};
/**
* Posts a encoded message to the Socket.IO server.
*
* @param {String} data A encoded message.
* @api private
*/
function empty() {
};
XHR.prototype.post = function (data) {
var self = this;
this.socket.setBuffer(true);
function stateChange() {
if (this.readyState == 4) {
this.onreadystatechange = empty;
self.posting = false;
if (this.status == 200) {
self.socket.setBuffer(false);
} else {
self.onClose();
}
}
}
function onload() {
this.onload = empty;
self.socket.setBuffer(false);
};
this.sendXHR = this.request('POST');
if (global.XDomainRequest && this.sendXHR instanceof XDomainRequest) {
this.sendXHR.onload = this.sendXHR.onerror = onload;
} else {
this.sendXHR.onreadystatechange = stateChange;
}
this.sendXHR.send(data);
};
/**
* Disconnects the established `XHR` connection.
*
* @returns {Transport}
* @api public
*/
XHR.prototype.close = function () {
this.onClose();
return this;
};
/**
* Generates a configured XHR request
*
* @param {String} url The url that needs to be requested.
* @param {String} method The method the request should use.
* @returns {XMLHttpRequest}
* @api private
*/
XHR.prototype.request = function (method) {
var req = io.util.request(this.socket.isXDomain())
, query = io.util.query(this.socket.options.query, 't=' + +new Date);
req.open(method || 'GET', this.prepareUrl() + query, true);
if (method == 'POST') {
try {
if (req.setRequestHeader) {
req.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
} else {
// XDomainRequest
req.contentType = 'text/plain';
}
} catch (e) {
}
}
return req;
};
/**
* Returns the scheme to use for the transport URLs.
*
* @api private
*/
XHR.prototype.scheme = function () {
return this.socket.options.secure ? 'https' : 'http';
};
/**
* Check if the XHR transports are supported
*
* @param {Boolean} xdomain Check if we support cross domain requests.
* @returns {Boolean}
* @api public
*/
XHR.check = function (socket, xdomain) {
try {
var request = io.util.request(xdomain),
usesXDomReq = (global.XDomainRequest && request instanceof XDomainRequest),
socketProtocol = (socket && socket.options && socket.options.secure ? 'https:' : 'http:'),
isXProtocol = (global.location && socketProtocol != global.location.protocol);
if (request && !(usesXDomReq && isXProtocol)) {
return true;
}
} catch (e) {
}
return false;
};
/**
* Check if the XHR transport supports cross domain requests.
*
* @returns {Boolean}
* @api public
*/
XHR.xdomainCheck = function (socket) {
return XHR.check(socket, true);
};
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
, this
);
|
// Copyright (c) CBC/Radio-Canada. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import ko from 'knockout';
import $ from 'jquery';
import moment from 'moment';
ko.bindingHandlers.datetime = {
update: function(element, valueAccessor, allBindingsAccessor /*, viewModel*/ ) {
var valueUnwrapped = ko.unwrap(valueAccessor());
if (!valueUnwrapped) {
return;
}
var datetime = moment.utc(valueUnwrapped).local();
var $element = $(element);
var allBindings = allBindingsAccessor();
var pattern = allBindings.datePattern || 'YYYY-MM-DD H:mm';
$element.text(datetime.format(pattern));
if ($element.is('time')) {
$element.attr('datetime', datetime.toISOString());
}
}
};
|
import { ObjectObserver, Observable } from '../observable';
class Transaction extends Observable {
constructor(transactionId, itemType, type) {
super();
this._observer = this._createObserver();
this._observerLocked = true;
this._transactionId = transactionId;
this._itemType = itemType;
this._type = type;
this._ready = false;
this._processing = false;
this._succeeded = false;
this._failed = false;
this._errors = [];
}
_createObserver() {
return new ObjectObserver();
}
get changed() {
return this._observer.changed;
}
markAsChanged() {
this._observer.markAsChanged();
if (this._parentObserver !== null) {
this._parentObserver.markAsChanged();
}
}
get transactionId() {
return this._transactionId;
}
get itemType() {
return this._itemType;
}
get type() {
return this._type;
}
get ready() {
return this._ready;
}
get processing() {
return this._processing;
}
get failed() {
return this._failed;
}
get succeeded() {
return this._succeeded;
}
get hasErrors() {
return (this.errors.length > 0);
}
get errors() {
return this._errors;
}
setReady(ready) {
this._ready = ready;
this.markAsChanged();
return this;
}
setProcessing(processing) {
this._processing = processing;
this.markAsChanged();
return this;
}
setSucceeded(succeeded) {
this._succeeded = succeeded;
this.markAsChanged();
return this;
}
setFailed(failed) {
this._failed = failed;
this.markAsChanged();
return this;
}
setErrors(errors) {
this._errors = errors;
this.markAsChanged();
return this;
}
}
export default Transaction;
|
// [], target
module.exports = [{
input: ['hello'],
output: 'olleh',
},{
input: ['abcdefg'],
output: 'gfedcba',
}] |
/* eslint-disable flowtype/require-valid-file-annotation */
module.exports = require('../lib/components-icons/Card');
|
'use strict';
// This is the entry point of the client's script.
var jQuery = require('jquery');
var $ = jQuery;
global.jQuery = jQuery;
require('bootstrap'); |
define(['razorcharts2/axes/axis'], function (Axis) {
var LeftAxis = function () {
this.init ();
this.registerTransformer ({key: 'render', transform: LeftAxisTransformer});
this.registerTransformer ({key: 'resize', transform: LeftAxisTransformer});
this.registerTransformer ({key: 'update', transform: LeftAxisUpdateTransformer});
};
LeftAxis.prototype = new Axis ();
LeftAxis.prototype.constructor = LeftAxis;
function LeftAxisTransformer (self) {
var $ticks = self.$ticks,
ticks = self.ticks,
scale = self.scale,
height = self.coreHeight,
tickHeight = height / ticks.length,
maxTickWidth;
for(var i=0; i<ticks.length; ++i) {
var y;
if(self.options.type === 'linear') {
y = height - scale.calc(ticks[i]) + 8;
} else {
y = height - scale.calc(ticks[i]) - tickHeight / 2;
}
$ticks[i].translate (-10, y);
$ticks[i].attr ({
'text-anchor': 'end'
});
}
self.line.attr({
x1: 0,
y1: 0,
x2: 0,
y2: height,
stroke: "none",
fill: 'none'
});
if(self.hasLabel()) {
self.$label.text(self.label);
self.$label.attr({
'text-anchor': 'middle'
});
maxTickWidth = self.getMaxTickWidth($ticks);
self.$label.translate(0 - maxTickWidth - self.$label.getBBox().height * 2, height / 2);
self.$label.rotate(-90);
}
};
function LeftAxisUpdateTransformer (self) {
console.log('LeftAxisUpdateTransformer called!');
var $ticks = self.$ticks,
$cachedTicks = self.$cachedTicks,
ticks = self.ticks,
cachedTicks = self.cachedTicks;
scale = self.scale,
cachedScale = self.cachedScale,
height = self.coreHeight;
cachedScale.range([0, height]);
for(var i=0; i<ticks.length; ++i) {
var y;
if(self.options.type === 'linear') {
y = height - scale.calc(ticks[i]) + 8;
} else {
y = height - scale.calc(ticks[i]) - tickHeight / 2;
}
var oldY = height - cachedScale.calc(ticks[i]) + 8;
if($ticks[i].__newTick) {
$ticks[i].attr('opacity', 0);
$ticks[i].__newTick = false;
}
$ticks[i].translate(-10, oldY);
$ticks[i].attr ({
'text-anchor': 'end'
});
$ticks[i].animate({
transform: {
translate: [-10, y]
},
opacity: 1
});
}
for(var i=0; i<cachedTicks.length; i++) {
var y = height - scale.calc(cachedTicks[i]) + 8;
(function(_i) {
$cachedTicks[_i].animate({
transform: {
translate: [-10, y]
},
opacity: 0
}, 500, function () {
$cachedTicks[_i].remove();
});
})(i);
}
self.cache ();
};
return LeftAxis;
}); |
'use strict';
// stdlib
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
// third party lib
import { Input } from '../../../../libs/bootstrap/form';
import ModalComponent from '../../../../libs/bootstrap/modal';
/**
* Modal to confirm before deleting an evidence.
*/
let ConfirmDelete = createReactClass({
propTypes: {
evidence: PropTypes.object, // Selected evidence row to be deleted
deleteEvidence: PropTypes.func // Function to call to delete the evidence row
},
handleModalClose() {
this.confirm.closeModal();
},
cancel() {
this.handleModalClose();
},
clickConfirm() {
this.props.deleteEvidence(this.props.evidence);
this.handleModalClose();
},
render() {
return (
<ModalComponent
modalTitle="Confirm evidence deletion"
modalClass="modal-default"
modalWrapperClass="confirm-interpretation-delete-evidence pull-right"
bootstrapBtnClass="btn btn-danger "
actuatorClass="interpretation-delete-evidence-btn"
actuatorTitle="Delete"
onRef={ref => (this.confirm = ref)}
>
<div>
<div className="modal-body">
<p>
Are you sure you want to delete this evidence?
</p>
</div>
<div className='modal-footer'>
<Input type="button" inputClassName="btn-primary btn-inline-spacer" clickHandler={this.clickConfirm} title="Confirm" />
<Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.cancel} title="Cancel" />
</div>
</div>
</ModalComponent>
);
}
});
module.exports = {
ConfirmDelete: ConfirmDelete
}
|
var webpack = require("webpack");
module.exports = {
context: "" ,
entry: "./node_modules/terminal.js/index",
output: {
libraryTarget: "var",
library: "Terminal",
path: "./",
filename: "terminal.js"
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
|
/*globals define, _, WebGMEGlobal*/
/*jshint browser: true*/
/**
* @author rkereskenyi / https://github.com/rkereskenyi
*/
define(['js/PanelBase/PanelBaseWithHeader',
'js/PanelManager/IActivePanel',
'js/Widgets/SetEditor/SetEditorWidget',
'./SetEditorController'
], function (PanelBaseWithHeader,
IActivePanel,
SetEditorWidget,
SetEditorController) {
'use strict';
var SetEditorPanel;
SetEditorPanel = function (layoutManager, params) {
var options = {};
//set properties from options
options[PanelBaseWithHeader.OPTIONS.LOGGER_INSTANCE_NAME] = 'SetEditorPanel';
options[PanelBaseWithHeader.OPTIONS.FLOATING_TITLE] = true;
//call parent's constructor
PanelBaseWithHeader.apply(this, [options, layoutManager]);
this._client = params.client;
//initialize UI
this._initialize();
this.logger.debug('SetEditorPanel ctor finished');
};
//inherit from PanelBaseWithHeader
_.extend(SetEditorPanel.prototype, PanelBaseWithHeader.prototype);
_.extend(SetEditorPanel.prototype, IActivePanel.prototype);
SetEditorPanel.prototype._initialize = function () {
var self = this;
//remove title container
/*if (this.$panelHeaderTitle) {
this.$panelHeaderTitle.remove();
}*/
this.widget = new SetEditorWidget(this.$el, {'toolBar': this.toolBar});
this.widget.setTitle = function (title) {
self.setTitle(title);
};
this.widget.onUIActivity = function () {
//WebGMEGlobal.PanelManager.setActivePanel(self);
WebGMEGlobal.KeyboardManager.setListener(self.widget);
};
this.control = new SetEditorController({
client: this._client,
widget: this.widget
});
this.onActivate();
};
/* OVERRIDE FROM WIDGET-WITH-HEADER */
/* METHOD CALLED WHEN THE WIDGET'S READ-ONLY PROPERTY CHANGES */
SetEditorPanel.prototype.onReadOnlyChanged = function (isReadOnly) {
//apply parent's onReadOnlyChanged
PanelBaseWithHeader.prototype.onReadOnlyChanged.call(this, isReadOnly);
this.widget.setReadOnly(isReadOnly);
this.control.setReadOnly(isReadOnly);
};
SetEditorPanel.prototype.onResize = function (width, height) {
this.logger.debug('onResize --> width: ' + width + ', height: ' + height);
this.widget.onWidgetContainerResize(width, height);
};
SetEditorPanel.prototype.destroy = function () {
this.control.destroy();
this.widget.destroy();
PanelBaseWithHeader.prototype.destroy.call(this);
WebGMEGlobal.KeyboardManager.setListener(undefined);
WebGMEGlobal.Toolbar.refresh();
};
/* override IActivePanel.prototype.onActivate */
SetEditorPanel.prototype.onActivate = function () {
this.widget.onActivate();
this.control.onActivate();
WebGMEGlobal.KeyboardManager.setListener(this.widget);
WebGMEGlobal.Toolbar.refresh();
};
/* override IActivePanel.prototype.onDeactivate */
SetEditorPanel.prototype.onDeactivate = function () {
this.widget.onDeactivate();
this.control.onDeactivate();
WebGMEGlobal.KeyboardManager.setListener(undefined);
WebGMEGlobal.Toolbar.refresh();
};
SetEditorPanel.prototype.getValidTypesInfo = function (/*nodeId, aspect*/) {
return {};
};
return SetEditorPanel;
});
|
'use strict';
angular.module('mean.icu.ui.searchlist')
.controller('SearchListController', function ($scope, results, term) {
$scope.results = results;
$scope.term = term;
});
|
(function(){
document.addEventListener('keypress',function(deets){
if(deets.charCode===32) window.togglePlayPause();
});
}());
|
#! /usr/bin/env node
var program = require('commander')
var tracker = require('../')
program
.arguments('<tracecode>')
.option('-c, --company <company>', 'Company Name', /^(ems)$/i, 'ems')
.action(function (tracecode) {
if (!tracker.COMPANY[program.company.toUpperCase()]) {
console.error('The Company is not supported.')
process.exit(1)
} else if (!tracecode) {
console.error('Please enter a tracecode.')
process.exit(1)
}
var company = tracker.company(program.company)
company.trace(tracecode, function (err, result) {
if (err) {
console.error(err)
process.exit(1)
}
console.log(JSON.stringify(result, null, 2))
process.exit(0)
})
})
.parse(process.argv)
|
'use strict';
// gulp
var gulp = require('gulp');
var paths = gulp.paths;
var options = gulp.options;
// modules
var bs = require('browser-sync').create();
var bsInit = function (paths, openOverride) {
var bsOptions = {
server: {
baseDir: paths
},
browser: 'google chrome'
};
if (options.open === false) {
bsOptions.open = false;
}
if (openOverride !== undefined) {
bsOptions.open = openOverride;
}
bs.init(bsOptions);
};
// WATCH
gulp.task('watch', ['inject-all'], function () {
// browser sync server
bsInit(['app', '.tmp']);
var watchFiles = paths.jsFiles
.concat([
'app/index.html',
'.tmp/*/styles/*.css', // each module's css
'app/*/assets/**/*'
])
.concat(paths.templates);
// start linting and watching
gulp.start('linting');
gulp.watch(watchFiles, function (event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
if (event.type === 'changed') {
bs.reload();
gulp.start('linting');
}
else { // added or deleted
// inject in index (implicitly reloads)
gulp.start('inject-all');
}
});
// watch for changes in scss
gulp.watch('app/*/styles/**/*.scss', ['styles']);
// watch for changes in environment files and new config files
gulp.watch([
'app/main/constants/env-*.json',
'app/*/constants/*config-const.js'
], ['environment']);
});
// WATCH-BUILD
var watchBuildDeps = [];
if (options.build !== false) {
watchBuildDeps.push('build');
}
gulp.task('watch-build', watchBuildDeps, function () {
bsInit(paths.dist);
gulp.watch(paths.dist + '**/*', function () {
bs.reload();
});
});
// SERVE TASKS
gulp.task('serve', ['inject-all'], function () {
bsInit(['app', '.tmp'], false);
});
gulp.task('serve-build', ['build'], function () {
bsInit(['app', '.tmp'], false);
});
|
const expect = require('chai').expect
const middleware = require('../../lib/middleware')
suite('middleware#toPath', function () {
test('overwrite path', function (done) {
var req = {}
var newPath = '/new/path'
var mw = middleware.toPath(newPath)
mw(req, null, function assert(err) {
expect(err).to.be.undefined
expect(req.url).to.be.equal(newPath)
done()
})
})
test('dynamic params', function (done) {
var req = {}
var newPath = '/profile/:id'
var mw = middleware.toPath(newPath, { id: 'chuck' })
mw(req, null, function assert(err) {
expect(err).to.be.undefined
expect(req.url).to.be.equal('/profile/chuck')
done()
})
})
test('multiple params', function (done) {
var req = {}
var newPath = '/profile/:id/:action/photo/:code'
var mw = middleware.toPath(newPath, { id: 'chuck', action: 'update', code: 100 })
mw(req, null, function assert(err) {
expect(err).to.be.undefined
expect(req.url).to.be.equal('/profile/chuck/update/photo/100')
done()
})
})
test('default previous params', function (done) {
var req = { params: { id: 'chuck', action: 'update' }}
var newPath = '/profile/:id/:action'
var mw = middleware.toPath(newPath)
mw(req, null, function assert(err) {
expect(err).to.be.undefined
expect(req.url).to.be.equal('/profile/chuck/update')
done()
})
})
test('invalid params', function (done) {
var req = {}
var newPath = '/profile/:id/:action'
var mw = middleware.toPath(newPath, { id: 'chuck', action: null })
mw(req, null, function assert(err) {
expect(err).to.be.undefined
expect(req.url).to.be.equal('/profile/chuck/')
done()
})
})
})
|
/**
* @fileoverview added by tsickle
* Generated from: test_files/protected/protected.ts
* @suppress {checkTypes,const,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** This test checks that we emit \@private/\@protected where necessary. */
goog.module('test_files.protected.protected');
var module = module || { id: 'test_files/protected/protected.ts' };
goog.require('tslib');
class Protected {
/**
* @public
* @param {string} anotherPrivate
* @param {string} anotherProtected
*/
constructor(anotherPrivate, anotherProtected) {
this.anotherPrivate = anotherPrivate;
this.anotherProtected = anotherProtected;
}
/**
* @private
* @return {void}
*/
privateMethod() { }
/**
* @protected
* @return {void}
*/
protectedMethod() { }
}
/* istanbul ignore if */
if (false) {
/**
* @type {string}
* @private
*/
Protected.prototype.privateMember;
/**
* @type {string}
* @protected
*/
Protected.prototype.protectedMember;
/**
* @type {string}
* @private
*/
Protected.prototype.anotherPrivate;
/**
* @type {string}
* @protected
*/
Protected.prototype.anotherProtected;
}
/**
* @abstract
*/
class Abstract {
}
/* istanbul ignore if */
if (false) {
/**
* @abstract
* @protected
* @return {void}
*/
Abstract.prototype.foo = function () { };
}
|
import { IconChevronDown, IconTimesCircle } from 'dls-icons-vue'
import ui from 'veui/managers/ui'
const CHECKBOX_SIZE_MAP = {
xs: 's',
s: 's',
m: 'm',
l: 'm'
}
const TAG_SIZE_MAP = {
xs: 's',
s: 's',
m: 's',
l: 'm'
}
ui.defaults(
{
icons: {
expand: IconChevronDown,
collapse: IconChevronDown,
clear: IconTimesCircle
},
ui: {
size: {
values: ['xs', 's', 'm', 'l'],
inherit: true,
default: 'm'
}
},
parts: {
clear: 'icon aux',
checkbox: ({ size }) => CHECKBOX_SIZE_MAP[size] || size,
tag: ({ size }) => TAG_SIZE_MAP[size] || size
}
},
'select'
)
|
// Test that we *don't* get SpiderMonkey extensions; see
// testJS1_8.js.
// application/javascript;version=ECMAv3
var GLib = imports.gi.GLib;
function testLet() {
assertRaises('missing ; before statement', function () { eval("let result = 1+1; result;") });
}
function testYield() {
assertRaises('missing ; before statement', function() { eval("function foo () { yield 42; }; foo();"); });
}
gjstestRun();
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('./List'), require('./Maybe'), require('../utils/clone')) :
typeof define === 'function' && define.amd ? define(['exports', './List', './Maybe', '../utils/clone'], factory) :
(factory((global['functional/core/Task'] = global['functional/core/Task'] || {}, global['functional/core/Task'].js = {}),global.List_mjs,global.Maybe_mjs,global.clone_mjs));
}(this, (function (exports,List_mjs,Maybe_mjs,clone_mjs) { 'use strict';
const isFunction = (obj) => !!(obj && obj.constructor && obj.call && obj.apply);
const toFunction = (job) => isFunction(job) ? job : () => job;
const emptyFn = _ => _;
const setPromise = (job) => (data, success) => new Promise((resolve, reject) => {
const dataCopy = clone_mjs.clone(data);
const fn = job.getOrElse(emptyFn);
if (success) {
return (fn.length <= 1) ? resolve(fn(dataCopy)) : fn(dataCopy, resolve, reject);
} else {
return reject(dataCopy);
}
});
/**
* Task class is for asyns/sync jobs. You can provide 3 types on tasks
* @Task((resolve,reject)=>resolve()) // resolve reject params
* @Task(()=>3) synchronus function with returning value !important argumentList have to be empty
* @Task(3) // Static values
* */
//Define Private methods;
const _parent = Symbol('_parent');
const _topRef = Symbol('_topRef');
const _topParent = Symbol('_topParent');
const _children = Symbol('_children');
const _resolvers = Symbol('_resolvers');
const _rejecters = Symbol('_rejecters');
const _resolve = Symbol('_resolve');
const _reject = Symbol('_reject');
const _bottomRef = Symbol('_bottomRef');
const _uuid = Symbol('_uuid');
const _create = Symbol('_create');
const _task = Symbol('_task');
const _setPromise = Symbol('_setPromise');
const _setParent = Symbol('_setParent');
const _addParent = Symbol('_addParent');
const _setChildren = Symbol('_setChildren');
const _resolveRun = Symbol('_resolveRun');
const _rejectRun = Symbol('_rejectRun');
const _triggerUp = Symbol('_triggerUp');
const _triggerDown = Symbol('_triggerDown');
const _run = Symbol('_run');
const _flatMap = Symbol('_flatMap');
const _copyJob = Symbol('_copyJob');
const _getTopRef = Symbol('_getTopRef');
const _getBottomRef = Symbol('_getBottomRef');
const _copy = Symbol('_copy');
class Task {
constructor(job, parent) {
this[_parent] = Maybe_mjs.none();
this[_topRef] = Maybe_mjs.none();
this[_topParent] = Maybe_mjs.none();
this[_children] = List_mjs.List.empty();
this[_resolvers] = List_mjs.List.empty();
this[_rejecters] = List_mjs.List.empty();
this[_resolve] = Maybe_mjs.none();
this[_reject] = Maybe_mjs.none();
this[_bottomRef] = Maybe_mjs.none();
this[_uuid] = Symbol('uuid');
this[_create](job, parent);
}
//private function.
[_create](job, parent) {
this[_setParent](parent);
this[_task] = job !== undefined ? Maybe_mjs.some(toFunction(job)) : Maybe_mjs.none();
return this;
};
[_setPromise](job) {
return setPromise(job);
};
[_setParent](parent) {
if (parent && parent.isTask && parent.isTask()) {
this[_parent] = Maybe_mjs.some((..._) => parent[_triggerUp](..._));
this[_topRef] = Maybe_mjs.some((..._) => parent[_getTopRef](..._));
this[_topParent] = Maybe_mjs.some((..._) => parent[_addParent](..._));
}
};
[_addParent](parent) {
this[_topParent].getOrElse((parent) => {
parent[_setChildren](this);
this[_setParent](parent);
})(parent);
return this;
};
[_setChildren](children) {
if (children && children.isTask && children.isTask()) {
this[_children] = this[_children].insert((..._) => children[_run](..._));
this[_bottomRef] = Maybe_mjs.some((..._) => children[_getBottomRef](..._));
}
};
[_resolveRun](data, uuid) {
this[_resolvers].forEach(fn => fn(data));
this[_resolve].getOrElse(emptyFn)(clone_mjs.clone(data));
this[_resolve] = Maybe_mjs.none();
if (uuid !== this[_uuid]) {
this[_triggerDown](data, true);
}
return clone_mjs.clone(data);
};
[_rejectRun](data) {
this[_rejecters].forEach(fn => fn(clone_mjs.clone(data)));
this[_reject].getOrElse(emptyFn)(clone_mjs.clone(data));
this[_reject] = Maybe_mjs.none();
this[_triggerDown](data, false);
return clone_mjs.clone(data);
};
[_triggerUp](uuid) {
return this[_parent].getOrElse(() => this[_run](undefined, true, uuid))();
};
[_triggerDown](data, resolve) {
this[_children].map(child => child(data, resolve));
};
[_run](data, success = true, uuid) {
return this[_setPromise](this[_task])(data, success)
.then((_) => this[_resolveRun](_, uuid))
.catch((_) => this[_rejectRun](_));
};
[_flatMap](fn) {
return this
.map(fn)
.map((responseTask) => {
if (!(responseTask.isTask && responseTask.isTask())) {
return Promise.reject('flatMap has to return task');
}
return responseTask.unsafeRun();
});
};
[_copyJob](parent) {
const job = task(this[_task].get(), parent);
job[_resolvers] = this[_resolvers];
job[_rejecters] = this[_rejecters];
if (parent) {
parent[_setChildren](job);
}
return job;
};
[_getTopRef](uuid, parent) {
return this[_topRef]
.getOrElse((uuid, parent) => this[_copy](uuid, parent))(uuid, parent);
};
[_getBottomRef](uuid, parent, goNext = false) {
const copyJob = goNext ? parent : this[_copyJob](parent);
const next = goNext || this[_uuid] === uuid;
return this[_bottomRef].getOrElse((uuid, job) => job)(uuid, copyJob, next);
}
[_copy](uuid) {
return this[_getBottomRef](uuid);
};
copy() {
return this[_getTopRef](this[_uuid]);
};
map(fn) {
const job = task(fn, this);
this[_setChildren](job);
return job;
};
flatMap(fn) {
return this[_flatMap](fn)
};
through(joined) {
return joined
.copy()
[_addParent](this);
};
forEach(fn) {
return this.map((d, res) => {
fn(d);
res(d);
});
};
resolve(fn) {
this[_resolvers] = this[_resolvers].insert(fn);
return this;
};
reject(fn) {
this[_rejecters] = this[_rejecters].insert(fn);
return this;
}
isTask() {
return this.toString() === '[object Task]';
}
toString() {
return '[object Task]'
};
clear() {
this[_resolvers] = List_mjs.List.empty();
this[_rejecters] = List_mjs.List.empty();
return this;
}
/**
* Method running executor and return Promise.
* @param resolve executed when resolved
* @param reject executed when rejected
* */
unsafeRun(resolve = emptyFn, reject = emptyFn) {
return new Promise((res, rej) => {
this[_resolve] = Maybe_mjs.some((data) => {
resolve(data);
res(data);
});
this[_reject] = Maybe_mjs.some((data) => {
reject(data);
rej(data);
});
this[_triggerUp](this[_uuid]);
});
};
static empty() {
return task();
};
static all(tasks = [], context = {}) {
return task()
.flatMap(() => task(
Promise.all(
tasks.map(_ => task(context)
.through(_)
.unsafeRun())
)
));
}
}
const task = (...tasks) => new Task(...tasks);
exports.Task = Task;
exports.task = task;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
var searchData=
[
['validate',['Validate',['../classCSF_1_1Zpt_1_1BatchRendering_1_1BatchRenderingOptionsValidator.html#aa6734e31491c63cf58ae84fae8a45b94',1,'CSF.Zpt.BatchRendering.BatchRenderingOptionsValidator.Validate()'],['../interfaceCSF_1_1Zpt_1_1BatchRendering_1_1IBatchRenderingOptionsValidator.html#a756a3e11cb1b1f71539adced1347ca83',1,'CSF.Zpt.BatchRendering.IBatchRenderingOptionsValidator.Validate()']]],
['validatebatchoptions',['ValidateBatchOptions',['../classCSF_1_1Zpt_1_1BatchRendering_1_1BatchRenderer.html#a07bc18dab6b1c97654fc4b55f4ad370c',1,'CSF::Zpt::BatchRendering::BatchRenderer']]],
['variablespecification',['VariableSpecification',['../classCSF_1_1Zpt_1_1ExpressionEvaluators_1_1CSharpExpressions_1_1Spec_1_1VariableSpecification.html#ac0b6da711873da11a52562178657b8af',1,'CSF.Zpt.ExpressionEvaluators.CSharpExpressions.Spec.VariableSpecification.VariableSpecification(string name)'],['../classCSF_1_1Zpt_1_1ExpressionEvaluators_1_1CSharpExpressions_1_1Spec_1_1VariableSpecification.html#a491012b7ad976e81295494e274bf1d5a',1,'CSF.Zpt.ExpressionEvaluators.CSharpExpressions.Spec.VariableSpecification.VariableSpecification(string name, string typeName)']]],
['variabletypedefinition',['VariableTypeDefinition',['../classCSF_1_1Zpt_1_1ExpressionEvaluators_1_1CSharpExpressions_1_1Spec_1_1VariableTypeDefinition.html#a06a1434f114eb05b907a242838692b44',1,'CSF::Zpt::ExpressionEvaluators::CSharpExpressions::Spec::VariableTypeDefinition']]],
['visit',['Visit',['../classCSF_1_1Zpt_1_1Metal_1_1MetalVisitor.html#a56121ae20d3dc853dbfc7a72b7669d1c',1,'CSF.Zpt.Metal.MetalVisitor.Visit()'],['../classCSF_1_1Zpt_1_1Rendering_1_1ContextVisitorBase.html#a295786b55bf01efbb1b37280059790cf',1,'CSF.Zpt.Rendering.ContextVisitorBase.Visit()'],['../classCSF_1_1Zpt_1_1Rendering_1_1NoOpVisitor.html#a56a4fa3f83df28d1d8cc8ce6bea6c332',1,'CSF.Zpt.Rendering.NoOpVisitor.Visit()'],['../classCSF_1_1Zpt_1_1SourceAnnotation_1_1SourceAnnotationVisitor.html#a3cfad929c7aca0783d2b5b00fc586998',1,'CSF.Zpt.SourceAnnotation.SourceAnnotationVisitor.Visit()'],['../classCSF_1_1Zpt_1_1SourceAnnotation_1_1SourceInfoBurnInVisitor.html#a50199f39850e1f742e49258ea0f52731',1,'CSF.Zpt.SourceAnnotation.SourceInfoBurnInVisitor.Visit()'],['../classCSF_1_1Zpt_1_1Tal_1_1TalVisitor.html#a1b837f0b88022cb2d07651ab754e4ac1',1,'CSF.Zpt.Tal.TalVisitor.Visit()']]],
['visitcontext',['VisitContext',['../classCSF_1_1Zpt_1_1Metal_1_1MetalTidyUpVisitor.html#ac7b9072e0c6bc215b946305cf070337d',1,'CSF.Zpt.Metal.MetalTidyUpVisitor.VisitContext()'],['../classCSF_1_1Zpt_1_1Rendering_1_1ContextVisitorBase.html#ab9579528e2ce5310759de0ffdd9f036b',1,'CSF.Zpt.Rendering.ContextVisitorBase.VisitContext()'],['../classCSF_1_1Zpt_1_1SourceAnnotation_1_1SourceInfoTidyUpVisitor.html#aec5a924d9ecc9a438168b0ba77cb2386',1,'CSF.Zpt.SourceAnnotation.SourceInfoTidyUpVisitor.VisitContext()'],['../classCSF_1_1Zpt_1_1Tal_1_1TalTidyUpVisitor.html#adf5444df529cb81faf2f9cb3ae3f0413',1,'CSF.Zpt.Tal.TalTidyUpVisitor.VisitContext()'],['../interfaceCSF_1_1Zpt_1_1Rendering_1_1IContextVisitor.html#ae0ca371cb2bba451c4e14fda2bdf03ec',1,'CSF.Zpt.Rendering.IContextVisitor.VisitContext()']]],
['visitrecursively',['VisitRecursively',['../classCSF_1_1Zpt_1_1Rendering_1_1ContextVisitorBase.html#ab7fc012aa9817b78a041b243a18d1d1e',1,'CSF.Zpt.Rendering.ContextVisitorBase.VisitRecursively()'],['../classCSF_1_1Zpt_1_1Tal_1_1TalVisitor.html#a5a4988a95454c36b82234f89607174b6',1,'CSF.Zpt.Tal.TalVisitor.VisitRecursively()']]]
];
|
/* @flow */
import _ from 'lodash';
import { inspectChain, innerChain } from './';
import { createChainBuilder, chainSymbol } from './chain-builder';
import type { ChainCreator } from './factories';
type DSL = {
[key: string]: (...args: Array<*>) => string,
};
function wrapBuilder(builder, dsl: DSL) {
return new Proxy(builder, {
get(target, name, receiver) {
if (_.has(dsl, name)) {
return (...args) => {
const dslChainProxy = dsl[name](...args);
const dslChain = dslChainProxy[chainSymbol];
target[chainSymbol].composeWith(dslChain);
return wrapBuilder(target, dsl);
};
}
// Handle String properties, but make sure to return a wrappedBuilder
// so custom steps can be chained after any other steps, either custom or
// generic.
if (_.isString(name)) {
return wrapBuilder(target[name], dsl);
}
// Do nothing, ie. forward Symbol objects to wrapped builder
return target[name];
},
apply(target, thisArg, args) {
// Intercept function call, and ensure we still return a wrappedBuilder
// so next steps can continue chaining custom steps as well as generic
// steps.
const toWrap = target(...args);
return wrapBuilder(toWrap, dsl);
},
});
}
export function createDsl(chainCreator: ChainCreator, dsl: DSL) {
return new Proxy(chainCreator, {
get(target, name, receiver) {
const builder = target[name];
return wrapBuilder(builder, dsl);
},
});
}
|
const helpers = require('../helpers');
const execSync = require('child_process').execSync;
const REPO_NAME_RE = /Push URL: https:\/\/github\.com\/.*\/(.*)\.git/;
function getWebpackConfigModule() {
if (helpers.hasProcessFlag('github-dev')) {
return require('../webpack.dev.js');
} else if (helpers.hasProcessFlag('github-prod')) {
return require('../webpack.prod.js');
} else {
throw new Error('Invalid compile option.');
}
}
function getRepoName(remoteName) {
remoteName = remoteName || 'origin';
var stdout = execSync('git remote show ' + remoteName),
match = REPO_NAME_RE.exec(stdout);
if (!match) {
return '/';
// throw new Error('Could not find a repository on remote ' + remoteName);
} else {
return match[1];
}
}
function stripTrailing(str, char) {
if (str[0] === char) {
str = str.substr(1);
}
if(str.substr(-1) === char) {
str = str.substr(0, str.length - 1);
}
return str;
}
/**
* Given a string remove trailing slashes and adds 1 slash at the end of the string.
*
* Example:
* safeUrl('/value/')
* // 'value/'
*
* @param url
* @returns {string}
*/
function safeUrl(url) {
const stripped = stripTrailing(url || '', '/');
return stripped ? stripped + '/' : ''
}
exports.getWebpackConfigModule = getWebpackConfigModule;
exports.getRepoName = getRepoName;
exports.safeUrl = safeUrl;
|
// Eloquent JavaScript
// Run this file in your terminal using `node my_solution.js`. Make sure it works before moving on!
// Program Structure
// Write your own variable and do something to it.
var myName = "Alex"
console.log(myName.length)
// var food = prompt("What is your favorite food?")
// alert(food + ' is my favorite too!')
// Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board
for (var i = 1; i <=100; i++){
if (i % 3 === 0 && i % 5 === 0){
console.log('FizzBuzz');
}
else if(i % 5 === 0){
console.log('Buzz');
}
else if(i % 3 === 0){
console.log('Fizz');
}
else{
console.log(i);
}
}
// Functions
function min(num1, num2){
if (num1 < num2) {
return num1;
}
else if (num1 > num2){
return num2;
}
else{
console.log("They are equal");
}
}
console.log(min(1,2))
min(2,2)
// Complete the `minimum` exercise.
// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.
var me = {
name:'Alex',
age: 26,
favorite_foods: ['pizza','ice-cream','pears'],
quirk:'I only like to wear one sock'
}; |
module.exports = {
name: "event",
ns: "hammerjs",
description: "Takes a hammer event and spreads it to the ports",
phrases: {
active: "Splitting event"
},
ports: {
input: {
event: {
title: "Event",
type: "object",
required: true
}
},
output: {
timestamp: {
title: "Timestamp",
type: "number",
description: "Time the event occurred"
},
target: {
title: "Target",
type: "any",
description: "Target element"
},
touches: {
title: "Touches",
type: "array",
description: "touches (fingers, mouse) on the screen"
},
pointerType: {
title: "Pointer Type",
type: "string",
description: "kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH"
},
center: {
title: "Center",
type: "object",
description: "center position of the touches. contains pageX and pageY"
},
deltaTime: {
title: "Delta Time",
type: "number",
description: "the total time of the touches in the screen"
},
deltaX: {
title: "Delta X",
type: "number",
description: "the delta on x axis we haved moved"
},
deltaY: {
title: "Delta Y",
type: "number",
description: "the delta on y axis we haved moved"
},
velocityX: {
title: "Velocity X",
type: "number",
description: "the velocity on the x axis"
},
velocityY: {
title: "Velocity Y",
type: "number",
description: "the velocity on the y axis"
},
angle: {
title: "Angle",
type: "number",
description: "the angle we are moving"
},
direction: {
title: "Direction",
type: "string",
description: "the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT"
},
distance: {
title: "Distance",
type: "number",
description: "the distance we haved moved"
},
scale: {
title: "Scale",
type: "number",
description: "scaling of the touches, needs 2 touches"
},
rotation: {
title: "Rotation",
type: "number",
description: "rotation of the touches, needs 2 touches"
},
eventType: {
title: "Event Type",
type: "string",
description: "matches Hammer.EVENT_START|MOVE|END"
},
srcEvent: {
title: "Source Event",
type: "object",
description: "the source event, like TouchStart or MouseDown"
}
}
},
fn: function event(input, $, output, state, done, cb, on) {
var r = function() {
// copies all the keys to ports
var keys = Object.keys($.event)
output = {}
for (var i = 0; i < keys.length; i++) {
output[keys[i]] = $.create($.event[keys[i]])
}
}.call(this);
return {
output: output,
state: state,
on: on,
return: r
};
}
} |
'use strict';
var Vec2 = require('./Common/Vec2');
/**
* The agents that live in the simulation engine.
*
* @class Agent
* @module CrowdSim
* @submodule Agent
* @constructor
* @param {Number} x coordinate
* @param {Number} y coordinate
* @param {Group} group parent
* @param {Object} options
*/
var Agent = function(x, y, group, options) {
var that = this;
this.id = Agent.id++;
// merge options with agent
Lazy(options).defaults(Agent.defaults).each(function(v, k) {
that[k] = v;
});
this.pos = Vec2.fromValues(x, y);
this.vel = Vec2.create();
this.group = group;
this.currentMobility = this.mobility;
if (this.debug) {
this.debug = {};
}
if (this.path) {
this.followPath(this.path, this.pathStart);
} else if (this.group.getEndContext()) {
this.setTargetInContext(this.group.getEndContext());
} else {
this.target = this.group;
}
};
/**
* Sets as the agent target the nearest point of a Context.
*
* @method setTargetInContext
* @param {Context} context
*/
Agent.prototype.setTargetInContext = function(context) {
// go to nearest point in contexts
var point = context.getNearestPoint(this.pos);
// generate virtual target
this.target = {pos: point, in: context.in.bind(context)};
};
/**
* Gets the aspect property. Used for color codes could be used for other purposes
*
* @method getAspect
* @return {Number} aspect
*/
Agent.prototype.getAspect = function() {
return this.aspect;
};
/**
* Get radius
* @method getRadius
* @return {Number} radius
*/
Agent.prototype.getRadius = function() {
return this.radius;
};
/**
* Set mobility correction applied to the current velocity
*
* @method setCurrentMobility
* @param {Number} mobility factor 0.0-1.0
*/
Agent.prototype.setCurrentMobility = function(mobility) {
this.currentMobility = mobility;
};
/**
* Set the agent to follow a give path starting at index.
*
* @method followPath
* @param {Path} path
* @param {Number} index position in path
*/
Agent.prototype.followPath = function(path, index) {
index = index || 0;
this.path = path;
if (path) {
this.pathStartIdx = index;
this._startPath();
} else {
this.target = null;
this.pathNextIdx = 0;
}
};
/**
* Helper to set the path start that takes into account inverse paths.
*
* @method _startPath
*/
Agent.prototype._startPath = function() {
this.joints = this.path.getJoints();
if (this.group.isPathReverse()) {
this.target = this.joints[this.pathStartIdx];
this.pathNextIdx = this.pathStartIdx - 1;
} else {
this.target = this.joints[this.pathStartIdx];
this.pathNextIdx = this.pathStartIdx + 1;
}
};
/**
* Advances the simulation of the agent one stepSize and moves the agent to its next possition defined by the group behavior mode.
*
* @method step
* @param {Number} stepSize defined by the simulation step size
*/
Agent.prototype.step = function(stepSize) {
var accel = this.group.behavior.getAccel(this, this.target);
if (this.debug) {
if (accel && (isNaN(accel[0]) || isNaN(accel[1]))) {
throw 'Agent pos invalid';
}
}
this.move(accel, stepSize);
// update target to next if arrive at current
var last = false;
if (this.target) {
if (this.pathNextIdx >= -1 && this.target.in(this.pos)) {
if (this.group.isPathReverse()) {
if (this.pathNextIdx >= 0) {
// follow to next waypoint
this.target = this.joints[this.pathNextIdx--];
} else {
last = true;
}
} else {
if (this.pathNextIdx < this.joints.length) {
// follow to next waypoint
this.target = this.joints[this.pathNextIdx++];
} else {
last = true;
}
}
if (last) { // last point check if is a circular path or end in endContext
if (this.group.isPathCircular()) {
this._startPath();
} else { // do one last trip for symetry to endContext if exists for symetry
var endContext = this.group.getEndContext();
if (endContext) {
this.setTargetInContext(endContext);
}
}
}
}
}
};
/**
* Moves the agent with the given accel => speed => position
*
* @method move
* @param {Number} accel
* @param {Number} stepSize simulation
*/
Agent.prototype.move = function(accel, stepSize) {
Vec2.scaleAndAdd(this.vel, this.vel, accel, stepSize);
if (Vec2.length(this.vel) > this.maxVel) {
Vec2.normalizeAndScale(this.vel, this.vel, this.maxVel * this.currentMobility);
}
Vec2.scaleAndAdd(this.pos, this.pos, this.vel, stepSize);
this.currentMobility = this.mobility; // restore mobility for next step reduced by contexts
};
Agent.defaults = {
aspect: 0xFFFFFF, // used for coloring
debug: false,
size: 0.5,
mass: 80e3,
mobility: 1.0,
maxAccel: 0.5, // m/s^2
maxVel: 1 // m/seg
};
Agent.id = 0;
Agent.type = 'agent';
module.exports = Agent;
|
module.exports = {
entry: './app/app.ts',
output: {
path: __dirname,
filename: "./dist/bundle.js"
},
resolve: {
extensions: ['', '.ts', '.js']
},
module: {
loaders: [
{ test: /\.ts$/, loader: 'ts-loader', exclude : /node_modules/ },
]
}
} |
/**
* Pipedrive API v1
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
import ProductSearchItemItemOwner from './ProductSearchItemItemOwner';
/**
* The ProductSearchItemItem model module.
* @module model/ProductSearchItemItem
* @version 1.0.0
*/
class ProductSearchItemItem {
/**
* Constructs a new <code>ProductSearchItemItem</code>.
* @alias module:model/ProductSearchItemItem
*/
constructor() {
ProductSearchItemItem.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>ProductSearchItemItem</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/ProductSearchItemItem} obj Optional instance to populate.
* @return {module:model/ProductSearchItemItem} The populated <code>ProductSearchItemItem</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ProductSearchItemItem();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
delete data['id'];
}
if (data.hasOwnProperty('type')) {
obj['type'] = ApiClient.convertToType(data['type'], 'String');
delete data['type'];
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
delete data['name'];
}
if (data.hasOwnProperty('code')) {
obj['code'] = ApiClient.convertToType(data['code'], 'Number');
delete data['code'];
}
if (data.hasOwnProperty('visible_to')) {
obj['visible_to'] = ApiClient.convertToType(data['visible_to'], 'Number');
delete data['visible_to'];
}
if (data.hasOwnProperty('owner')) {
obj['owner'] = ProductSearchItemItemOwner.constructFromObject(data['owner']);
delete data['owner'];
}
if (data.hasOwnProperty('custom_fields')) {
obj['custom_fields'] = ApiClient.convertToType(data['custom_fields'], 'Number');
delete data['custom_fields'];
}
if (Object.keys(data).length > 0) {
Object.assign(obj, data);
}
}
return obj;
}
}
/**
* The ID of the product
* @member {Number} id
*/
ProductSearchItemItem.prototype['id'] = undefined;
/**
* The type of the item
* @member {String} type
*/
ProductSearchItemItem.prototype['type'] = undefined;
/**
* The name of the product
* @member {String} name
*/
ProductSearchItemItem.prototype['name'] = undefined;
/**
* The code of the product
* @member {Number} code
*/
ProductSearchItemItem.prototype['code'] = undefined;
/**
* The visibility of the product
* @member {Number} visible_to
*/
ProductSearchItemItem.prototype['visible_to'] = undefined;
/**
* @member {module:model/ProductSearchItemItemOwner} owner
*/
ProductSearchItemItem.prototype['owner'] = undefined;
/**
* The custom fields
* @member {Number} custom_fields
*/
ProductSearchItemItem.prototype['custom_fields'] = undefined;
export default ProductSearchItemItem;
|
var canvas = null;
var ctx = null;
var assets = ['/media/img/gamedev/robowalk/robowalk00.png',
'/media/img/gamedev/robowalk/robowalk01.png',
'/media/img/gamedev/robowalk/robowalk02.png',
'/media/img/gamedev/robowalk/robowalk03.png',
'/media/img/gamedev/robowalk/robowalk04.png',
'/media/img/gamedev/robowalk/robowalk05.png',
'/media/img/gamedev/robowalk/robowalk06.png',
'/media/img/gamedev/robowalk/robowalk07.png',
'/media/img/gamedev/robowalk/robowalk08.png',
'/media/img/gamedev/robowalk/robowalk09.png',
'/media/img/gamedev/robowalk/robowalk10.png',
'/media/img/gamedev/robowalk/robowalk11.png',
'/media/img/gamedev/robowalk/robowalk12.png',
'/media/img/gamedev/robowalk/robowalk13.png',
'/media/img/gamedev/robowalk/robowalk14.png',
'/media/img/gamedev/robowalk/robowalk15.png',
'/media/img/gamedev/robowalk/robowalk16.png',
'/media/img/gamedev/robowalk/robowalk17.png',
'/media/img/gamedev/robowalk/robowalk18.png'
];
var frames = [];
var onImageLoad = function () {
console.log("IMAGE!!!");
};
var setup = function () {
body = document.getElementById('body');
canvas = document.createElement('canvas');
ctx = canvas.getContext('2d');
canvas.width = 100;
canvas.height = 100;
body.appendChild(canvas);
// Load each image URL from the assets array into the frames array
// in the correct order.
// Afterwards, call setInterval to run at a framerate of 30 frames
// per second, calling the animate function each time.
for (var i = 0; i < assets.length; i++) {
var img = new Image();
img.src = assets[i];
frames[i] = img;
}
setInterval(animate, 30);
};
var animate = function () {
// Draw each frame in order, looping back around to the
// beginning of the animation once you reach the end.
// Draw each frame at a position of (0,0) on the canvas.
// Try your code with this call to clearRect commented out
// and uncommented to see what happens!
ctx.clearRect(0,0,canvas.width, canvas.height);
for (var i = 0; i < frames.length; i++) {
ctx.drawImage(frames[i], 192, 192);
}
};
// We'll call your setup function in our test code, so
// don't call it in your code.
// setup(); |
/**
* Internal dependencies.
*/
var Surround = require('../lib/surround')
, index = require('../lib');
/**
* Simple object used for surrounding.
*/
var obj = {
bar: function() {}
};
describe('index', function() {
it('should return new Surround instnace', function() {
index(obj, 'bar').should.be.an.instanceof(Surround);
});
});
|
var Phase = require('./phase').Phase;
var start_tag_handlers = {
html: 'startTagHtml',
head: 'startTagHead',
'-default': 'startTagOther',
}
var end_tag_handlers = {
html: 'endTagImplyHead',
head: 'endTagImplyHead',
body: 'endTagImplyHead',
br: 'endTagImplyHead',
p: 'endTagImplyHead',
'-default': 'endTagOther',
}
var p = exports.Phase = function (parser, tree) {
Phase.call(this, parser, tree);
this.start_tag_handlers = start_tag_handlers;
this.end_tag_handlers = end_tag_handlers;
this.name = 'before_head_phase';
}
p.prototype = new Phase;
p.prototype.processEOF = function() {
this.startTagHead('head', {});
this.parser.phase.processEOF();
}
p.prototype.processCharacters = function(data) {
this.startTagHead('head', {});
this.parser.phase.processCharacters(data);
}
p.prototype.processSpaceCharacters = function(data) {
}
p.prototype.startTagHead = function(name, attributes) {
this.tree.insert_element(name, attributes);
this.tree.head_pointer = this.tree.open_elements.last();
this.parser.newPhase('inHead');
}
p.prototype.startTagOther = function(name, attributes) {
this.startTagHead('head', {});
this.parser.phase.processStartTag(name, attributes);
}
p.prototype.endTagImplyHead = function(name) {
this.startTagHead('head', {});
this.parser.phase.processEndTag(name);
}
p.prototype.endTagOther = function(name) {
this.parse_error('end-tag-after-implied-root', {name: name});
}
|
/**
* ConfigController
*
* @module :: Controller
* @description :: A set of functions called `actions`.
*
* Actions contain code telling Sails how to respond to a certain type of request.
* (i.e. do stuff, then send some JSON, show an HTML page, or redirect to another URL)
*
* You can configure the blueprint URLs which trigger these actions (`config/controllers.js`)
* and/or override them with custom routes (`config/routes.js`)
*
* NOTE: The code you write here supports both HTTP and Socket.io automatically.
*
* @docs :: http://sailsjs.org/#!documentation/controllers
*/
module.exports = {
/**
* Overrides for the settings in `config/controllers.js`
* (specific to ConfigController)
*/
_config: {},
find:function(req,res){
res.send({
name:"main",
static_url:sails.config.aws.cf_url,
default_deceased_image: sails.config.aws.deceased_image_path.replace(':name','default.jpg'),
menu:[
{
path:"/ads",
label:"Main"
},{
path:'/category/52a834a472b9d89814000002',
label:"Information",
},{
path:'/category/52a8349672b9d89814000001',
label:"Services"
}
]
});
}
};
|
class ValidationError extends Error {}
module.exports = ValidationError
|
var Web3 = require('web3');
var rpc = require('node-json-rpc');
var fs = require('fs');
var totGen, totCons, data;
var received = false;
/*============ Web3 Initialisation =============================*/
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
if (!web3.isConnected()) {
console.log("you are note connected to node...")
} else {
console.log("node is connected! \n web3 version:", web3.version.api)
}
/*=========== Contract ABI from a file and contract address ==================*/
var bisol_address = fs.readFileSync('../BISOL_implementation_1/BISOL_5.txt', 'utf8'); //address
const Abi = require('../BISOL_implementation_1/BISOL_5.json'); //abi
const Contract = web3.eth.contract(Abi);
const Bisol = Contract.at(bisol_address.trim());
/*============ Password from a file =========================*/
var password = fs.readFileSync('/home/nodepwrd.txt', 'utf8');
/*============ JSON-RPC communication to node ================================*/
var options = {
// int port of rpc server, default 5080 for http or 5433 for https
// for parity(default) 8545
port: 8545,
// string domain name or ip of rpc server, default '127.0.0.1'
host: '127.0.0.1',
// string with default path, default '/'
path: '/',
// boolean false to turn rpc checks off, default true
strict: true
};
// Create a client object with options
var client = new rpc.Client(options);
/*=========== Unlocking account for one transaction =======================*/
function unlockAndExecute(makeTransaction){
//makeTransaction - function that requres signing
//accIndex - index of your account in node
client.call(
{"method":"personal_unlockAccount","params": [web3.eth.accounts[0], password.trim(), null ],"id":1,"jsonrpc":"2.0"},
function (err, res) {
if (err) {
console.log(err);
}
else {
console.log(res);
console.log("signing transaction.....");
makeTransaction(); //function that requires unlocking account
}
}
);
}
/*================================Bisol contract interaction=============================*/
//trigger inputs from slaves
var initiate = function() {
Bisol.triggerInput({
from: web3.eth.accounts[0],
gas: 300000
});
}
//check if inputs from slaves are received
var watchReceived = function() {
console.log("starting to watch Received event")
var entities_length = web3.toDecimal(Bisol.getEntitiesCount());
var addr_array = Bisol.getEntity(entities_length - 1);
var last_addr = addr_array[0];
var filter = Bisol.Received({
fromBlock: 'latest',
toBlock: 'latest',
_from: last_addr
})
filter.watch(function(error, result) {
if (!error) {
console.log(result.args._result);
unlockAndExecute(agg);
}
});
}
//Calculating total consumption and generation
var agg = function() {
console.log("Calculating total consumption and generation")
Bisol.aggregate({
from: web3.eth.accounts[0],
gas: 300000
});
}
/*=================================================================================================*/
unlockAndExecute(initiate);
watchReceived();
|
if(Meteor.isServer){
Meteor.methods({
'getCurrentForecast': function(lat, lng){
check(lat, Number);
check(lng, Number);
var lastDatabase = Forecast.find({'owner_id': Meteor.userId()}).fetch();
var timeChecker;
if(lastDatabase[0]){
timeChecker = (moment().valueOf() - moment(lastDatabase[0].fetchTime).valueOf());
}
/* initiate database for the first time or update forecast data every 20 minutes = 1200000ms */
if(!lastDatabase[0] || timeChecker >= 1200000){
/* Fetch data from openweathermap.org */
var openWeatherMapData = Meteor.http.call('GET', 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lng + '&units=metric' + '&APPID=' + settings.services.openWeatherMapDataID );
var procOpenWeatherMapData = JSON.parse(openWeatherMapData.content);
/* Fetch data from forecast.io */
var forecastIOData = Meteor.http.call('GET', 'https://api.forecast.io/forecast/' + settings.services.forecastID + '/' + lat + ',' + lng + '/?units=si');
/* Initiate the graph data for the first time */
var graphInit;
var graphData = HourForecast.find({'owner_id': Meteor.userId()}).fetch();
if(!graphData[0]){
var date = new Date();
graphInit = true;
// Meteor.call('updateLogs', 'Account Creation', 'This ePersonal account has just been created.', date.toISOString()) // save logs for first account creation.
console.log('Forecast database created for ' + Meteor.userId() + ' at date: ' + date + '.');
} else {
graphInit = false;
}
/* Get fetch time in ISO time format */
var fetchTime = new Date(forecastIOData.data.currently.time * 1000);
var fetchTimeISO = fetchTime.toISOString();
console.log('Data now update at time: ' + fetchTime);
var sunriseTime = new Date(forecastIOData.data.daily.data[0].sunriseTime * 1000);
var sunriseTimeISO = sunriseTime.toISOString();
var sunsetTime = new Date(forecastIOData.data.daily.data[0].sunsetTime * 1000);
var sunsetTimeISO = sunsetTime.toISOString();
/* Get cloudiness percentage */
var cloudPercentage = (forecastIOData.data.currently.cloudCover * 100);
/* Get humidity percentage */
var humidityPercent = (forecastIOData.data.currently.humidity * 100);
/* Get precipitation percentage */
var precipitationPercent = (forecastIOData.data.currently.precipProbability * 100);
Forecast.remove({'owner_id': Meteor.userId()});
Forecast.insert({
'owner_id': Meteor.userId(), // Meteor.user().username
'created_at': new Date(),
'city': procOpenWeatherMapData.name,
'country': procOpenWeatherMapData.sys.country,
'icon': forecastIOData.data.currently.icon,
'temperature': (forecastIOData.data.currently.temperature).toFixed(2),
'forecast_statement': forecastIOData.data.hourly.summary,
'weather': forecastIOData.data.currently.summary,
'fetchTime': fetchTimeISO,
'windSpeed': (forecastIOData.data.currently.windSpeed).toFixed(2),
'windDegree': forecastIOData.data.currently.windBearing,
'cloudiness': cloudPercentage.toFixed(2),
'precipProbability': precipitationPercent.toFixed(2),
'precipType': forecastIOData.data.currently.precipType,
'pressure': (forecastIOData.data.currently.pressure).toFixed(2),
'humidity': humidityPercent.toFixed(2),
'sunrise': sunriseTimeISO,
'sunset': sunsetTimeISO,
'latitude': lat.toFixed(2),
'longitude': lng.toFixed(2)
});
/* HourForecast & TemperaturePattern & FullHourForecast Datasets Configurations */
var forecast_data = [], precipitation_value, arrayTemperature = [], fullForecast_data = [];
for (var i=0; i<forecastIOData.data.hourly.data.length; i++){ // total 49 points for 2 days
/* Get fetch time in ISO time format */
var fetchTime = new Date(forecastIOData.data.hourly.data[i].time * 1000);
var fetchTimeISO = fetchTime.toISOString();
/* Wind Speed */
var windSpeed_value = forecastIOData.data.hourly.data[i].windSpeed * 10;
/* Precipitation */
var precipitation_value = forecastIOData.data.hourly.data[i].precipIntensity * 100;
/* Initiate the forecast_data for the first time */
if(!forecast_data[0]){
/* Push all data into forecast_data in array form */
forecast_data.push({
'forecastTime': fetchTimeISO,
'time_checker': forecastIOData.data.hourly.data[i].time,
'precipitation': precipitation_value.toFixed(1), // divide 100 for actual value
'temperature': forecastIOData.data.hourly.data[i].temperature,
'weather': forecastIOData.data.hourly.data[i].summary,
'windSpeed': windSpeed_value.toFixed(1), // divide 10 for actual value
'windDegree': forecastIOData.data.hourly.data[i].windBearing,
'cloudiness': forecastIOData.data.hourly.data[i].cloudCover,
'pressure': forecastIOData.data.hourly.data[i].pressure,
'humidity': forecastIOData.data.hourly.data[i].humidity
});
}
else if (forecast_data[0] && forecast_data.length < 9){
var arrayValue = (forecast_data.length - 1);
/* Update the data every 3 hour interval, for 24 hours data = 9 values */
if((forecastIOData.data.hourly.data[i].time - forecast_data[arrayValue].time_checker) === 10800){
/* Push all data into forecast_data in array form */
forecast_data.push({
'forecastTime': fetchTimeISO,
'time_checker': forecastIOData.data.hourly.data[i].time,
'precipitation': precipitation_value.toFixed(1), // divide 100 for actual value
'temperature': forecastIOData.data.hourly.data[i].temperature,
'weather': forecastIOData.data.hourly.data[i].summary,
'windSpeed': windSpeed_value.toFixed(1), // divide 10 for actual value
'windDegree': forecastIOData.data.hourly.data[i].windBearing,
'cloudiness': forecastIOData.data.hourly.data[i].cloudCover,
'pressure': forecastIOData.data.hourly.data[i].pressure,
'humidity': forecastIOData.data.hourly.data[i].humidity
});
}
}
/* TemperaturePattern Datasets Configurations */
arrayTemperature.push({
'forecastTime': fetchTimeISO,
'temperature': forecastIOData.data.hourly.data[i].temperature
});
/* FullHourForecast Datasets Configurations */
fullForecast_data.push({
'forecastTime': fetchTimeISO,
'summary': forecastIOData.data.hourly.data[i].summary,
'precipType': forecastIOData.data.hourly.data[i].precipType,
'precipitation': (forecastIOData.data.hourly.data[i].precipIntensity).toFixed(1),
'windSpeed': (forecastIOData.data.hourly.data[i].windSpeed).toFixed(1),
'windDegree': (forecastIOData.data.hourly.data[i].windBearing).toFixed(1),
'pressure': (forecastIOData.data.hourly.data[i].pressure).toFixed(1),
'humidity': (forecastIOData.data.hourly.data[i].humidity * 100).toFixed(1), // divide 100 for actual value
'ozone': (forecastIOData.data.hourly.data[i].ozone).toFixed(1),
'temperature': (forecastIOData.data.hourly.data[i].temperature).toFixed(1), // use in graph
'cloudCover': (forecastIOData.data.hourly.data[i].cloudCover * 100).toFixed(1), // use in graph, divide 100 for actual value
'dewPoint': (forecastIOData.data.hourly.data[i].dewPoint).toFixed(1), // use in graph
'precipProbability': (forecastIOData.data.hourly.data[i].precipProbability * 100).toFixed(1), // use in graph, divide 100 for actual value
'precipitation_graph': precipitation_value.toFixed(1), // use in graph, divide 100 for actual value
'windSpeed_graph': windSpeed_value.toFixed(1), // use in graph, divide 10 for actual value
'pressure_graph': (forecastIOData.data.hourly.data[i].pressure/100).toFixed(1), // use in graph, times 100 for actual value
'ozone_graph': (forecastIOData.data.hourly.data[i].ozone/10).toFixed(1) // use in graph, times 10 for actual value
});
}
/* Update the HourForecast in database */
HourForecast.remove({'owner_id': Meteor.userId()});
HourForecast.insert({
'owner_id': Meteor.userId(),
'created_at': new Date(),
'city': procOpenWeatherMapData.name,
'country': procOpenWeatherMapData.sys.country,
'forecast_data': forecast_data,
'latitude': lat.toFixed(2),
'longitude': lng.toFixed(2)
});
/* Update the TemperaturePattern in database */
TemperaturePattern.remove({'owner_id': Meteor.userId()});
TemperaturePattern.insert({
'owner_id': Meteor.userId(),
'created_at': new Date(),
'temperature_pattern': arrayTemperature
});
/* Update the FullHourForecast in database */
FullHourForecast.remove({'owner_id': Meteor.userId()});
FullHourForecast.insert({
'owner_id': Meteor.userId(),
'created_at': new Date(),
'forecast_data': fullForecast_data
});
/* Tell the client if this is the first time render graph */
return graphInit;
}
}
});
} |
/*
* Copyright (c) 2011-2012, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
var knox = require('knox'),
Crypto = require('crypto'),
mime = require('mime');
/**
* Send blob to S3 with an optional checksum in the filename.
*
* @param options {Object} S3 task options.
* @param options.name {String} Resource name.
* @param options.client {Object} S3 client (key, secret, bucket).
* @param blob {Object} Incoming blob.
* @param done {Function} Callback on task completion.
*/
var s3 = exports.s3 = function s3(options, blob, done) {
var self = this,
name = options.name,
result,
client,
checksum,
req;
result = blob.result;
client = knox.createClient(options.client);
if (name.indexOf('{checksum}') > -1) { // Replace {checksum} with md5 string
checksum = Crypto.createHash('md5');
checksum.update(result);
name = name.replace('{checksum}', checksum.digest('hex'));
}
req = client.put(name, {'Content-Length': result.length, 'Content-Type': mime.lookup(name)});
req.on('response', function (res) {
if (res.statusCode === 200) {
done(null, new blob.constructor(result, {name: name, url: req.url}));
} else {
done('Failed to write to S3');
}
});
req.end(result);
};
s3.type = 'slice'; |
"use strict";
module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars
ecs.addEach(function depositPods(player, elapsed) { // eslint-disable-line no-unused-vars
var playerCollisions = data.entities.get(player, "collisions");
var inventory = data.entities.get(player, "inventory");
for (var i = 0; i < playerCollisions.length; i++) {
var other = playerCollisions[i];
if (data.entities.get(other, "bin") && inventory.used > 0) {
//confirm("Deposit your pods?");
var timers = data.entities.get(player, "timers");
timers.deposit.running = true;
}
}
}, "player");
};
|
/*
* leap.coffee
a flow-control tool
(c) 2013 Vladimir Tarasov
Leap is unspired by:
- [invoke.js](https://github.com/repeatingbeats/invoke) by Steve Lloyd
- [first](https://github.com/DanielBaulig/first) by Daniel Baulig
- [async.js](https://github.com/caolan/async) by Caolan McMahon
Leap is freely distributable under the terms of the [MIT license](http://en.wikipedia.org/wiki/MIT_License).
All merit is dedicated to the benefit of all beings.
*/
(function() {
var slice = [].slice,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
!(function(name, definition) {
if (typeof module !== "undefined" && module !== null ? module.exports : void 0) {
return typeof module !== "undefined" && module !== null ? module.exports = definition() : void 0;
} else if (typeof define !== "undefined" && define !== null ? define.amd : void 0) {
return define(name, definition);
} else {
return this[name] = definition();
}
})('leap', function() {
var Flow, FlowWithManualStart, Step, _property, defer, identity, leap;
defer = (typeof process !== "undefined" && process !== null ? process.nextTick : void 0) || function(f) {
return setTimeout(f, 1);
};
identity = function(x, cb) {
return cb(null, x);
};
Flow = (function() {
function Flow() {
var fns;
fns = 1 <= arguments.length ? slice.call(arguments, 0) : [];
this.current = this.root = new Step(this._wrap_first(fns));
this.then.flow = this;
this.and.flow = this;
if (!this.manual_start) {
defer((function(_this) {
return function() {
return _this.yeah();
};
})(this));
}
}
Flow.prototype.then = function() {
var fn;
fn = 1 <= arguments.length ? slice.call(arguments, 0) : [];
this.current = this.current.child(fn);
return this;
};
Flow.prototype.and = function(fn) {
if (this.current === this.root) {
fn = this._wrap_first(fn);
}
this.current.sibling(fn);
return this;
};
Flow.prototype.identity = function() {
if (this.current === this.root) {
this.then(identity);
}
return this.and(identity);
};
Flow.prototype.rescue = function(fn) {
this._rescue = fn;
return this;
};
Flow.prototype._rescue = function(err) {
throw Error(err);
};
Flow.prototype.yeah = function() {
return this.root.run(null, this._rescue);
};
Flow.prototype.back = function(fn) {
this.then(function(x) {
return fn(null, x);
});
return this.rescue(fn);
};
Flow.prototype._wrap_first = function(fn) {
var addF, f, j, len1, res;
if (Array.isArray(fn)) {
res = [];
addF = function(fun) {
return res.push(function(___, next) {
return fun.call(next, next);
});
};
for (j = 0, len1 = fn.length; j < len1; j++) {
f = fn[j];
addF(f);
}
return res;
} else {
return function(___, next) {
return fn.call(next, next);
};
}
};
return Flow;
})();
Step = (function() {
Step.prototype.functions = [];
function Step(actions) {
this._next = this._err = null;
if (Array.isArray(actions)) {
this.functions = actions;
} else if (typeof actions === 'function') {
this.functions = [actions];
}
}
Step.prototype.child = function(fn) {
return this._next = new Step(fn);
};
Step.prototype.sibling = function(fn) {
return this.functions.push(fn);
};
Step.prototype.run = function(passed, rescue) {
var completed, f, i, j, len, len1, parallel, ref, results, results1;
len = this.functions.length;
results = [];
completed = 0;
parallel = (function(_this) {
return function(index, fn) {
var callback;
callback = function(err, res) {
if (_this.err) {
return;
}
if (err) {
_this.err = err;
return rescue(err);
}
if (len === 1) {
results = res;
} else {
results[index] = res;
}
if (_this._next && ++completed === len) {
return _this._next.run(results, rescue);
}
};
callback.next = callback.cb = function(res) {
var arg;
arg = Array.prototype.slice.call(arguments);
arg.unshift(null);
return callback.apply(this, arg);
};
if (typeof Backbone !== 'undefined') {
callback.bb = {
success: function() {
var arg;
arg = Array.prototype.slice.call(arguments);
arg.unshift(null);
return callback.call(this, arg);
},
error: function() {
return callback.call(this, Array.prototype.slice.call(arguments));
}
};
}
return fn.apply(callback, [passed, callback]);
};
})(this);
ref = this.functions;
results1 = [];
for (i = j = 0, len1 = ref.length; j < len1; i = ++j) {
f = ref[i];
results1.push(parallel(i, f));
}
return results1;
};
return Step;
})();
leap = function() {
var fn;
fn = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Flow, fn, function(){});
};
FlowWithManualStart = (function(superClass) {
extend(FlowWithManualStart, superClass);
function FlowWithManualStart() {
return FlowWithManualStart.__super__.constructor.apply(this, arguments);
}
FlowWithManualStart.prototype.manual_start = true;
return FlowWithManualStart;
})(Flow);
leap["export"] = function() {
var fn;
fn = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(FlowWithManualStart, fn, function(){});
};
leap.map = function(collection, iterator, next) {
var flow, fn1, i, j, len1;
flow = new Flow;
if (!collection || collection.length === 0) {
flow.and(function() {
return this();
}).then(function() {
return this.next([]);
});
} else {
fn1 = function(param) {
return flow.and(function() {
return iterator.call(this, param, this);
});
};
for (j = 0, len1 = collection.length; j < len1; j++) {
i = collection[j];
fn1(i);
}
if (collection.length === 1) {
flow.then(function(res) {
return this.next([res]);
});
}
}
if (next) {
flow.then(function(res) {
return next(null, res);
});
flow.rescue(next);
}
return flow;
};
Flow.prototype.then.map = function(fn) {
return this.flow.then(function(arr, cb) {
return leap.map(arr, fn, cb);
});
};
Flow.prototype.and.map = function(fn) {
return this.flow.and(function(arr, cb) {
return leap.map(arr, fn, cb);
});
};
leap.reduce = function(collection, iterator, next) {
var flow, fn1, i, j, len1;
flow = new Flow(function() {
return this();
});
fn1 = function(param) {
return flow.then(function(memo) {
return iterator.call(this, param, memo, this);
});
};
for (j = 0, len1 = collection.length; j < len1; j++) {
i = collection[j];
fn1(i);
}
if (next) {
flow.then(function(res) {
return next(null, res);
});
flow.rescue(next);
}
return flow;
};
Flow.prototype.then.reduce = function(fn) {
return this.flow.then(function(arr, cb) {
return leap.reduce(arr, fn, cb);
});
};
Flow.prototype.and.reduce = function(fn) {
return this.flow.and(function(arr, cb) {
return leap.reduce(arr, fn, cb);
});
};
leap.filter = function(collection, iterator, next) {
return leap.map(collection, iterator).then(function(arr) {
var i, j, len1, res, val;
res = [];
for (i = j = 0, len1 = arr.length; j < len1; i = ++j) {
val = arr[i];
if (val) {
res.push(collection[i]);
}
}
if (next) {
return next(null, res);
}
return this.next(res);
});
};
Flow.prototype.then.filter = function(fn) {
return this.flow.then(function(arr, cb) {
return leap.filter(arr, fn, cb);
});
};
Flow.prototype.and.filter = function(fn) {
return this.flow.and(function(arr, cb) {
return leap.filter(arr, fn, cb);
});
};
leap.reject = function(collection, iterator, next) {
return leap.map(collection, iterator).then(function(arr) {
var i, j, len1, res, val;
res = [];
for (i = j = 0, len1 = arr.length; j < len1; i = ++j) {
val = arr[i];
if (!val) {
res.push(collection[i]);
}
}
if (next) {
return next(null, res);
}
return this.next(res);
});
};
Flow.prototype.then.reject = function(fn) {
return this.flow.then(function(arr, cb) {
return leap.reject(arr, fn, cb);
});
};
Flow.prototype.and.reject = function(fn) {
return this.flow.and(function(arr, cb) {
return leap.reject(arr, fn, cb);
});
};
_property = function(key) {
return function(obj) {
return obj[key];
};
};
leap.pluck = function(key) {
return function(collection, next) {
return this(null, collection.map(_property(key)));
};
};
Flow.prototype.then.pluck = function(key) {
return this.flow.then(leap.pluck(key));
};
leap.I = identity;
leap.of = {
faith: leap
};
leap.VERSION = "0.1.3";
return leap;
});
}).call(this);
|
var Benchmark = require('benchmark'),
benchmarks = require('beautify-benchmark'),
isUri = require('..'),
suite = new Benchmark.Suite,
testUri = 'http://asdf:qw%20er@[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8000?asdf=12345&asda=fc%2F#bacon';
suite.add({
name: 'isUri#test(uri)',
minSamples: 100,
fn: function () {
isUri.isValid(testUri);
}
}).on('start', function onCycle() {
process.stdout.write(' Testing URI "' + testUri + '"\n\n')
}).on('cycle', function onCycle(event) {
benchmarks.add(event.target);
}).on('complete', function onComplete() {
benchmarks.log();
}).run(); |
'use strict';
const uuid = require('uuid');
const autoBind = require('auto-bind');
/**
* @class InMemoryDB
*/
class InMemoryDB {
constructor() {
this.data = {};
autoBind(this);
}
findAll(cb) {
const self = this;
const results = Object.keys(self.data).map(key => self.data[key]);
return cb(null, results);
}
findOne(id, cb) {
const self = this;
const result = self.data[id] || null;
return cb(null, result);
}
add(obj, options, cb) {
const self = this;
if (typeof options === 'function') {
cb = options;
options = {};
}
const id = obj._id ? obj._id : uuid.v4();
self.data[id] = Object.assign(obj, { _id: id });
if (options.expire) {
setTimeout(() => {
delete self.data[obj._id];
}, options.expire);
}
return cb(null, obj);
}
clear(cb) {
this.data = {};
cb && cb();
}
update(entity, cb) {
const self = this;
if (self.data[entity._id]) {
Object.assign(self.data[entity._id], entity);
return cb(null, self.data[entity._id]);
}
cb(null, null);
}
remove(id, cb) {
const self = this;
if (self.data[id]) {
const obj = self.data[id];
delete self.data[id];
return cb(null, obj);
}
cb(null, null);
}
disconnect(cb){
cb && cb();
}
}
module.exports = InMemoryDB;
|
'use strict'
const {create, loader, plugin} = require('./config')
const plugins = [
plugin.prodEnv,
plugin.occurrence,
plugin.dedupe,
plugin.uglifyJs,
plugin.extractCss
]
const loaders = [loader.worker, loader.babel, loader.cssExtracted, loader.markdown]
module.exports = create(plugins, loaders)
|
/*****************************************************************************/
/* Utility Methods */
/*****************************************************************************/
Meteor.methods({
/*
* Example:
* '/app/utility/update/email': function (email) {
* Users.update({_id: this.userId}, {$set: {'profile.email': email}});
* }
*
*/
}); |
datab = [{},{"Coding Scheme Designator":{"colspan":"1","rowspan":"1","text":"SRT"},"Code Value":{"colspan":"1","rowspan":"1","text":"R-10260"},"Code Meaning":{"colspan":"1","rowspan":"1","text":"Estimated"},"SNOMED-CT Concept ID":{"colspan":"1","rowspan":"1","text":"414135002"},"UMLS Concept Unique ID":{"colspan":"1","rowspan":"1","text":"C0750572"}},{"Coding Scheme Designator":{"colspan":"1","rowspan":"1","text":"SRT"},"Code Value":{"colspan":"1","rowspan":"1","text":"R-41D2D"},"Code Meaning":{"colspan":"1","rowspan":"1","text":"Calculated"},"SNOMED-CT Concept ID":{"colspan":"1","rowspan":"1","text":"258090004"},"UMLS Concept Unique ID":{"colspan":"1","rowspan":"1","text":"C0444686"}}]; |
var DependencyDiagram = {
_data : null,
_container : null,
_chord : null,
_group : null,
_chordSystems : [],
_chordData : [],
_sortProperties : [],
_sortDirections: [],
_refreshMethod : null,
_refreshComponent : null,
_collapseStates : [],
_searchText : "",
init : function() {
DependencyDiagram._sortProperties = ["id","id","id"];
DependencyDiagram._sortDirections = ["asc","asc","asc"];
DependencyDiagram._collapseStates = [false, true, true];
},
refresh : function() {
DependencyDiagram._chordSystems = [];
DependencyDiagram._chordData = [];
$("#dependencyDiagramCanvas").empty();
var width = $(window).height() - 130,
height = width,
outerRadius = Math.min(width, height) / 2 - 10,
innerRadius = outerRadius - 48;
var depth = DependencyDiagram._data.components.length;
var parseComponents = [];
for (var i=0;i<depth;i++)
{
parseComponents.push([]);
if (DependencyDiagram._data.components[i].services && DependencyDiagram._data.components[i].services.length > 0) {
for (var j=0;j<depth;j++)
{
if (DependencyDiagram._data.components[j].dependsOn && DependencyDiagram._data.components[j].dependsOn.length > 0) {
// return # of endpoints that component[j] has dependencies for
var dependencies = 0;
var result = jQuery.each(DependencyDiagram._data.components[j].dependsOn,
function(dIndex) {
jQuery.each(DependencyDiagram._data.components[i].services,
function(sIndex) {
dependencies+=(DependencyDiagram._data.components[i].services[sIndex].id === DependencyDiagram._data.components[j].dependsOn[dIndex].endpointId)?1:0;
});
}
);
parseComponents[i].push(dependencies);
} else parseComponents[i].push(0);
}
} else {
for (var k=0;k<depth;k++) {
parseComponents[i].push(0);
}
}
}
for (var i=0;i<parseComponents.length;i++)
{
var sum = parseComponents[i].reduce((a,b) => a + b, 0);
DependencyDiagram._chordSystems.push(DependencyDiagram._data.components[i]);
DependencyDiagram._chordData.push(parseComponents[i]);
}
var arc = d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius);
var layout = d3.layout.chord().padding(.04).sortSubgroups(d3.descending).sortChords(d3.ascending);
var path = d3.svg.chord().radius(innerRadius);
var svg = d3.select("#dependencyDiagramCanvas").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "circle")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
svg.append("circle").attr("r", outerRadius);
layout.matrix(DependencyDiagram._chordData);
DependencyDiagram._group = svg.selectAll("g.group")
.data(layout.groups())
.enter().append("svg:g")
.attr("class", "group")
.on("mouseover", DependencyDiagram.groupMouseover)
.on("click", DependencyDiagram.renderComponentInfo)
.on("mouseout", function (d) { d3.select("#tooltip").style("visibility", "hidden") });
var groupPath = DependencyDiagram._group.append("svg:path")
.attr("id", function(d, i) { return "group" + i; })
.attr("d", arc)
.style("fill", function(d, i) {
return (DependencyDiagram.findSearchMatchesInComponent(DependencyDiagram._chordSystems[i])?"#33FF33":DependencyDiagram._chordSystems[i].color);
});
var groupText = DependencyDiagram._group.append("text").attr("dx", 6).attr("dy", 15);
groupText.append("textPath")
.attr("xlink:href", function(d, i) { return "#group" + i; })
.text(function(d, i) { return DependencyDiagram._chordSystems[i].acronym; });
DependencyDiagram._chord = svg.selectAll("path.chord")
.data(layout.chords)
.enter().append("svg:path")
.attr("class", "chord")
.style("fill", function(d) {
var sourceComponent = DependencyDiagram._chordSystems[d.source.index];
var targetComponent = DependencyDiagram._chordSystems[d.target.index];
var dependentServices = DependencyDiagram.getDependentServices(sourceComponent, targetComponent);
for (var i=0;i<dependentServices.length;i++) {
if (DependencyDiagram.findSearchMatchesForService(dependentServices[i])) return "#33FF33";
}
return sourceComponent.color;
})
.attr("d", path)
.on("click", function(d) { DependencyDiagram.renderEndpointInfo(d); })
.on("mouseover", DependencyDiagram.chordMouseover);
},
render : function(container, data) {
$(container).load("./templates/dependencyDiagram.htm?uuid=" + DependencyDiagram.generateUUID(), function() {
DependencyDiagram._data = data;
DependencyDiagram._container = container;
DependencyDiagram.init();
DependencyDiagram.refresh();
});
window.addEventListener("resize", DependencyDiagram.refresh)
},
refreshInfo : function() {
if (DependencyDiagram._refreshComponent !== null)
(DependencyDiagram._refreshMethod === "endpoint")?DependencyDiagram.renderEndpointInfo(DependencyDiagram._refreshComponent):DependencyDiagram.renderComponentInfo(DependencyDiagram._refreshComponent);
},
renderEndpointInfo :function(d) {
DependencyDiagram._refreshComponent = d;
DependencyDiagram._refreshMethod = "endpoint";
var sourceComponent = DependencyDiagram._chordSystems[d.source.index];
var targetComponent = DependencyDiagram._chordSystems[d.target.index];
var dependsOnList = DependencyDiagram._chordSystems[d.target.index].dependsOn;
var html = new Array();
html.push("<div class='panel-group' id='endpointInfoAccordian'>");
html.push("<div class='infoHeader infoHeader-source'>" + targetComponent.acronym + " using " + sourceComponent.acronym + "</div>");
html.push("<div class='panel panel-default'>");
html.push("<div class='panel-heading'>");
html.push("<h4 class='panel-title'><a data-toggle='collapse' data-parent='#endpointInfoAccordian' href='#collapseEndpoints' onclick='DependencyDiagram.rememberCollapse(0,this)'>Endpoints</a></h4>");
html.push("</div>");
html.push("<div id='collapseEndpoints' class='panel-collapse collapse" + (DependencyDiagram._collapseStates[0]===true?"":" in") + "'>");
html.push("<div class='panel-body dd-panel-scrollable'>");
html.push("<table class='table table-condensed'>");
html.push("<thead><tr><th class='dd-column-sortable' column='id' onclick='DependencyDiagram.handleSortClick(0,this)'>ID</th><th class='dd-column-sortable' column='description' onclick='DependencyDiagram.handleSortClick(0,this)'>Description</th><th class='dd-column-sortable' column='endpointSig' onclick='DependencyDiagram.handleSortClick(0,this)'>Signature</th><th>Method</th></tr></thead><tbody>");
var resultSet = [];
for (var i=0;i<dependsOnList.length;i++) {
var service = DependencyDiagram._chordSystems[d.source.index].services.find(function(service) {
return dependsOnList[i].endpointId === service.id;
});
if (service) resultSet.push(service);
}
var sortedResultSet = DependencyDiagram.sortColumns(0, resultSet);
for (var i=0;i<sortedResultSet.length;i++)
{
var service = sortedResultSet[i];
var classTag = "dd-rowInfo";
if (DependencyDiagram.findSearchMatchesForService(service)) classTag += " dd-searchMatch";
html.push("<tr class='" + classTag + "' link='" + service.docLink + "' onclick='DependencyDiagram.handleDocClick(this)'><td>" + service.id + "</td><td>" + service.description + "</td><td>" + service.endpointSig + "</td><td>" + service.endpointType + " " + service.endpointVerb + "</td></tr>");
}
html.push("</tbody></table>");
html.push("</div></div>");
$("#dependencyDiagramInfo").empty().append(html.join(""))
$(".infoHeader-target").css("background-color", DependencyDiagram._chordSystems[d.target.index].color);
$(".infoHeader-source").css("background-color", DependencyDiagram._chordSystems[d.source.index].color);
$(".info").css("display", "inline-block");
},
renderComponentInfo(d) {
DependencyDiagram._refreshComponent = d;
DependencyDiagram._refreshMethod = "component";
var component = DependencyDiagram._chordSystems[d.index];
var html = new Array();
html.push("<div class='panel-group' id='endpointInfoAccordian'>");
html.push("<div class='infoHeader infoHeader-source'>" + component.acronym + "</div>");
html.push("<div class='panel panel-default'>");
html.push("<div class='panel-heading'>");
html.push("<h4 class='panel-title'><a data-toggle='collapse' data-parent='#endpointInfoAccordian' href='#collapseEndpoints' onclick='DependencyDiagram.rememberCollapse(0,this)'>Endpoints</a></h4>");
html.push("</div>");
html.push("<div id='collapseEndpoints' class='panel-collapse collapse" + (DependencyDiagram._collapseStates[0]===true?"":" in") + "'>");
html.push("<div class='panel-body dd-panel-scrollable'>");
html.push("<table class='table table-condensed'>");
html.push("<thead><tr><th class='dd-column-sortable' column='id' onclick='DependencyDiagram.handleSortClick(0,this)'>ID</th><th class='dd-column-sortable' column='description' onclick='DependencyDiagram.handleSortClick(0,this)'>Description</th><th class='dd-column-sortable' column='endpointSig' onclick='DependencyDiagram.handleSortClick(0,this)'>Signature</th><th>Method</th></tr></thead><tbody>");
var sortedResultSet = DependencyDiagram.sortColumns(0, component.services);
for (var i=0;i<sortedResultSet.length;i++) {
var service = sortedResultSet[i];
var classTag = "dd-rowInfo";
if (DependencyDiagram.findSearchMatchesForService(service)) classTag += " dd-searchMatch";
html.push("<tr class='" + classTag + "' link='" + service.docLink + "' onclick='DependencyDiagram.handleDocClick(this)'><td>" + service.id + "</td><td>" + service.description + "</td><td>" + service.endpointSig + "</td><td>" + service.endpointType + " " + service.endpointVerb + "</td></tr>");
}
html.push("</tbody></table>");
html.push("</div></div>");
var targetAcronym = component.id;
html.push("<div class='panel panel-default'>");
html.push("<div class='panel-heading'>");
html.push("<h4 class='panel-title'><a data-toggle='collapse' data-parent='#endpointInfoAccordian' href='#collapseDependents' onclick='DependencyDiagram.rememberCollapse(1,this)'>Dependents</a></h4>");
html.push("</div>");
html.push("<div id='collapseDependents' class='panel-collapse collapse" + (DependencyDiagram._collapseStates[1]===true?"":" in") + "'>");
html.push("<div class='panel-body dd-panel-scrollable'>");
html.push("<table class='table table-condensed'>");
html.push("<thead><tr><th class='dd-column-sortable' column='id' onclick='DependencyDiagram.handleSortClick(1,this)'>ID</th><th class='dd-column-sortable' column='acronym' onclick='DependencyDiagram.handleSortClick(1,this)'>Called By</th><th class='dd-column-sortable' column='endpointSig' onclick='DependencyDiagram.handleSortClick(1,this)'>Signature</th><th>Method</th></tr></thead><tbody>");
var resultSet = [];
for (var i=0;i<DependencyDiagram._chordSystems.length;i++) {
var dependentComponent = DependencyDiagram._chordSystems[i];
if (dependentComponent.dependsOn) {
for (var j=0;j<dependentComponent.dependsOn.length;j++) {
if (dependentComponent.dependsOn[j].endpointId.startsWith(component.acronym))
{
var service = component.services.find(function(service) {
return dependentComponent.dependsOn[j].endpointId === service.id;
});
if (service)
resultSet.push({"docLink" : service.docLink, "id" : dependentComponent.dependsOn[j].endpointId, "acronym" : dependentComponent.acronym, "endpointSig" : service.endpointSig, "endpointType" : service.endpointType, "endpointVerb" : service.endpointVerb});
}
}
}
}
var sortedResultSet = DependencyDiagram.sortColumns(1, resultSet);
for (var i=0;i<sortedResultSet.length;i++) {
var service = sortedResultSet[i];
var classTag = "dd-rowInfo";
if (DependencyDiagram.findSearchMatchesForService(service)) classTag += " dd-searchMatch";
html.push("<tr class='" + classTag + "' link='" + service.docLink + "' onclick='DependencyDiagram.handleDocClick(this)'><td>" + service.id + "</td><td>" + service.acronym + "</td><td>" + service.endpointSig + "</td><td>" + service.endpointType + " " + service.endpointVerb + "</td></tr>");
}
html.push("</tbody></table>")
html.push("</div></div>");
html.push("<div class='panel panel-default'>");
html.push("<div class='panel-heading'>");
html.push("<h4 class='panel-title'><a data-toggle='collapse' data-parent='#endpointInfoAccordian' href='#collapseDependendencies' onclick='DependencyDiagram.rememberCollapse(2,this)'>Dependencies</a></h4>");
html.push("</div>");
html.push("<div id='collapseDependendencies' class='panel-collapse collapse" + (DependencyDiagram._collapseStates[2]===true?"":" in") + "'>");
html.push("<div class='panel-body dd-panel-scrollable'>");
html.push("<table class='table table-condensed'>");
html.push("<thead><tr><th class='dd-column-sortable' column='acronym' onclick='DependencyDiagram.handleSortClick(2,this)'>Dependency</th><th class='dd-column-sortable' column='id' onclick='DependencyDiagram.handleSortClick(2,this)'>Depends On</th><th class='dd-column-sortable' column='endpointSig' onclick='DependencyDiagram.handleSortClick(2,this)'>Signature</th><th>Method</th></tr></thead><tbody>");
var resultSet = [];
if (component.dependsOn) {
for (var i=0;i<component.dependsOn.length;i++) {
var dependComponent = DependencyDiagram._chordSystems.find(function(dependComponent) {
return (component.dependsOn[i].endpointId.startsWith(dependComponent.acronym));
});
if (dependComponent) {
var dependService = dependComponent.services.find(function(dependService) {
return (component.dependsOn[i].endpointId === dependService.id);
});
if (dependService)
resultSet.push({"docLink" : dependService.docLink, "acronym" : dependComponent.acronym, "id" : component.dependsOn[i].endpointId, "endpointSig" : dependService.endpointSig, "endpointType" : dependService.endpointType, "endpointVerb" : dependService.endpointVerb});
} else {
// cannot find component
}
}
var sortedResultSet = DependencyDiagram.sortColumns(2, resultSet);
for (var i=0;i<sortedResultSet.length;i++) {
var service = sortedResultSet[i];
var classTag = "dd-rowInfo";
if (DependencyDiagram.findSearchMatchesForService(service)) classTag += " dd-searchMatch";
html.push("<tr class='" + classTag + "' link='" + service.docLink + "' onclick='DependencyDiagram.handleDocClick(this)'><td>" + service.acronym + "</td><td>" + service.id + "</td><td>" + service.endpointSig + "</td><td>" + service.endpointType + " " + service.endpointVerb + "</td></tr>");
}
} else {
html.push("<tr><td colspan='4'>No dependencies</td></tr>");
}
html.push("</tbody></table>")
html.push("</div></div>");
html.push("</div>"); // panel panel-default
html.push("</div>");
$("#dependencyDiagramInfo").empty().append(html.join(""))
$(".infoHeader").css("background-color", DependencyDiagram._chordSystems[d.index].color);
$(".info").css("display", "inline-block");
},
groupTip : function(d) {
var endpointCount = (DependencyDiagram._chordSystems[d.index].services)?DependencyDiagram._chordSystems[d.index].services.length:0;
var dependentCount = DependencyDiagram._chordData[d.index].reduce((a,b) => a + b, 0);
var dependencyCount = (DependencyDiagram._chordSystems[d.index].dependsOn)?DependencyDiagram._chordSystems[d.index].dependsOn.length:0;
return DependencyDiagram._chordSystems[d.index].name + "<br/>" + endpointCount + " endpoints<br />" + dependentCount + " dependents<br />" + dependencyCount + " dependencies" ;
},
chordTip : function(d) {
return DependencyDiagram._chordSystems[d.target.index].acronym + " uses " + DependencyDiagram._chordData[d.source.index][d.target.index] + " " + DependencyDiagram._chordSystems[d.source.index].acronym + " endpoints" ;
},
chordMouseover : function(d) {
d3.select("#tooltip").
style("visibility", "visible").
html(DependencyDiagram.chordTip(d)).
style("top", function () { return (d3.event.pageY)+"px"}).
style("left", function () { return (d3.event.pageX)+"px";})
DependencyDiagram._chord.classed("fadeElement", function(p) {
return p != d;
});
},
groupMouseover : function(d, i) {
d3.select("#tooltip")
.style("visibility", "visible")
.html(DependencyDiagram.groupTip(d))
.style("top", function () { return (d3.event.pageY)+"px"})
.style("left", function () { return (d3.event.pageX)+"px";})
DependencyDiagram._chord.classed("fadeElement", function(p) {
return (p.source.index != i) && (p.target.index != i);
});
},
handleDocClick : function(element) {
var link = $(element).attr("link");
if ("undefined" !== link)
window.open(link);
else UI.alert("#alertModal", "Error", "No document link defined.");
},
handleSortClick : function(index, columnElement) {
if (DependencyDiagram._sortProperties[index] === columnElement.getAttribute("column"))
DependencyDiagram._sortDirections[index] = (DependencyDiagram._sortDirections[index] === "asc" ? "desc" : "asc");
else
{
DependencyDiagram._sortProperties[index] = columnElement.getAttribute("column");
DependencyDiagram._sortDirections[index] = "asc";
}
DependencyDiagram.refreshInfo();
},
getDependentServices : function(sourceComponent, targetComponent) {
var result = [];
if (targetComponent.dependsOn && targetComponent.dependsOn.length) {
for (var i=0;i<targetComponent.dependsOn.length;i++) {
var sourceService = sourceComponent.services.find(function(e) {
return targetComponent.dependsOn[i].endpointId === e.id;
});
if (sourceService) result.push(sourceService);
}
}
return result;
},
sortServices : function(array) {
return array.sort(function(a, b) {
return a.id > b.id ? 1 : -1;
});
},
sortDependsOn : function(array) {
return array.sort(function(a, b) {
return a.endpointId > b.endpointId ? 1 : -1;
});
},
sortColumns : function(index, array) {
return array.sort(function(a, b) {
return (DependencyDiagram._sortDirections[index] === "asc") ?
(a[DependencyDiagram._sortProperties[index]] > b[DependencyDiagram._sortProperties[index]] ? 1 : -1) :
(b[DependencyDiagram._sortProperties[index]] > a[DependencyDiagram._sortProperties[index]] ? 1 : -1);
});
},
rememberCollapse : function(index, element) {
var isCollapsed = $(element.getAttribute("href")).hasClass("in");
DependencyDiagram._collapseStates[index] = isCollapsed;
},
findSearchMatchesInComponent : function(component) {
// search name, acronym, description, technologies, vendor
if (DependencyDiagram._searchText.length > 2) {
if (DependencyDiagram.findSearchMatch([component.name])) return true;
if (DependencyDiagram.findSearchMatch([component.acronym])) return true;
if (DependencyDiagram.findSearchMatch([component.description])) return true;
if (DependencyDiagram.findSearchMatch(component.technologies)) return true;
if (DependencyDiagram.findSearchMatch([component.vendor])) return true;
}
return false;
},
findSearchMatchesForService : function(service) {
// search id, description, endpointSig and tags
if (DependencyDiagram._searchText.length > 2) {
if (DependencyDiagram.findSearchMatch([service.id])) return true;
if (DependencyDiagram.findSearchMatch([service.description])) return true;
if (DependencyDiagram.findSearchMatch([service.endpointSig])) return true;
if (DependencyDiagram.findSearchMatch(service.tags)) return true;
}
return false;
},
findSearchMatch : function(list) {
if (list && list.length > 0 && list[0])
return list.find(function(e) { return e.indexOfInsensitive(DependencyDiagram._searchText) > -1; });
else return false;
},
setSearchText : function(text) {
DependencyDiagram._searchText = text;
},
searchFor : function(text) {
DependencyDiagram.setSearchText(text);
DependencyDiagram.refresh();
DependencyDiagram.refreshInfo();
},
generateUUID : function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
}
}
|
'use strict';
var mon = require("../lib");
function dummy() {
}
describe("Theme - Positive", function () {
describe("valid customization", function () {
it("must be successful", function () {
expect(
mon.setTheme({
time: dummy,
value: dummy,
cn: dummy,
tx: dummy,
paramTitle: dummy,
errorTitle: dummy,
query: dummy,
special: dummy,
error: dummy
})
).toBeUndefined();
});
});
describe('valid theme name', function () {
it('must be successful', function () {
expect(mon.setTheme('matrix')).toBeUndefined();
});
});
});
describe("Theme - Negative", function () {
describe("invalid parameters", function () {
var error = 'Invalid theme parameter specified.';
it("must throw an error", function () {
expect(function () {
mon.setTheme();
}).toThrow(error);
expect(function () {
mon.setTheme(123);
}).toThrow(error);
});
});
describe("non-existing theme", function () {
it("must throw an error", function () {
expect(function () {
mon.setTheme('unknown');
}).toThrow("Theme 'unknown' does not exist.");
});
});
describe("missing attributes", function () {
it("must throw an error", function () {
expect(function () {
mon.setTheme({});
}).toThrow("Invalid theme: property 'time' is missing.");
});
});
describe("invalid attribute value", function () {
it("must throw an error", function () {
expect(function () {
mon.setTheme({
time: null
});
}).toThrow("Theme property 'time' is invalid.");
});
});
});
|
import Vue from 'vue'
import Avatar from 'src/components/Avatar'
import { getRenderedText } from './utils'
describe('Avatar.vue', () => {
it('should render avatar', () => {
const Constructor = Vue.extend(Avatar)
const vm = new Constructor().$mount()
expect(vm.$el.querySelector('.avatar .icon').textContent.trim()).to.equal('');
})
// Inspect the component instance on mount
it('correctly sets initials when created', () => {
const vm = new Vue(Avatar).$mount()
expect(vm.initials).to.equal('');
})
it('renders initials with different props', () => {
expect(getRenderedText(Avatar, {
userName: 'Yarik'
})).to.equal('Y');
expect(getRenderedText(Avatar, {
userName: 'Twin Peaks'
})).to.equal('TP')
})
})
|
/* eslint-env jasmine */
'use strict';
const subject = require('../lib/config.js');
const defaultOptions = subject.defaultOptions;
describe('Options', () => {
it('default enablement is true', () => {
expect(defaultOptions.enabled).toBe(true);
});
it('default position is plugin', () => {
expect(defaultOptions.position).toEqual('plugin');
});
it('default minify is false', () => {
expect(defaultOptions.minify).toBe(false);
});
it('returns default values when nothing passed in', () => {
expect(subject()).toEqual(defaultOptions);
});
it('returns default values when undefined passed in', () => {
expect(subject(undefined)).toEqual(defaultOptions);
});
it('returns disabled when false passed in', () => {
const expected = Object.assign({}, defaultOptions, { enabled: false });
expect(subject(false)).toEqual(expected);
});
it('returns default options when true passed in', () => {
expect(subject(true)).toEqual(defaultOptions);
});
it('if minify is passed as true, options.minify is empty object', () => {
const options = subject({ minify: true });
expect(options.minify).toEqual({});
});
it('if minify is passed as object, options.minify is same object', () => {
const minify = { foo: 'bar' };
const options = subject({ minify });
expect(options.minify).toEqual(minify);
});
});
|
'use strict';
/*!
* Module dependencies.
*/
const specialProperties = ['__proto__', 'constructor', 'prototype'];
/**
* Clones objects
*
* @param {Object} obj the object to clone
* @param {Object} options
* @return {Object} the cloned object
* @api private
*/
const clone = exports.clone = function clone(obj, options) {
if (obj === undefined || obj === null)
return obj;
if (Array.isArray(obj))
return exports.cloneArray(obj, options);
if (obj.constructor) {
if (/ObjectI[dD]$/.test(obj.constructor.name)) {
return 'function' == typeof obj.clone
? obj.clone()
: new obj.constructor(obj.id);
}
if (obj.constructor.name === 'ReadPreference') {
return new obj.constructor(obj.mode, clone(obj.tags, options));
}
if ('Binary' == obj._bsontype && obj.buffer && obj.value) {
return 'function' == typeof obj.clone
? obj.clone()
: new obj.constructor(obj.value(true), obj.sub_type);
}
if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name)
return new obj.constructor(+obj);
if ('RegExp' === obj.constructor.name)
return new RegExp(obj);
if ('Buffer' === obj.constructor.name)
return Buffer.from(obj);
}
if (isObject(obj))
return exports.cloneObject(obj, options);
if (obj.valueOf)
return obj.valueOf();
};
/*!
* ignore
*/
exports.cloneObject = function cloneObject(obj, options) {
const minimize = options && options.minimize,
ret = {},
keys = Object.keys(obj),
len = keys.length;
let hasKeys = false,
val,
k = '',
i = 0;
for (i = 0; i < len; ++i) {
k = keys[i];
// Not technically prototype pollution because this wouldn't merge properties
// onto `Object.prototype`, but avoid properties like __proto__ as a precaution.
if (specialProperties.indexOf(k) !== -1) {
continue;
}
val = clone(obj[k], options);
if (!minimize || ('undefined' !== typeof val)) {
hasKeys || (hasKeys = true);
ret[k] = val;
}
}
return minimize
? hasKeys && ret
: ret;
};
exports.cloneArray = function cloneArray(arr, options) {
const ret = [],
l = arr.length;
let i = 0;
for (; i < l; i++)
ret.push(clone(arr[i], options));
return ret;
};
/**
* process.nextTick helper.
*
* Wraps the given `callback` in a try/catch. If an error is
* caught it will be thrown on nextTick.
*
* node-mongodb-native had a habit of state corruption when
* an error was immediately thrown from within a collection
* method (find, update, etc) callback.
*
* @param {Function} [callback]
* @api private
*/
exports.tick = function tick(callback) {
if ('function' !== typeof callback) return;
return function() {
// callbacks should always be fired on the next
// turn of the event loop. A side benefit is
// errors thrown from executing the callback
// will not cause drivers state to be corrupted
// which has historically been a problem.
const args = arguments;
soon(function() {
callback.apply(this, args);
});
};
};
/**
* Merges `from` into `to` without overwriting existing properties.
*
* @param {Object} to
* @param {Object} from
* @api private
*/
exports.merge = function merge(to, from) {
const keys = Object.keys(from);
for (const key of keys) {
if (specialProperties.indexOf(key) !== -1) {
continue;
}
if ('undefined' === typeof to[key]) {
to[key] = from[key];
} else {
if (exports.isObject(from[key])) {
merge(to[key], from[key]);
} else {
to[key] = from[key];
}
}
}
};
/**
* Same as merge but clones the assigned values.
*
* @param {Object} to
* @param {Object} from
* @api private
*/
exports.mergeClone = function mergeClone(to, from) {
const keys = Object.keys(from);
for (const key of keys) {
if (specialProperties.indexOf(key) !== -1) {
continue;
}
if ('undefined' === typeof to[key]) {
to[key] = clone(from[key]);
} else {
if (exports.isObject(from[key])) {
mergeClone(to[key], from[key]);
} else {
to[key] = clone(from[key]);
}
}
}
};
/**
* Read pref helper (mongo 2.2 drivers support this)
*
* Allows using aliases instead of full preference names:
*
* p primary
* pp primaryPreferred
* s secondary
* sp secondaryPreferred
* n nearest
*
* @param {String} pref
*/
exports.readPref = function readPref(pref) {
switch (pref) {
case 'p':
pref = 'primary';
break;
case 'pp':
pref = 'primaryPreferred';
break;
case 's':
pref = 'secondary';
break;
case 'sp':
pref = 'secondaryPreferred';
break;
case 'n':
pref = 'nearest';
break;
}
return pref;
};
/**
* Read Concern helper (mongo 3.2 drivers support this)
*
* Allows using string to specify read concern level:
*
* local 3.2+
* available 3.6+
* majority 3.2+
* linearizable 3.4+
* snapshot 4.0+
*
* @param {String|Object} concern
*/
exports.readConcern = function readConcern(concern) {
if ('string' === typeof concern) {
switch (concern) {
case 'l':
concern = 'local';
break;
case 'a':
concern = 'available';
break;
case 'm':
concern = 'majority';
break;
case 'lz':
concern = 'linearizable';
break;
case 's':
concern = 'snapshot';
break;
}
concern = { level: concern };
}
return concern;
};
/**
* Object.prototype.toString.call helper
*/
const _toString = Object.prototype.toString;
exports.toString = function(arg) {
return _toString.call(arg);
};
/**
* Determines if `arg` is an object.
*
* @param {Object|Array|String|Function|RegExp|any} arg
* @return {Boolean}
*/
const isObject = exports.isObject = function(arg) {
return '[object Object]' == exports.toString(arg);
};
/**
* Object.keys helper
*/
exports.keys = Object.keys;
/**
* Basic Object.create polyfill.
* Only one argument is supported.
*
* Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
*/
exports.create = 'function' == typeof Object.create
? Object.create
: create;
function create(proto) {
if (arguments.length > 1) {
throw new Error('Adding properties is not supported');
}
function F() { }
F.prototype = proto;
return new F;
}
/**
* inheritance
*/
exports.inherits = function(ctor, superCtor) {
ctor.prototype = exports.create(superCtor.prototype);
ctor.prototype.constructor = ctor;
};
/**
* nextTick helper
* compat with node 0.10 which behaves differently than previous versions
*/
const soon = exports.soon = 'function' == typeof setImmediate
? setImmediate
: process.nextTick;
/**
* Check if this object is an arguments object
*
* @param {Any} v
* @return {Boolean}
*/
exports.isArgumentsObject = function(v) {
return Object.prototype.toString.call(v) === '[object Arguments]';
};
|
return {
// ******************************** Builtin ********************************
// Select Left Tab.
"1": "gBrowser.tabContainer.advanceSelectedTab(-1, true);",
// Select Right Tab.
"2": "gBrowser.tabContainer.advanceSelectedTab(1, true);",
// Scroll Left.
"A": `goDoCommand("cmd_scrollLeft");`,
// Scroll Right.
"D": `goDoCommand("cmd_scrollRight");`,
// Scroll page Up.
"W": `goDoCommand("cmd_scrollPageUp");`,
// Scroll page Down.
"S": `goDoCommand("cmd_scrollPageDown");`,
// Reload skip cache.
"R": "BrowserReloadSkipCache();",
// Open InoReader.
"F1": function ()
{
Common.openURL("https://www.inoreader.com");
},
// Open current page with google cache.
"F2": function ()
{
const url = gBrowser.currentURI.spec;
if (url !== "" && !url.startsWith("about:"))
{
Common.openURL(`https://www.google.com/search?q=cache:${encodeURIComponent(url)}`);
}
},
/**
* Translate selected text.
*/
"F3": function ()
{
Common.evalInContent("content.document.getSelection().toString()", (data) =>
{
if (data === "")
{
Common.openURL("http://dict.youdao.com");
}
else
{
Common.openURL(`http://dict.youdao.com/search?q=${encodeURIComponent(data)}`);
}
});
},
/**
* Translate selected text.
*/
"Shift+F3": function ()
{
Common.evalInContent("content.document.getSelection().toString()", (data) =>
{
if (data === "")
{
Common.openURL("https://translate.google.com/?sl=auto&tl=zh-CN");
}
else
{
Common.openURL(`https://translate.google.com/?sl=auto&tl=zh-CN&text=${encodeURIComponent(data)}&op=translate`);
}
});
},
// Open about page
"F4": function ()
{
Common.openURL("about:about");
},
// Open profiles Folder.
"F9": function ()
{
FileUtils.getDir("ProfD", ["chrome"]).launch();
},
// Open addons manager.
"Alt+A": "BrowserOpenAddonsMgr();",
// Open bookmark search plus.
// "Alt+B": `PlacesCommandHook.showPlacesOrganizer("AllBookmarks");`,
// Copy page url.
"Alt+C": function ()
{
Common.copy(gBrowser.currentURI.spec);
},
// Focus url bar and select all.
"Alt+D": function ()
{
gURLBar.focus();
document.getElementById("urlbar-input").select();
},
// Clear history.
"Alt+Delete": function ()
{
Common.doCommand("sanitizeItem");
},
// Open history manager.
"Alt+H": `PlacesCommandHook.showPlacesOrganizer("History");`,
// Open home page.
"Alt+Home": "BrowserHome();",
// Open reader mode.
// "Alt+K": "ReaderParent.toggleReaderMode(event);",
// Go back.
"Alt+Left": "BrowserBack()",
// Go forward.
"Alt+Right": "BrowserForward()",
// Open firefox color picker.
"Alt+P": function ()
{
Common.doCommand("menu_eyedropper");
},
// Browse page info.
"Alt+U": "BrowserPageInfo();",
// Undo closed Tab.
"Alt+Z": "undoCloseTab();",
// Open bookmarks.
"Ctrl+B": `PlacesCommandHook.showPlacesOrganizer("AllBookmarks");`,
// Inspect DOM elements.
"Ctrl+E": function ()
{
Common.doCommand("menuitem_inspector");
},
// Create a new tab.
"Ctrl+N": function ()
{
// BrowserOpenTab();
Common.openURL("about:newtab");
},
// Toggle mute and disable Mac's stupid minimize app shortcut.
"Ctrl+M": function ()
{
gBrowser.selectedTab.toggleMuteAudio();
},
// Open preferences.
"Ctrl+P": "openPreferences();",
// Create a new container tab.
"Ctrl+T": function ()
{
Common.doCommand("_c607c8df-14a7-4f28-894f-29e8722976af_-browser-action");
},
// Close tab.
"Ctrl+W": "BrowserCloseTabOrWindow();",
// Restart Firefox.
"Ctrl+Alt+R": function ()
{
Common.restartFirefox();
},
// ****************************** UserChrome.js ******************************
// NetEase Music Global Hotkey.
// "Ctrl+Alt+Left": function (e)
// {
// // 感谢黑仪大螃蟹。
// if (gBrowser.selectedBrowser.documentURI.asciiHost !== "music.163.com")
// {
// let browser = null;
// const length = gBrowser.browsers.length;
// for (let i = 0; i < length; i++)
// {
// browser = gBrowser.browsers[i];
// if (browser.documentURI.asciiHost === "music.163.com")
// {
// const button = browser.contentDocument.querySelector(".prv");
// button && button.click();
// break;
// }
// }
// }
// },
// NetEase Music Global Hotkey.
// "Ctrl+Alt+Right": function (e)
// {
// // 感谢黑仪大螃蟹。
// if (gBrowser.selectedBrowser.documentURI.asciiHost != "music.163.com")
// {
// let browser = null;
// const length = gBrowser.browsers.length;
// for (let i = 0; i < length; i++)
// {
// browser = gBrowser.browsers[i];
// if (browser.documentURI.asciiHost === "music.163.com")
// {
// const button = browser.contentDocument.querySelector(".nxt");
// button && button.click();
// break;
// }
// }
// }
// },
// ******************************** Addons ********************************
// Open RESTer.
"F8": function ()
{
Common.openURL("moz-extension://8f6f7d5a-3885-3841-a4c5-34b8ff25dd23/site/index.html");
},
// Convert to Simplified Chinese.
// "Alt+J": function ()
// {
// Common.doCommand("tongwen_softcup-browser-action", true);
// },
// Convert to Traditional Chinese.
// "Ctrl+Alt+J": function ()
// {
// TongWen.trans(TongWen.TRAFLAG);
// },
// Show QR code.
// "Alt+Q": function (e)
// {
// Common.doCommand("tinyqrcode_nonoroazoro_com-browser-action");
// },
// Open Net Video Hunter.
// "Alt+N": "com.netvideohunter.downloader.Overlay_Instance.openMediaListWindow();",
// Switch proxy mode.
"X": function ()
{
Common.doCommand("switchyomega_feliscatus_addons_mozilla_org-browser-action");
},
// Copy all download links fro Thunder.
"Alt+M": function (e)
{
Common.evalInContent(
() =>
{
const urls = [];
urls.push(..._filterURLs(content.document.getElementsByTagName("a"), "href"));
urls.push(..._filterURLs(content.document.getElementsByTagName("input"), "value"));
urls.push(..._filterURLs(content.document.getElementsByTagName("textarea"), "value"));
function _filterURLs(elements, key)
{
let value;
const result = [];
const regex = /(^ed2k:\/\/)|(^thunder:\/\/)|(^magnet:\?xt=)/i;
for (const element of elements)
{
value = element[key].trim();
if (regex.test(value))
{
result.push(value);
}
}
return result;
}
return [...new Set(urls)].sort((a, b) => a.localeCompare(b)).join("\n");
},
(data) =>
{
Common.copy(data);
}
);
},
// Save page to file.
// "Alt+S": function (e)
// {
// Common.doCommand("_531906d3-e22f-4a6c-a102-8057b88a1a63_-browser-action", true);
// }
};
|
var admZip = require('adm-zip');
var check = require('validator');
var fs = require('fs');
var minimatch = require('minimatch');
var os = require('os');
var path = require('path');
var process = require('process');
var ncp = require('child_process');
var semver = require('semver');
var shell = require('shelljs');
var syncRequest = require('sync-request');
var childproc = require('child_process');
// global paths
var downloadPath = path.join(__dirname, '_download');
var makeOptions = require('./make-options.json');
// list of .NET culture names
var cultureNames = ['cs', 'de', 'es', 'fr', 'it', 'ja', 'ko', 'pl', 'pt-BR', 'ru', 'tr', 'zh-Hans', 'zh-Hant'];
//------------------------------------------------------------------------------
// shell functions
//------------------------------------------------------------------------------
var shellAssert = function () {
var errMsg = shell.error();
if (errMsg) {
throw new Error(errMsg);
}
}
var cd = function (dir) {
shell.cd(dir);
shellAssert();
}
exports.cd = cd;
var cp = function (options, source, dest) {
if (dest) {
shell.cp(options, source, dest);
}
else {
shell.cp(options, source);
}
shellAssert();
}
exports.cp = cp;
var mkdir = function (options, target) {
if (target) {
shell.mkdir(options, target);
}
else {
shell.mkdir(options);
}
shellAssert();
}
exports.mkdir = mkdir;
var rm = function (options, target) {
if (target) {
shell.rm(options, target);
}
else {
shell.rm(options);
}
shellAssert();
}
exports.rm = rm;
var test = function (options, p) {
var result = shell.test(options, p);
shellAssert();
return result;
}
exports.test = test;
//------------------------------------------------------------------------------
var assert = function (value, name) {
if (!value) {
throw new Error('"' + name + '" cannot be null or empty.');
}
}
exports.assert = assert;
var banner = function (message, noBracket) {
console.log();
if (!noBracket) {
console.log('------------------------------------------------------------');
}
console.log(message);
if (!noBracket) {
console.log('------------------------------------------------------------');
}
console.log();
}
exports.banner = banner;
var rp = function (relPath) {
return path.join(pwd() + '', relPath);
}
exports.rp = rp;
var fail = function (message) {
console.error('ERROR: ' + message);
process.exit(1);
}
exports.fail = fail;
var ensureExists = function (checkPath) {
assert(checkPath, 'checkPath');
var exists = test('-d', checkPath) || test('-f', checkPath);
if (!exists) {
fail(checkPath + ' does not exist');
}
}
exports.ensureExists = ensureExists;
var pathExists = function (checkPath) {
return test('-d', checkPath) || test('-f', checkPath);
}
exports.pathExists = pathExists;
var buildNodeTask = function (taskPath, outDir) {
var originalDir = pwd();
cd(taskPath);
var packageJsonPath = rp('package.json');
if (test('-f', packageJsonPath)) {
var packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());
if (packageJson.devDependencies && Object.keys(packageJson.devDependencies).length != 0) {
fail('The package.json should not contain dev dependencies. Move the dev dependencies into a package.json file under the Tests sub-folder. Offending package.json: ' + packageJsonPath);
}
run('npm install');
}
if (test('-f', rp(path.join('Tests', 'package.json')))) {
cd(rp('Tests'));
run('npm install');
cd(taskPath);
}
run('tsc --outDir ' + outDir + ' --rootDir ' + taskPath);
cd(originalDir);
}
exports.buildNodeTask = buildNodeTask;
var copyTaskResources = function (taskMake, srcPath, destPath) {
assert(taskMake, 'taskMake');
assert(srcPath, 'srcPath');
assert(destPath, 'destPath');
// copy the globally defined set of default task resources
var toCopy = makeOptions['taskResources'];
toCopy.forEach(function (item) {
matchCopy(item, srcPath, destPath, { noRecurse: true, matchBase: true });
});
// copy the locally defined set of resources
if (taskMake.hasOwnProperty('cp')) {
copyGroups(taskMake.cp, srcPath, destPath);
}
// remove the locally defined set of resources
if (taskMake.hasOwnProperty('rm')) {
removeGroups(taskMake.rm, destPath);
}
}
exports.copyTaskResources = copyTaskResources;
var matchFind = function (pattern, root, options) {
assert(pattern, 'pattern');
assert(root, 'root');
// create a copy of the options
var clone = {};
Object.keys(options || {}).forEach(function (key) {
clone[key] = options[key];
});
options = clone;
// determine whether to recurse
var noRecurse = options.hasOwnProperty('noRecurse') && options.noRecurse;
delete options.noRecurse;
// normalize first, so we can substring later
root = path.resolve(root);
// determine the list of items
var items;
if (noRecurse) {
items = fs.readdirSync(root)
.map(function (name) {
return path.join(root, name);
});
}
else {
items = find(root)
.filter(function (item) { // filter out the root folder
return path.normalize(item) != root;
});
}
return minimatch.match(items, pattern, options);
}
exports.matchFind = matchFind;
var matchCopy = function (pattern, sourceRoot, destRoot, options) {
assert(pattern, 'pattern');
assert(sourceRoot, 'sourceRoot');
assert(destRoot, 'destRoot');
console.log(`copying ${pattern}`);
// normalize first, so we can substring later
sourceRoot = path.resolve(sourceRoot);
destRoot = path.resolve(destRoot);
matchFind(pattern, sourceRoot, options)
.forEach(function (item) {
// create the dest dir based on the relative item path
var relative = item.substring(sourceRoot.length + 1);
assert(relative, 'relative'); // should always be filterd out by matchFind
var dest = path.dirname(path.join(destRoot, relative));
mkdir('-p', dest);
cp('-Rf', item, dest + '/');
});
}
exports.matchCopy = matchCopy;
var run = function (cl, inheritStreams, noHeader) {
if (!noHeader) {
console.log();
console.log('> ' + cl);
}
var options = {
stdio: inheritStreams ? 'inherit' : 'pipe'
};
var rc = 0;
var output;
try {
output = ncp.execSync(cl, options);
}
catch (err) {
if (!inheritStreams) {
console.error(err.output ? err.output.toString() : err.message);
}
process.exit(1);
}
return (output || '').toString().trim();
}
exports.run = run;
var ensureTool = function (name, versionArgs, validate) {
console.log(name + ' tool:');
var toolPath = which(name);
if (!toolPath) {
fail(name + ' not found. might need to run npm install');
}
if (versionArgs) {
var result = exec(name + ' ' + versionArgs);
if (typeof validate == 'string') {
if (result.output.trim() != validate) {
fail('expected version: ' + validate);
}
}
else {
validate(result.output.trim());
}
}
console.log(toolPath + '');
}
exports.ensureTool = ensureTool;
var downloadFile = function (url) {
// validate parameters
if (!url) {
throw new Error('Parameter "url" must be set.');
}
// skip if already downloaded
var scrubbedUrl = url.replace(/[/\:?]/g, '_');
var targetPath = path.join(downloadPath, 'file', scrubbedUrl);
var marker = targetPath + '.completed';
if (!test('-f', marker)) {
console.log('Downloading file: ' + url);
// delete any previous partial attempt
if (test('-f', targetPath)) {
rm('-f', targetPath);
}
// download the file
mkdir('-p', path.join(downloadPath, 'file'));
if (process.env.http_proxy) {
$command = 'curl.exe -k -L --proxy "' + process.env.http_proxy + '"';
if (process.env.http_proxyuser) {
if (process.env.http_proxypass) {
$command += ' --proxyuser "' + process.env.http_proxyuser + ':' + process.env.http_proxypass + '"';
} else {
$command += ' --proxyuser "' + process.env.http_proxyuser + '"';
}
} else {
$command += ' --proxy-ntlm';
}
$command += ' -o "' + targetPath + '"';
$command += ' "' + url + '"';
console.log('Executing: ' + $command);
childproc.execSync($command);
} else {
var result = syncRequest('GET', url);
fs.writeFileSync(targetPath, result.getBody());
}
// write the completed marker
fs.writeFileSync(marker, '');
}
return targetPath;
}
exports.downloadFile = downloadFile;
var downloadArchive = function (url, omitExtensionCheck) {
// validate parameters
if (!url) {
throw new Error('Parameter "url" must be set.');
}
if (!omitExtensionCheck && !url.match(/\.zip$/)) {
throw new Error('Expected .zip');
}
// skip if already downloaded and extracted
var scrubbedUrl = url.replace(/[/\:?]/g, '_');
var targetPath = path.join(downloadPath, 'archive', scrubbedUrl);
var marker = targetPath + '.completed';
console.log('Marker file: ' + marker);
console.log('Downloaded archive: ' + url);
console.log('Target path extracted archive: ' + targetPath);
if (!test('-f', marker)) {
// download the archive
var archivePath = downloadFile(url);
console.log('Extracting archive: ' + url);
// delete any previously attempted extraction directory
if (test('-d', targetPath)) {
rm('-rf', targetPath);
}
// extract
mkdir('-p', targetPath);
var zip = new admZip(archivePath);
zip.extractAllTo(targetPath);
// write the completed marker
fs.writeFileSync(marker, '');
}
return targetPath;
}
exports.downloadArchive = downloadArchive;
var copyGroup = function (group, sourceRoot, destRoot) {
// example structure to copy a single file:
// {
// "source": "foo.dll"
// }
//
// example structure to copy an array of files/folders to a relative directory:
// {
// "source": [
// "foo.dll",
// "bar",
// ],
// "dest": "baz/",
// "options": "-R"
// }
//
// example to multiply the copy by .NET culture names supported by TFS:
// {
// "source": "<CULTURE_NAME>/foo.dll",
// "dest": "<CULTURE_NAME>/"
// }
//
// validate parameters
assert(group, 'group');
assert(group.source, 'group.source');
if (typeof group.source == 'object') {
assert(group.source.length, 'group.source.length');
group.source.forEach(function (s) {
assert(s, 'group.source[i]');
});
}
assert(sourceRoot, 'sourceRoot');
assert(destRoot, 'destRoot');
// multiply by culture name (recursive call to self)
if (group.dest && group.dest.indexOf('<CULTURE_NAME>') >= 0) {
cultureNames.forEach(function (cultureName) {
// culture names do not contain any JSON-special characters, so this is OK (albeit a hack)
var localizedGroupJson = JSON.stringify(group).replace(/<CULTURE_NAME>/g, cultureName);
copyGroup(JSON.parse(localizedGroupJson), sourceRoot, destRoot);
});
return;
}
// build the source array
var source = typeof group.source == 'string' ? [group.source] : group.source;
source = source.map(function (val) { // root the paths
return path.join(sourceRoot, val);
});
// create the destination directory
var dest = group.dest ? path.join(destRoot, group.dest) : destRoot + '/';
dest = path.normalize(dest);
mkdir('-p', dest);
// copy the files
if (group.hasOwnProperty('options') && group.options) {
cp(group.options, source, dest);
}
else {
cp(source, dest);
}
}
var copyGroups = function (groups, sourceRoot, destRoot) {
assert(groups, 'groups');
assert(groups.length, 'groups.length');
groups.forEach(function (group) {
copyGroup(group, sourceRoot, destRoot);
})
}
exports.copyGroups = copyGroups;
var removeGroup = function (group, pathRoot) {
// example structure to remove an array of files/folders:
// {
// "items": [
// "foo.dll",
// "bar",
// ],
// "options": "-R"
// }
// validate parameters
assert(group, 'group');
assert(group.items, 'group.items');
if (typeof group.items != 'object') {
throw new Error('Expected group.items to be an array');
} else {
assert(group.items.length, 'group.items.length');
group.items.forEach(function (p) {
assert(p, 'group.items[i]');
});
}
assert(group.options, 'group.options');
assert(pathRoot, 'pathRoot');
// build the rooted items array
var rootedItems = group.items.map(function (val) { // root the paths
return path.join(pathRoot, val);
});
// remove the items
rm(group.options, rootedItems);
}
var removeGroups = function (groups, pathRoot) {
assert(groups, 'groups');
assert(groups.length, 'groups.length');
groups.forEach(function (group) {
removeGroup(group, pathRoot);
})
}
exports.removeGroups = removeGroups;
var addPath = function (directory) {
var separator;
if (os.platform() == 'win32') {
separator = ';';
}
else {
separator = ':';
}
var existing = process.env['PATH'];
if (existing) {
process.env['PATH'] = directory + separator + existing;
}
else {
process.env['PATH'] = directory;
}
}
exports.addPath = addPath;
var getExternals = function (externals, destRoot) {
assert(externals, 'externals');
assert(destRoot, 'destRoot');
// .zip files
if (externals.hasOwnProperty('archivePackages')) {
var archivePackages = externals.archivePackages;
archivePackages.forEach(function (archive) {
assert(archive.url, 'archive.url');
assert(archive.dest, 'archive.dest');
// download and extract the archive package
var archiveSource = downloadArchive(archive.url);
// copy the files
var archiveDest = path.join(destRoot, archive.dest);
mkdir('-p', archiveDest);
cp('-R', path.join(archiveSource, '*'), archiveDest)
});
}
// external NuGet V2 packages
if (externals.hasOwnProperty('nugetv2')) {
var nugetPackages = externals.nugetv2;
nugetPackages.forEach(function (package) {
// validate the structure of the data
assert(package.name, 'package.name');
assert(package.version, 'package.version');
assert(package.repository, 'package.repository');
assert(package.cp, 'package.cp');
assert(package.cp, 'package.cp.length');
// download and extract the NuGet V2 package
var url = package.repository.replace(/\/$/, '') + '/package/' + package.name + '/' + package.version;
var packageSource = downloadArchive(url, /*omitExtensionCheck*/true);
// copy specific files
copyGroups(package.cp, packageSource, destRoot);
});
}
// external NuGet V3 packages
if (externals.hasOwnProperty('nugetv3')) {
var nugetPackages = externals.nugetv3;
nugetPackages.forEach(function (package) {
// validate the structure of the data
assert(package.name, 'package.name');
assert(package.version, 'package.version');
assert(package.repository, 'package.repository');
assert(package.cp, 'package.cp');
assert(package.cp, 'package.cp.length');
// download and extract the NuGet V2 package
var url = package.repository.replace(/\/$/, '') + '/package/' + package.name + '/' + package.version;
var packageSource = downloadArchive(url, /*omitExtensionCheck*/true);
// copy specific files
copyGroups(package.cp, packageSource, destRoot);
});
}
// for any file type that has to be shipped with task
if (externals.hasOwnProperty('files')) {
var files = externals.files;
files.forEach(function (file) {
assert(file.url, 'file.url');
assert(file.dest, 'file.dest');
// download the file from url
var fileSource = downloadFile(file.url);
// copy the files
var fileDest = path.join(destRoot, file.dest);
mkdir('-p', path.dirname(fileDest));
cp(fileSource, fileDest);
});
}
}
exports.getExternals = getExternals;
//------------------------------------------------------------------------------
// task.json functions
//------------------------------------------------------------------------------
var createResjson = function (task, taskPath) {
var resources = {};
if (task.hasOwnProperty('friendlyName')) {
resources['loc.friendlyName'] = task.friendlyName;
}
if (task.hasOwnProperty('helpMarkDown')) {
resources['loc.helpMarkDown'] = task.helpMarkDown;
}
if (task.hasOwnProperty('description')) {
resources['loc.description'] = task.description;
}
if (task.hasOwnProperty('instanceNameFormat')) {
resources['loc.instanceNameFormat'] = task.instanceNameFormat;
}
if (task.hasOwnProperty('releaseNotes')) {
resources['loc.releaseNotes'] = task.releaseNotes;
}
if (task.hasOwnProperty('groups')) {
task.groups.forEach(function (group) {
if (group.hasOwnProperty('name')) {
resources['loc.group.displayName.' + group.name] = group.displayName;
}
});
}
if (task.hasOwnProperty('inputs')) {
task.inputs.forEach(function (input) {
if (input.hasOwnProperty('name')) {
resources['loc.input.label.' + input.name] = input.label;
if (input.hasOwnProperty('helpMarkDown') && input.helpMarkDown) {
resources['loc.input.help.' + input.name] = input.helpMarkDown;
}
}
});
}
if (task.hasOwnProperty('messages')) {
Object.keys(task.messages).forEach(function (key) {
resources['loc.messages.' + key] = task.messages[key];
});
}
var resjsonPath = path.join(taskPath, 'Strings', 'resources.resjson', 'en-US', 'resources.resjson');
mkdir('-p', path.dirname(resjsonPath));
fs.writeFileSync(resjsonPath, JSON.stringify(resources, null, 2));
};
exports.createResjson = createResjson;
var createTaskLocJson = function (taskPath) {
var taskJsonPath = path.join(taskPath, 'task.json');
var taskLoc = JSON.parse(fs.readFileSync(taskJsonPath));
taskLoc.friendlyName = 'ms-resource:loc.friendlyName';
taskLoc.helpMarkDown = 'ms-resource:loc.helpMarkDown';
taskLoc.description = 'ms-resource:loc.description';
taskLoc.instanceNameFormat = 'ms-resource:loc.instanceNameFormat';
if (taskLoc.hasOwnProperty('releaseNotes')) {
taskLoc.releaseNotes = 'ms-resource:loc.releaseNotes';
}
if (taskLoc.hasOwnProperty('groups')) {
taskLoc.groups.forEach(function (group) {
if (group.hasOwnProperty('name')) {
group.displayName = 'ms-resource:loc.group.displayName.' + group.name;
}
});
}
if (taskLoc.hasOwnProperty('inputs')) {
taskLoc.inputs.forEach(function (input) {
if (input.hasOwnProperty('name')) {
input.label = 'ms-resource:loc.input.label.' + input.name;
if (input.hasOwnProperty('helpMarkDown') && input.helpMarkDown) {
input.helpMarkDown = 'ms-resource:loc.input.help.' + input.name;
}
}
});
}
if (taskLoc.hasOwnProperty('messages')) {
Object.keys(taskLoc.messages).forEach(function (key) {
taskLoc.messages[key] = 'ms-resource:loc.messages.' + key;
});
}
fs.writeFileSync(path.join(taskPath, 'task.loc.json'), JSON.stringify(taskLoc, null, 2));
};
exports.createTaskLocJson = createTaskLocJson;
// Validates the structure of a task.json file.
var validateTask = function (task) {
if (!task.id || !check.isUUID(task.id)) {
fail('id is a required guid');
};
if (!task.name || !check.isAlphanumeric(task.name)) {
fail('name is a required alphanumeric string');
}
if (!task.friendlyName || !check.isLength(task.friendlyName, 1, 40)) {
fail('friendlyName is a required string <= 40 chars');
}
if (!task.instanceNameFormat) {
fail('instanceNameFormat is required');
}
};
exports.validateTask = validateTask;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// package functions
//------------------------------------------------------------------------------
var getRefs = function () {
console.log();
console.log('> Getting branch/commit info')
var info = {};
var branch;
if (process.env.TF_BUILD) {
// during CI agent checks out a commit, not a branch.
// $(build.sourceBranch) indicates the branch name, e.g. releases/m108
branch = process.env.BUILD_SOURCEBRANCH;
}
else {
// assumes user has checked out a branch. this is a fairly safe assumption.
// this code only runs during "package" and "publish" build targets, which
// is not typically run locally.
branch = run('git symbolic-ref HEAD', /*inheritStreams*/false, /*noHeader*/true);
}
assert(branch, 'branch');
var commit = run('git rev-parse --short=8 HEAD', /*inheritStreams*/false, /*noHeader*/true);
var release;
if (branch.match(/^(refs\/heads\/)?releases\/m[0-9]+$/)) {
release = parseInt(branch.split('/').pop().substr(1));
}
// get the ref info for HEAD
var info = {
head: {
branch: branch, // e.g. refs/heads/releases/m108
commit: commit, // leading 8 chars only
release: release // e.g. 108 or undefined if not a release branch
},
releases: {}
};
// get the ref info for each release branch within range
run('git branch --list --remotes "origin/releases/m*"', /*inheritStreams*/false, /*noHeader*/true)
.split('\n')
.forEach(function (branch) {
branch = branch.trim();
if (!branch.match(/^origin\/releases\/m[0-9]+$/)) {
return;
}
var release = parseInt(branch.split('/').pop().substr(1));
// filter out releases less than 108 and greater than HEAD
if (release < 108 ||
release > (info.head.release || 999)) {
return;
}
branch = 'refs/remotes/' + branch;
var commit = run(`git rev-parse --short=8 "${branch}"`, /*inheritStreams*/false, /*noHeader*/true);
info.releases[release] = {
branch: branch,
commit: commit,
release: release
};
});
return info;
}
exports.getRefs = getRefs;
var compressTasks = function (sourceRoot, destPath, individually) {
assert(sourceRoot, 'sourceRoot');
assert(destPath, 'destPath');
run(`powershell.exe -NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "& '${path.join(__dirname, 'Compress-Tasks.ps1')}' -SourceRoot '${sourceRoot}' -TargetPath '${destPath}' -Individually:${individually ? '$true' : '$false'}"`, /*inheritStreams:*/true, /*noHeader*/true);
}
exports.compressTasks = compressTasks;
//------------------------------------------------------------------------------
|
// The MIT License (MIT)
//
// Copyright (c) 2017-2022 Camptocamp SA
//
// 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.
// Todo - use the 'Filter' theme instead if the 'Edit' theme
import angular from 'angular';
import './importdatasource.css';
import 'bootstrap/js/src/tooltip';
import gmfDatasourceManager from 'gmf/datasource/Manager';
import gmfImportImportdatasourceComponent from 'gmf/import/importdatasourceComponent';
import gmfLayertreeComponent from 'gmf/layertree/component';
import gmfLayertreeTreeManager from 'gmf/layertree/TreeManager';
import gmfMapComponent from 'gmf/map/component';
import gmfThemeThemes from 'gmf/theme/Themes';
import ngeoDatasourceDataSources from 'ngeo/datasource/DataSources';
import ngeoQueryComponent from 'ngeo/query/component';
import ngeoMapModule from 'ngeo/map/module';
import EPSG2056 from 'ngeo/proj/EPSG_2056';
import olMap from 'ol/Map';
import olView from 'ol/View';
import olLayerTile from 'ol/layer/Tile';
import olSourceOSM from 'ol/source/OSM';
import options from './options';
/**
* @type {angular.IModule}
* @hidden
*/
const myModule = angular.module('gmfapp', [
'gettext',
gmfDatasourceManager.name,
gmfImportImportdatasourceComponent.name,
gmfLayertreeComponent.name,
gmfLayertreeTreeManager.name,
gmfMapComponent.name,
gmfThemeThemes.name,
ngeoDatasourceDataSources.name,
ngeoQueryComponent.name,
ngeoMapModule.name,
]);
/**
* @private
*/
class MainController {
/**
* @param {angular.IScope} $scope Angular scope.
* @param {import('gmf/datasource/Manager').DatasourceManager} gmfDataSourcesManager The gmf
* data sources manager service.
* @param {import('gmf/theme/Themes').ThemesService} gmfThemes The gmf themes service.
* @param {import('gmf/layertree/TreeManager').LayertreeTreeManager} gmfTreeManager gmf Tree Manager
* service.
* @param {import('ngeo/datasource/DataSources').DataSource} ngeoDataSources Ngeo data sources service.
* @ngInject
*/
constructor($scope, gmfDataSourcesManager, gmfThemes, gmfTreeManager, ngeoDataSources) {
/**
* @type {angular.IScope}
* @private
*/
this.scope_ = $scope;
gmfThemes.loadThemes();
/**
* @type {import('gmf/layertree/TreeManager').LayertreeTreeManager}
*/
this.gmfTreeManager = gmfTreeManager;
/**
* @type {import('ol/Map').default}
*/
this.map = new olMap({
layers: [
new olLayerTile({
source: new olSourceOSM(),
}),
],
view: new olView({
projection: EPSG2056,
resolutions: [200, 100, 50, 20, 10, 5, 2.5, 2, 1, 0.5],
center: [2537635, 1152640],
zoom: 2,
}),
});
// Init the datasources with our map.
gmfDataSourcesManager.setDatasourceMap(this.map);
gmfThemes.getThemesObject().then((themes) => {
if (themes) {
// Set 'Filters' theme, i.e. the one with id 175
for (let i = 0, ii = themes.length; i < ii; i++) {
if (themes[i].id === 175) {
this.gmfTreeManager.setFirstLevelGroups(themes[i].children);
break;
}
}
}
});
/**
* @type {boolean}
*/
this.queryActive = true;
// initialize tooltips
$('[data-toggle="tooltip"]').tooltip({
container: 'body',
trigger: 'hover',
});
}
}
myModule.controller('MainController', MainController);
myModule.constant('defaultTheme', 'Filters');
options(myModule);
export default myModule;
|
/**
* Controller for the application
* @author: chhetrisushil
* @date: 3/27/13
* @time: 2:10 PM
*/
(function (window, document, $, APP, Base, undefined) {
// Package scope Interface
var ITodoList = new JSgoodies.Interface('ITodoList', ['add', 'update', 'delete']);
APP.TodoListController = JSgoodies.Class({
debug: true,
name: 'APP.TodoListController',
config: null,
init: function (config) {
var _self = this;
this.log('initialing the application');
this.config = $.extend(true, {}, config);
this.config.collection.addObserver('updateComplete', function (collection) {
console.log('observer to be called after completion of update', collection.models);
_self.config.view.render(collection.models);
});
},
add: function () {
},
update: function () {
this.config.collection.update();
},
delete: function () {
}
})._extends(Base.Controller)._implements(ITodoList);
})(this, this.document, jQuery, (this.APP || (this.APP = {})), (this.Base || (this.Base = {}))); |
'use strict';
var RedisClient = require('./redisclient');
var async = require('async');
var SlidingWindow = {};
function _expire(key, windowInSeconds, callback) {
var redisClient = RedisClient.getRedisClient();
var now = new Date().getTime();
var expires = now - (windowInSeconds * 1000);
redisClient.zremrangebyscore(key, '-inf', expires, callback);
}
function _getCardinality(key, callback) {
var redisClient = RedisClient.getRedisClient();
redisClient.zcard(key, callback);
}
function _addCall(key, callback) {
var redisClient = RedisClient.getRedisClient();
var now = new Date().getTime();
redisClient.zadd(key, now, now, callback);
}
SlidingWindow.check = function (key, windowInSeconds, limit, callback) {
async.series({
delete: function (done) {
_expire(key, windowInSeconds, done);
},
cardinality: function (done) {
_getCardinality(key, done);
}
}, function (err, results) {
// If we have an error default to limited
if (err) {
return callback(err, true);
}
else {
if (results.cardinality < limit) {
_addCall(key, function (err) {
return callback(err, false);
});
}
else {
return callback(null, true);
}
}
});
};
SlidingWindow.count = function (key, callback) {
_getCardinality(key, callback);
};
module.exports = SlidingWindow;
|
module.exports = {
'ā': {letter: 'a', tone: 1},
'á': {letter: 'a', tone: 2},
'ǎ': {letter: 'a', tone: 3},
'à': {letter: 'a', tone: 4},
'ō': {letter: 'o', tone: 1},
'ó': {letter: 'o', tone: 2},
'ǒ': {letter: 'o', tone: 3},
'ò': {letter: 'o', tone: 4},
'ē': {letter: 'e', tone: 1},
'é': {letter: 'e', tone: 2},
'ě': {letter: 'e', tone: 3},
'è': {letter: 'e', tone: 4},
'ī': {letter: 'i', tone: 1},
'í': {letter: 'i', tone: 2},
'ǐ': {letter: 'i', tone: 3},
'ì': {letter: 'i', tone: 4},
'ū': {letter: 'u', tone: 1},
'ú': {letter: 'u', tone: 2},
'ǔ': {letter: 'u', tone: 3},
'ù': {letter: 'u', tone: 4},
'ǖ': {letter: 'ü', tone: 1},
'ǘ': {letter: 'ü', tone: 2},
'ǚ': {letter: 'ü', tone: 3},
'ǜ': {letter: 'ü', tone: 4},
'ü': {letter: 'ü', tone: 5},
'üē': {letter: 'üe', tone: 1},
'üé': {letter: 'üe', tone: 2},
'üě': {letter: 'üe', tone: 3},
'üè': {letter: 'üe', tone: 4},
'üā': {letter: 'üa', tone: 1},
'üá': {letter: 'üa', tone: 2},
'üǎ': {letter: 'üa', tone: 3},
'üà': {letter: 'üa', tone: 4},
};
|
import { DESCRIPTORS, GLOBAL, NATIVE, TYPED_ARRAYS } from '../helpers/constants';
if (DESCRIPTORS) QUnit.test('%TypedArrayPrototype%.set', assert => {
// we can't implement %TypedArrayPrototype% in all engines, so run all tests for each typed array constructor
for (const name in TYPED_ARRAYS) {
const TypedArray = GLOBAL[name];
const { set } = TypedArray.prototype;
assert.isFunction(set, `${ name }::set is function`);
if (NATIVE) assert.arity(set, 1, `${ name }::set arity is 1`);
assert.name(set, 'set', `${ name }::set name is 'set'`);
assert.looksNative(set, `${ name }::set looks native`);
assert.same(new TypedArray(1).set([1]), undefined, 'void');
const array1 = new TypedArray([1, 2, 3, 4, 5]);
const array2 = new TypedArray(5);
array2.set(array1);
assert.arrayEqual(array2, [1, 2, 3, 4, 5]);
assert.throws(() => array2.set(array1, 1));
assert.throws(() => array2.set(array1, -1));
array2.set(new TypedArray([99, 98]), 2);
assert.arrayEqual(array2, [1, 2, 99, 98, 5]);
array2.set(new TypedArray([99, 98, 97]), 2);
assert.arrayEqual(array2, [1, 2, 99, 98, 97]);
assert.throws(() => array2.set(new TypedArray([99, 98, 97, 96]), 2));
assert.throws(() => array2.set([101, 102, 103, 104], 4));
const array3 = new TypedArray(2);
assert.notThrows(() => array3.set({ length: 2, 0: 1, 1: 2 }), 'set array-like #1');
assert.arrayEqual(array3, [1, 2], 'set array-like #2');
assert.notThrows(() => array3.set('34'), 'set string #1');
assert.arrayEqual(array3, [3, 4], 'set string #2');
assert.notThrows(() => array3.set(1), 'set number #1');
assert.arrayEqual(array3, [3, 4], 'set number #2');
assert.throws(() => set.call([1, 2, 3], [1]), "isn't generic");
}
});
|
var el = domvm.defineElement;
const itemsToLoad = 20;
function ItemListView(vm, model) {
const itemHeight = 30;
const windowHeight = 300;
const loadWhenNumFromBottom = 5;
function calcLoadLine(scrollHeight) {
return scrollHeight - (itemHeight * loadWhenNumFromBottom);
}
var loadLine = calcLoadLine(itemsToLoad * itemHeight);
var onscroll = function(e) {
var winBottom = e.target.scrollTop + windowHeight;
if (winBottom >= loadLine) {
model.loadMoar();
vm.redraw();
loadLine = calcLoadLine(e.target.scrollHeight);
}
};
// this is render() and is called on every redraw() to regen the template
return function() {
var props = {
style: {height: windowHeight+"px", overflowY: "scroll"},
onscroll: onscroll,
};
var kids = model.items.map(function(item) {
return el("div", {style: {color: item.color, height: itemHeight+"px"}}, item.color);
});
return el("#win", props, kids);
}
}
function randColor() {
return '#'+Math.floor(Math.random()*16777215).toString(16);
}
var model = {
loadMoar: function() {
for (var i = itemsToLoad; i > 0; i--)
model.items.push({color: randColor()});
},
items: [],
};
// load initial items
model.loadMoar();
domvm.createView(ItemListView, model).mount(document.body); |
'use strict'
const express = require('express');
const Auth = require('../config/auth');
const router = express.Router();
// Protected route
router.get('/', Auth.isLoggedIn, (req, res) => {
req.logout();
req.flash('homeMsg', 'You\'ve been logged out!');
res.redirect('/');
});
module.exports = router; |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* Central class for registering and accessing data sources
* Also handles processing of data events.
*
* There is a shared global instance that most client code should access via
* goog.ds.DataManager.getInstance(). However you can also create your own
* DataManager using new
*
* Implements DataNode to provide the top element in a data registry
* Prepends '$' to top level data names in path to denote they are root object
*
*/
goog.provide('goog.ds.DataManager');
goog.require('goog.ds.BasicNodeList');
goog.require('goog.ds.DataNode');
goog.require('goog.ds.Expr');
goog.require('goog.string');
goog.require('goog.structs');
goog.require('goog.structs.Map');
/**
* Create a DataManger
* @extends {goog.ds.DataNode}
* @constructor
* @final
*/
goog.ds.DataManager = function() {
this.dataSources_ = new goog.ds.BasicNodeList();
this.autoloads_ = new goog.structs.Map();
this.listenerMap_ = {};
this.listenersByFunction_ = {};
this.aliases_ = {};
this.eventCount_ = 0;
this.indexedListenersByFunction_ = {};
};
/**
* Global instance
* @private
*/
goog.ds.DataManager.instance_ = null;
goog.inherits(goog.ds.DataManager, goog.ds.DataNode);
/**
* Get the global instance
* @return {goog.ds.DataManager} The data manager singleton.
*/
goog.ds.DataManager.getInstance = function() {
if (!goog.ds.DataManager.instance_) {
goog.ds.DataManager.instance_ = new goog.ds.DataManager();
}
return goog.ds.DataManager.instance_;
};
/**
* Clears the global instance (for unit tests to reset state).
*/
goog.ds.DataManager.clearInstance = function() {
goog.ds.DataManager.instance_ = null;
};
/**
* Add a data source
* @param {goog.ds.DataNode} ds The data source.
* @param {boolean=} opt_autoload Whether to automatically load the data,
* defaults to false.
* @param {string=} opt_name Optional name, can also get name
* from the datasource.
*/
goog.ds.DataManager.prototype.addDataSource = function(ds, opt_autoload,
opt_name) {
var autoload = !!opt_autoload;
var name = opt_name || ds.getDataName();
if (!goog.string.startsWith(name, '$')) {
name = '$' + name;
}
ds.setDataName(name);
this.dataSources_.add(ds);
this.autoloads_.set(name, autoload);
};
/**
* Create an alias for a data path, very similar to assigning a variable.
* For example, you can set $CurrentContact -> $Request/Contacts[5], and all
* references to $CurrentContact will be procesed on $Request/Contacts[5].
*
* Aliases will hide datasources of the same name.
*
* @param {string} name Alias name, must be a top level path ($Foo).
* @param {string} dataPath Data path being aliased.
*/
goog.ds.DataManager.prototype.aliasDataSource = function(name, dataPath) {
if (!this.aliasListener_) {
this.aliasListener_ = goog.bind(this.listenForAlias_, this);
}
if (this.aliases_[name]) {
var oldPath = this.aliases_[name].getSource();
this.removeListeners(this.aliasListener_, oldPath + '/...', name);
}
this.aliases_[name] = goog.ds.Expr.create(dataPath);
this.addListener(this.aliasListener_, dataPath + '/...', name);
this.fireDataChange(name);
};
/**
* Listener function for matches of paths that have been aliased.
* Fires a data change on the alias as well.
*
* @param {string} dataPath Path of data event fired.
* @param {string} name Name of the alias.
* @private
*/
goog.ds.DataManager.prototype.listenForAlias_ = function(dataPath, name) {
var aliasedExpr = this.aliases_[name];
if (aliasedExpr) {
// If it's a subpath, appends the subpath to the alias name
// otherwise just fires on the top level alias
var aliasedPath = aliasedExpr.getSource();
if (dataPath.indexOf(aliasedPath) == 0) {
this.fireDataChange(name + dataPath.substring(aliasedPath.length));
} else {
this.fireDataChange(name);
}
}
};
/**
* Gets a named child node of the current node.
*
* @param {string} name The node name.
* @return {goog.ds.DataNode} The child node,
* or null if no node of this name exists.
*/
goog.ds.DataManager.prototype.getDataSource = function(name) {
if (this.aliases_[name]) {
return this.aliases_[name].getNode();
} else {
return this.dataSources_.get(name);
}
};
/**
* Get the value of the node
* @return {Object} The value of the node, or null if no value.
* @override
*/
goog.ds.DataManager.prototype.get = function() {
return this.dataSources_;
};
/** @override */
goog.ds.DataManager.prototype.set = function(value) {
throw Error('Can\'t set on DataManager');
};
/** @override */
goog.ds.DataManager.prototype.getChildNodes = function(opt_selector) {
if (opt_selector) {
return new goog.ds.BasicNodeList(
[this.getChildNode(/** @type {string} */(opt_selector))]);
} else {
return this.dataSources_;
}
};
/**
* Gets a named child node of the current node
* @param {string} name The node name.
* @return {goog.ds.DataNode} The child node,
* or null if no node of this name exists.
* @override
*/
goog.ds.DataManager.prototype.getChildNode = function(name) {
return this.getDataSource(name);
};
/** @override */
goog.ds.DataManager.prototype.getChildNodeValue = function(name) {
var ds = this.getDataSource(name);
return ds ? ds.get() : null;
};
/**
* Get the name of the node relative to the parent node
* @return {string} The name of the node.
* @override
*/
goog.ds.DataManager.prototype.getDataName = function() {
return '';
};
/**
* Gets the a qualified data path to this node
* @return {string} The data path.
* @override
*/
goog.ds.DataManager.prototype.getDataPath = function() {
return '';
};
/**
* Load or reload the backing data for this node
* only loads datasources flagged with autoload
* @override
*/
goog.ds.DataManager.prototype.load = function() {
var len = this.dataSources_.getCount();
for (var i = 0; i < len; i++) {
var ds = this.dataSources_.getByIndex(i);
var autoload = this.autoloads_.get(ds.getDataName());
if (autoload) {
ds.load();
}
}
};
/**
* Gets the state of the backing data for this node
* @return {goog.ds.LoadState} The state.
* @override
*/
goog.ds.DataManager.prototype.getLoadState = goog.abstractMethod;
/**
* Whether the value of this node is a homogeneous list of data
* @return {boolean} True if a list.
* @override
*/
goog.ds.DataManager.prototype.isList = function() {
return false;
};
/**
* Get the total count of events fired (mostly for debugging)
* @return {number} Count of events.
*/
goog.ds.DataManager.prototype.getEventCount = function() {
return this.eventCount_;
};
/**
* Adds a listener
* Listeners should fire when any data with path that has dataPath as substring
* is changed.
* TODO(user) Look into better listener handling
*
* @param {Function} fn Callback function, signature function(dataPath, id).
* @param {string} dataPath Fully qualified data path.
* @param {string=} opt_id A value passed back to the listener when the dataPath
* is matched.
*/
goog.ds.DataManager.prototype.addListener = function(fn, dataPath, opt_id) {
// maxAncestor sets how distant an ancestor you can be of the fired event
// and still fire (you always fire if you are a descendant).
// 0 means you don't fire if you are an ancestor
// 1 means you only fire if you are parent
// 1000 means you will fire if you are ancestor (effectively infinite)
var maxAncestors = 0;
if (goog.string.endsWith(dataPath, '/...')) {
maxAncestors = 1000;
dataPath = dataPath.substring(0, dataPath.length - 4);
} else if (goog.string.endsWith(dataPath, '/*')) {
maxAncestors = 1;
dataPath = dataPath.substring(0, dataPath.length - 2);
}
opt_id = opt_id || '';
var key = dataPath + ':' + opt_id + ':' + goog.getUid(fn);
var listener = {dataPath: dataPath, id: opt_id, fn: fn};
var expr = goog.ds.Expr.create(dataPath);
var fnUid = goog.getUid(fn);
if (!this.listenersByFunction_[fnUid]) {
this.listenersByFunction_[fnUid] = {};
}
this.listenersByFunction_[fnUid][key] = {listener: listener, items: []};
while (expr) {
var listenerSpec = {listener: listener, maxAncestors: maxAncestors};
var matchingListeners = this.listenerMap_[expr.getSource()];
if (matchingListeners == null) {
matchingListeners = {};
this.listenerMap_[expr.getSource()] = matchingListeners;
}
matchingListeners[key] = listenerSpec;
maxAncestors = 0;
expr = expr.getParent();
this.listenersByFunction_[fnUid][key].items.push(
{key: key, obj: matchingListeners});
}
};
/**
* Adds an indexed listener.
*
* Indexed listeners allow for '*' in data paths. If a * exists, will match
* all values and return the matched values in an array to the callback.
*
* Currently uses a promiscuous match algorithm: Matches everything before the
* first '*', and then does a regex match for all of the returned events.
* Although this isn't optimized, it is still an improvement as you can collapse
* 100's of listeners into a single regex match
*
* @param {Function} fn Callback function, signature (dataPath, id, indexes).
* @param {string} dataPath Fully qualified data path.
* @param {string=} opt_id A value passed back to the listener when the dataPath
* is matched.
*/
goog.ds.DataManager.prototype.addIndexedListener = function(fn, dataPath,
opt_id) {
var firstStarPos = dataPath.indexOf('*');
// Just need a regular listener
if (firstStarPos == -1) {
this.addListener(fn, dataPath, opt_id);
return;
}
var listenPath = dataPath.substring(0, firstStarPos) + '...';
// Create regex that matches * to any non '\' character
var ext = '$';
if (goog.string.endsWith(dataPath, '/...')) {
dataPath = dataPath.substring(0, dataPath.length - 4);
ext = '';
}
var regExpPath = goog.string.regExpEscape(dataPath);
var matchRegExp = regExpPath.replace(/\\\*/g, '([^\\\/]+)') + ext;
// Matcher function applies the regex and calls back the original function
// if the regex matches, passing in an array of the matched values
var matchRegExpRe = new RegExp(matchRegExp);
var matcher = function(path, id) {
var match = matchRegExpRe.exec(path);
if (match) {
match.shift();
fn(path, opt_id, match);
}
};
this.addListener(matcher, listenPath, opt_id);
// Add the indexed listener to the map so that we can remove it later.
var fnUid = goog.getUid(fn);
if (!this.indexedListenersByFunction_[fnUid]) {
this.indexedListenersByFunction_[fnUid] = {};
}
var key = dataPath + ':' + opt_id;
this.indexedListenersByFunction_[fnUid][key] = {
listener: {dataPath: listenPath, fn: matcher, id: opt_id}
};
};
/**
* Removes indexed listeners with a given callback function, and optional
* matching datapath and matching id.
*
* @param {Function} fn Callback function, signature function(dataPath, id).
* @param {string=} opt_dataPath Fully qualified data path.
* @param {string=} opt_id A value passed back to the listener when the dataPath
* is matched.
*/
goog.ds.DataManager.prototype.removeIndexedListeners = function(
fn, opt_dataPath, opt_id) {
this.removeListenersByFunction_(
this.indexedListenersByFunction_, true, fn, opt_dataPath, opt_id);
};
/**
* Removes listeners with a given callback function, and optional
* matching dataPath and matching id
*
* @param {Function} fn Callback function, signature function(dataPath, id).
* @param {string=} opt_dataPath Fully qualified data path.
* @param {string=} opt_id A value passed back to the listener when the dataPath
* is matched.
*/
goog.ds.DataManager.prototype.removeListeners = function(fn, opt_dataPath,
opt_id) {
// Normalize data path root
if (opt_dataPath && goog.string.endsWith(opt_dataPath, '/...')) {
opt_dataPath = opt_dataPath.substring(0, opt_dataPath.length - 4);
} else if (opt_dataPath && goog.string.endsWith(opt_dataPath, '/*')) {
opt_dataPath = opt_dataPath.substring(0, opt_dataPath.length - 2);
}
this.removeListenersByFunction_(
this.listenersByFunction_, false, fn, opt_dataPath, opt_id);
};
/**
* Removes listeners with a given callback function, and optional
* matching dataPath and matching id from the given listenersByFunction
* data structure.
*
* @param {Object} listenersByFunction The listeners by function.
* @param {boolean} indexed Indicates whether the listenersByFunction are
* indexed or not.
* @param {Function} fn Callback function, signature function(dataPath, id).
* @param {string=} opt_dataPath Fully qualified data path.
* @param {string=} opt_id A value passed back to the listener when the dataPath
* is matched.
* @private
*/
goog.ds.DataManager.prototype.removeListenersByFunction_ = function(
listenersByFunction, indexed, fn, opt_dataPath, opt_id) {
var fnUid = goog.getUid(fn);
var functionMatches = listenersByFunction[fnUid];
if (functionMatches != null) {
for (var key in functionMatches) {
var functionMatch = functionMatches[key];
var listener = functionMatch.listener;
if ((!opt_dataPath || opt_dataPath == listener.dataPath) &&
(!opt_id || opt_id == listener.id)) {
if (indexed) {
this.removeListeners(
listener.fn, listener.dataPath, listener.id);
}
if (functionMatch.items) {
for (var i = 0; i < functionMatch.items.length; i++) {
var item = functionMatch.items[i];
delete item.obj[item.key];
}
}
delete functionMatches[key];
}
}
}
};
/**
* Get the total number of listeners (per expression listened to, so may be
* more than number of times addListener() has been called
* @return {number} Number of listeners.
*/
goog.ds.DataManager.prototype.getListenerCount = function() {
var count = 0;
goog.structs.forEach(this.listenerMap_, function(matchingListeners) {
count += goog.structs.getCount(matchingListeners);
});
return count;
};
/**
* Disables the sending of all data events during the execution of the given
* callback. This provides a way to avoid useless notifications of small changes
* when you will eventually send a data event manually that encompasses them
* all.
*
* Note that this function can not be called reentrantly.
*
* @param {Function} callback Zero-arg function to execute.
*/
goog.ds.DataManager.prototype.runWithoutFiringDataChanges = function(callback) {
if (this.disableFiring_) {
throw Error('Can not nest calls to runWithoutFiringDataChanges');
}
this.disableFiring_ = true;
try {
callback();
} finally {
this.disableFiring_ = false;
}
};
/**
* Fire a data change event to all listeners
*
* If the path matches the path of a listener, the listener will fire
*
* If your path is the parent of a listener, the listener will fire. I.e.
* if $Contacts/bob@bob.com changes, then we will fire listener for
* $Contacts/bob@bob.com/Name as well, as the assumption is that when
* a parent changes, all children are invalidated.
*
* If your path is the child of a listener, the listener may fire, depending
* on the ancestor depth.
*
* A listener for $Contacts might only be interested if the contact name changes
* (i.e. $Contacts doesn't fire on $Contacts/bob@bob.com/Name),
* while a listener for a specific contact might
* (i.e. $Contacts/bob@bob.com would fire on $Contacts/bob@bob.com/Name).
* Adding "/..." to a lisetener path listens to all children, and adding "/*" to
* a listener path listens only to direct children
*
* @param {string} dataPath Fully qualified data path.
*/
goog.ds.DataManager.prototype.fireDataChange = function(dataPath) {
if (this.disableFiring_) {
return;
}
var expr = goog.ds.Expr.create(dataPath);
var ancestorDepth = 0;
// Look for listeners for expression and all its parents.
// Parents of listener expressions are all added to the listenerMap as well,
// so this will evaluate inner loop every time the dataPath is a child or
// an ancestor of the original listener path
while (expr) {
var matchingListeners = this.listenerMap_[expr.getSource()];
if (matchingListeners) {
for (var id in matchingListeners) {
var match = matchingListeners[id];
var listener = match.listener;
if (ancestorDepth <= match.maxAncestors) {
listener.fn(dataPath, listener.id);
}
}
}
ancestorDepth++;
expr = expr.getParent();
}
this.eventCount_++;
};
|
// To use this file in WebStorm, right click on the file name in the Project Panel (normally left) and select "Open Grunt Console"
/** @namespace __dirname */
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";
module.exports = function (grunt) {
var srcDir = __dirname + '/';
var pkg = grunt.file.readJSON('package.json');
var iopackage = grunt.file.readJSON('io-package.json');
var version = (pkg && pkg.version) ? pkg.version : iopackage.common.version;
var newname = grunt.option('name');
var author = grunt.option('author') || 'instalator';
var email = grunt.option('email') || 'vvvalt@mail.ru';
var fs = require('fs');
// check arguments
if (process.argv[2] == 'rename') {
console.log('Try to rename to "' + newname + '"');
if (!newname) {
console.log('Please write the new players name, like: "grunt rename --name=mywidgetset" --author="Author Name"');
process.exit();
}
if (newname.indexOf(' ') != -1) {
console.log('Name may not have space in it.');
process.exit();
}
if (newname.toLowerCase() != newname) {
console.log('Name must be lower case.');
process.exit();
}
if (fs.existsSync(__dirname + '/admin/players.png')) {
fs.renameSync(__dirname + '/admin/players.png', __dirname + '/admin/' + newname + '.png');
}
if (fs.existsSync(__dirname + '/widgets/players.html')) {
fs.renameSync(__dirname + '/widgets/players.html', __dirname + '/widgets/' + newname + '.html');
}
if (fs.existsSync(__dirname + '/widgets/players/js/players.js')) {
fs.renameSync(__dirname + '/widgets/players/js/players.js', __dirname + '/widgets/players/js/' + newname + '.js');
}
if (fs.existsSync(__dirname + '/widgets/players')) {
fs.renameSync(__dirname + '/widgets/players', __dirname + '/widgets/' + newname);
}
}
// Project configuration.
grunt.initConfig({
pkg: pkg,
replace: {
version: {
options: {
patterns: [
{
match: /version: *"[\.0-9]*"/,
replacement: 'version: "' + version + '"'
},
{
match: /"version": *"[\.0-9]*",/g,
replacement: '"version": "' + version + '",'
},
{
match: /version: *"[\.0-9]*",/g,
replacement: 'version: "' + version + '",'
}
]
},
files: [
{
expand: true,
flatten: true,
src: [
srcDir + 'package.json',
srcDir + 'io-package.json'
],
dest: srcDir
},
{
expand: true,
flatten: true,
src: [
srcDir + 'widgets/' + pkg.name.substring('iobroker.vis-'.length) + '.html'
],
dest: srcDir + 'widgets'
}
]
},
name: {
options: {
patterns: [
{
match: /players/g,
replacement: newname
},
{
match: /Players/g,
replacement: newname ? (newname[0].toUpperCase() + newname.substring(1)) : 'Players'
},
{
match: /instalator/g,
replacement: author
},
{
match: /vvvalt@mail.ru/g,
replacement: email
}
]
},
files: [
{
expand: true,
flatten: true,
src: [
srcDir + 'io-package.json',
srcDir + 'LICENSE',
srcDir + 'package.json',
srcDir + 'README.md',
srcDir + 'io-package.json',
srcDir + 'Gruntfile.js'
],
dest: srcDir
},
{
expand: true,
flatten: true,
src: [
srcDir + 'widgets/' + newname +'.html'
],
dest: srcDir + 'widgets'
},
{
expand: true,
flatten: true,
src: [
srcDir + 'admin/index.html'
],
dest: srcDir + 'admin'
},
{
expand: true,
flatten: true,
src: [
srcDir + 'widgets/' + newname + '/js/' + newname +'.js'
],
dest: srcDir + 'widgets/' + newname + '/js'
},
{
expand: true,
flatten: true,
src: [
srcDir + 'widgets/' + newname + '/css/*.css'
],
dest: srcDir + 'widgets/' + newname + '/css'
}
]
}
},
// Javascript code styler
jscs: require(__dirname + '/tasks/jscs.js'),
// Lint
jshint: require(__dirname + '/tasks/jshint.js'),
http: {
get_hjscs: {
options: {
url: 'https://raw.githubusercontent.com/ioBroker/ioBroker.js-controller/master/tasks/jscs.js'
},
dest: 'tasks/jscs.js'
},
get_jshint: {
options: {
url: 'https://raw.githubusercontent.com/ioBroker/ioBroker.js-controller/master/tasks/jshint.js'
},
dest: 'tasks/jshint.js'
},
get_jscsRules: {
options: {
url: 'https://raw.githubusercontent.com/ioBroker/ioBroker.js-controller/master/tasks/jscsRules.js'
},
dest: 'tasks/jscsRules.js'
}
}
});
grunt.loadNpmTasks('grunt-replace');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-http');
grunt.registerTask('default', [
'http',
'replace:version',
'jshint',
'jscs'
]);
grunt.registerTask('prepublish', [
'http',
'replace:version'
]);
grunt.registerTask('p', [
'http',
'replace:version'
]);
grunt.registerTask('rename', [
'replace:name'
]);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.