code stringlengths 2 1.05M |
|---|
import { createStore, applyMiddleware, compose } from "redux";
import thunkMiddleware from "redux-thunk";
import apiMiddleware from "../api-middleware";
import rootReducer from "../reducers";
// import createLogger from 'redux-logger'
export default function configureStore(initialState) {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
return createStore(
rootReducer,
initialState,
// apiMiddleware can now use thunk when calling `next()`
composeEnhancers( applyMiddleware(apiMiddleware, thunkMiddleware)), //, createLogger())
);
}
|
describe('Chart.animations', function() {
it('should override property collection with property', function() {
const chart = {};
const anims = new Chart.Animations(chart, {
collection1: {
properties: ['property1', 'property2'],
duration: 1000
},
property2: {
duration: 2000
}
});
expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000}));
expect(anims._properties.get('property2')).toEqual(jasmine.objectContaining({duration: 2000}));
});
it('should ignore duplicate definitions from collections', function() {
const chart = {};
const anims = new Chart.Animations(chart, {
collection1: {
properties: ['property1'],
duration: 1000
},
collection2: {
properties: ['property1', 'property2'],
duration: 2000
}
});
expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000}));
expect(anims._properties.get('property2')).toEqual(jasmine.objectContaining({duration: 2000}));
});
it('should not animate undefined options key', function() {
const chart = {};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const target = {
value: 1,
options: {
option: 2
}
};
expect(anims.update(target, {
options: undefined
})).toBeUndefined();
});
it('should assing options directly, if target does not have previous options', function() {
const chart = {};
const anims = new Chart.Animations(chart, {option: {duration: 200}});
const target = {};
expect(anims.update(target, {options: {option: 1}})).toBeUndefined();
});
it('should clone the target options, if those are shared and new options are not', function() {
const chart = {options: {}};
const anims = new Chart.Animations(chart, {option: {duration: 200}});
const options = {option: 0, $shared: true};
const target = {options};
expect(anims.update(target, {options: {option: 1}})).toBeTrue();
expect(target.options.$shared).not.toBeTrue();
expect(target.options !== options).toBeTrue();
});
it('should assign shared options to target after animations complete', function(done) {
const chart = {
draw: function() {},
options: {}
};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const target = {
value: 1,
options: {
option: 2
}
};
const sharedOpts = {option: 10, $shared: true};
expect(anims.update(target, {
options: sharedOpts
})).toBeTrue();
expect(target.options !== sharedOpts).toBeTrue();
Chart.animator.start(chart);
setTimeout(function() {
expect(Chart.animator.running(chart)).toBeFalse();
expect(target.options === sharedOpts).toBeTrue();
Chart.animator.remove(chart);
done();
}, 300);
});
it('should not assign shared options to target when animations are cancelled', function(done) {
const chart = {
draw: function() {},
options: {}
};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const target = {
value: 1,
options: {
option: 2
}
};
const sharedOpts = {option: 10, $shared: true};
expect(anims.update(target, {
options: sharedOpts
})).toBeTrue();
expect(target.options !== sharedOpts).toBeTrue();
Chart.animator.start(chart);
setTimeout(function() {
expect(Chart.animator.running(chart)).toBeTrue();
Chart.animator.stop(chart);
expect(Chart.animator.running(chart)).toBeFalse();
setTimeout(function() {
expect(target.options === sharedOpts).toBeFalse();
Chart.animator.remove(chart);
done();
}, 250);
}, 50);
});
it('should assign final shared options to target after animations complete', function(done) {
const chart = {
draw: function() {},
options: {}
};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const origOpts = {option: 2};
const target = {
value: 1,
options: origOpts
};
const sharedOpts = {option: 10, $shared: true};
const sharedOpts2 = {option: 20, $shared: true};
expect(anims.update(target, {
options: sharedOpts
})).toBeTrue();
expect(target.options !== sharedOpts).toBeTrue();
Chart.animator.start(chart);
setTimeout(function() {
expect(Chart.animator.running(chart)).toBeTrue();
expect(target.options === origOpts).toBeTrue();
expect(anims.update(target, {
options: sharedOpts2
})).toBeUndefined();
expect(target.options === origOpts).toBeTrue();
setTimeout(function() {
expect(target.options === sharedOpts2).toBeTrue();
Chart.animator.remove(chart);
done();
}, 250);
}, 50);
});
});
|
const http = require('http');
const faye = require('faye');
const extensions = require('./faye-extensions');
const utils = require('./faye-utils');
class FayeServer {
constructor(options = {}) {
this.options = {
FAYE_PORT: options.FAYE_PORT || 8080,
FAYE_MOUNT: options.FAYE_MOUNT || '/bayeux',
FAYE_TIMEOUT: options.FAYE_TIMEOUT || 45,
FAYE_LOG_LEVEL: options.FAYE_LOG_LEVEL || 0,
FAYE_STATS: options.FAYE_STATS || 'false',
FAYE_STATS_PORT: options.FAYE_STATS_PORT || 1936,
FAYE_WILDCARD_SUBSCRIPTION_ON_ROOT: options.FAYE_WILDCARD_SUBSCRIPTION_ON_ROOT || 'false'
};
this.httpServer = null;
this.statsServer = null;
this.statistics = {};
}
start() {
if (this.httpServer) {
throw new Error('Server is already running on port ' + this.options.FAYE_PORT);
}
if (this.options.FAYE_LOG_LEVEL >= 1) {
console.log('Starting Faye server\n' + JSON.stringify(this.options, null, 2));
}
var bayeux = new faye.NodeAdapter({
mount: this.options.FAYE_MOUNT,
timeout: this.options.FAYE_TIMEOUT
});
if (!(this.options.FAYE_WILDCARD_SUBSCRIPTION_ON_ROOT === 'true')) {
bayeux.addExtension(extensions.forbidWildcardSubscriptionOnRoot);
}
if (this.options.FAYE_LOG_LEVEL >= 1) {
utils.enableLoggingOfConnections(bayeux);
utils.enableLoggingOfSubscriptions(bayeux);
}
if (this.options.FAYE_LOG_LEVEL >= 2) {
utils.enableLoggingOfPublications(bayeux);
}
this.httpServer = http.createServer();
bayeux.attach(this.httpServer);
this.httpServer.listen(this.options.FAYE_PORT);
if (this.options.FAYE_STATS === 'true') {
utils.enableStatistics(bayeux, this.statistics);
this.statsServer = http.createServer(utils.statisticsRequestListener(this.statistics));
this.statsServer.listen(this.options.FAYE_STATS_PORT);
}
};
stop() {
if (this.options.FAYE_LOG_LEVEL >= 1) {
console.log('Stopping server at port ' + this.options.FAYE_PORT);
}
if (this.httpServer) {
this.httpServer.close(() => {
if (this.options.FAYE_LOG_LEVEL >= 1) {
console.log('Faye service stopped');
}
});
this.httpServer = null;
}
if (this.statsServer) {
this.statsServer.close(() => {
if (this.options.FAYE_LOG_LEVEL >= 1) {
console.log('Stats service stopped');
}
});
this.statsServer = null;
}
};
}
module.exports = FayeServer;
|
var inflect = require('i')()
, injector = require('injector');
module.exports = function hasMany(mongoose, Klass, Proto, assocTo) {
assocTo = assocTo instanceof Array ? underscore.clone(assocTo) : [assocTo, {}];
if (Klass.primaryKeys.length !== 1) {
throw new Error('hasMany association not support without primaryKeys.');
}
var sourceModelName = Klass.modelName
, targetModelName = assocTo.shift()
, associationOptions = assocTo.shift()
, sourceModel = Klass
, association = {};
association.identifier = inflect.pluralize(associationOptions.foreignKey ? associationOptions.foreignKey : (Klass.underscored === true ? inflect.foreign_key(targetModelName, Klass.primaryKey) : inflect.camelize(targetModelName + '_' + Klass.primaryKey, true)));
association.sourceName = sourceModelName;
association.type = 'hasMany';
association.targetName = associationOptions.through ? associationOptions.through : targetModelName;
association.as = inflect.pluralize(inflect.camelize((associationOptions.alias || associationOptions.as || targetModelName.replace('Model','')), true))
association.target = injector.getInstance(association.targetName + 'Model');
association.source = sourceModel ? sourceModel : sourceModelName;
Klass.associations.push(association);
Klass.fields[association.as] = [{
type : mongoose.Schema.ObjectId,
of : assocTo
}];
Klass.getters[association.as] = function getRelation() {
return this.entity[association.as];
};
Klass.setters[association.as] = function setRelation(val) {
this.entity[association.as] = val;
return this;
};
Klass.getters[association.identifier] = function getRelationIdentifier() {
return this.entity[association.as] &&
this.entity[assocTo].entity &&
this.entity[assocTo].entity._id ? this.entity[assocTo].entity._id : this.entity[assocTo];
};
Klass.setters[association.identifier] = function setRelationIdentifier(val) {
this.entity[association.identifier] = val.id || val;
return this;
};
Proto['get' + association.as] = function getRelationAs(val) {
return this.entity[association.as];
};
Proto['set' + association.as] = function setRelationAs(val) {
this.entity[association.as] = val;
return this.save();
};
} |
export default {
PENDING: 'PENDING',
SUCCESS: 'SUCCESS',
FAIL: 'FAIL',
};
|
webpackHotUpdate("static\\development\\pages\\_error.js",{
/***/ "./node_modules/next-server/head.js":
false,
/***/ "./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F_error&absolutePagePath=C%3A%5CUsers%5Cmanoel.filho%5CDocuments%5CGitHub%5Cdevconductor.github.io%5Cpages%5C_error.js!./":
/*!****************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F_error&absolutePagePath=C%3A%5CUsers%5Cmanoel.filho%5CDocuments%5CGitHub%5Cdevconductor.github.io%5Cpages%5C_error.js ***!
\****************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
(window.__NEXT_P=window.__NEXT_P||[]).push(["/_error", function() {
var page = __webpack_require__(/*! ./pages/_error.js */ "./pages/_error.js")
if(true) {
module.hot.accept(/*! ./pages/_error.js */ "./pages/_error.js", function() {
if(!next.router.components["/_error"]) return
var updatedPage = __webpack_require__(/*! ./pages/_error.js */ "./pages/_error.js")
next.router.update("/_error", updatedPage.default || updatedPage)
})
}
return { page: page.default || page }
}]);
/***/ }),
/***/ "./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F_error&absolutePagePath=next%2Fdist%2Fpages%2F_error!./":
false,
/***/ "./node_modules/next/dist/pages/_error.js":
false,
/***/ "./pages/_error.js":
/*!*************************!*\
!*** ./pages/_error.js ***!
\*************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _components_section__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../components/section */ "./components/section.js");
/* harmony import */ var _components_header__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../components/header */ "./components/header.js");
var _jsxFileName = "C:\\Users\\manoel.filho\\Documents\\GitHub\\devconductor.github.io\\pages\\_error.js";
var Error = function Error() {
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, {
__source: {
fileName: _jsxFileName,
lineNumber: 5
},
__self: this
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_components_header__WEBPACK_IMPORTED_MODULE_2__["default"], {
__source: {
fileName: _jsxFileName,
lineNumber: 6
},
__self: this
}), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_components_section__WEBPACK_IMPORTED_MODULE_1__["default"], {
firstSection: true,
alignCenter: true,
title: "P\xE1gina n\xE3o encontrada!",
__source: {
fileName: _jsxFileName,
lineNumber: 7
},
__self: this
}));
};
/* harmony default export */ __webpack_exports__["default"] = (Error);
/***/ }),
/***/ 5:
/*!********************************************************************************************************************************************************************!*\
!*** multi next-client-pages-loader?page=%2F_error&absolutePagePath=C%3A%5CUsers%5Cmanoel.filho%5CDocuments%5CGitHub%5Cdevconductor.github.io%5Cpages%5C_error.js ***!
\********************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! next-client-pages-loader?page=%2F_error&absolutePagePath=C%3A%5CUsers%5Cmanoel.filho%5CDocuments%5CGitHub%5Cdevconductor.github.io%5Cpages%5C_error.js! */"./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F_error&absolutePagePath=C%3A%5CUsers%5Cmanoel.filho%5CDocuments%5CGitHub%5Cdevconductor.github.io%5Cpages%5C_error.js!./");
/***/ })
})
//# sourceMappingURL=_error.js.391dd3b8f39755f2d485.hot-update.js.map |
var React = require('react');
var TestEvaluator = require('../mixins/TestEvaluator');
var WithKeyedChildren = require('../mixins/WithKeyedChildren');
var Conditional = React.createClass({
mixins: [TestEvaluator, WithKeyedChildren],
_findChildToRender() {
var childrensCount = React.Children.count(this.props.children);
if (childrensCount === 0) return null;
if (childrensCount === 1) {
var child = this.props.children;
var testVal = this.evaluateTestProp(child.props);
return child.type === Conditional.If && testVal ? child : null;
} else {
var validChild = this.props.children.find(child => {
var testVal = this.evaluateTestProp(child.props);
return (child.type === Conditional.If || child.type === Conditional.ElseIf) && testVal;
});
if(validChild) return validChild;
else {
var elseComponent = this.findChildByType(Conditional.Else);
return elseComponent ? elseComponent : null;
}
}
},
render: function () {
var result = this._findChildToRender();
return !result ? null : result;
}
});
Conditional.If = React.createClass({
propTypes: {
test: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.func
]).isRequired
},
render(){
return React.isValidElement(this.props.children) ? this.props.children : <div>{this.props.children}</div>;
}
});
Conditional.ElseIf = React.createClass({
propTypes: {
test: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.func
]).isRequired
},
render(){
return React.isValidElement(this.props.children) ? this.props.children : <div>{this.props.children}</div>;
}
});
Conditional.Else = React.createClass({
render(){
return React.isValidElement(this.props.children) ? this.props.children : <div>{this.props.children}</div>;
}
});
module.exports = Conditional;
|
var fs = require( 'fs' )
var File = require( './' )
module.exports = function write( data, offset, callback ) {
var self = this
var buffer = Buffer.isBuffer( data ) ?
data : new Buffer( data )
if( typeof offset === 'function' ) {
callback = offset
offset = 0
}
if( typeof callback === 'function' ) {
if( this.__OOB( offset ) )
return callback.call( this, new Error( 'Offset out of bounds' ) )
if( this.__OOB( offset + buffer.length ) )
return callback.call( this, new Error( 'Length out of bounds' ) )
this.writes.push(
[ this.fd, buffer, 0, buffer.length, offset ],
function( error, bytesWritten, buffer ) {
callback.call( self, error, bytesWritten, buffer )
}
)
} else {
if( this.__OOB( offset ) )
throw new Error( 'Offset out of bounds' )
if( this.__OOB( offset + buffer.length ) )
throw new Error( 'Length out of bounds' )
return fs.writeSync(
this.fd, buffer, 0, buffer.length, offset
)
}
return -1
}
|
/**
* Simple test file for unibot-dtc plugin.
*
* Purpose of this is just to "mimic" actual IRC messages on channel where plugin is enabled.
*
* Usage:
* node test.js [message]
*
* @todo make real help for this.
*/
/**
* Runner dependencies.
*
* @type {exports}
*/
var _ = require('lodash');
var plugin = require('./index');
/**
* Nick who is making query
*
* @type {string}
*/
var from = 'tarlepp';
var message = process.argv.slice(2).join(' ');
if (_.isEmpty(message)) {
console.log('Please give some command to process...');
return;
}
message = '!' + message;
var match = false;
_.each(plugin({})({say: function(message, from) { from ? console.log(from + ': ' + message) : console.log(message); } }), function iterator(callback, pattern) {
var expression = new RegExp(pattern, 'i');
var matches = expression.exec(message);
if (matches) {
console.log('Plugin matches with: ' + message);
match = true;
callback(from, matches);
}
});
if (!match) {
console.log('Plugin does not match with: ' + message);
} |
define(function () {
'use strict';
return {
port: '8000',
secret: 'eifvdn9843(&T423?=90*#+_:21387SkjwnH_=',
tokenExpiresInMinutes: 120,
defaultClient: 'test',
permissions: {
'admin': 'admin',
'sysadmin': 'sysadmin',
'user': 'user'
}
};
}); |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M20 5h-3.17L15 3H9L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 14H4V7h4.05l.59-.65L9.88 5h4.24l1.24 1.35.59.65H20v12z" /><path d="M12 17c-2.21 0-4-1.79-4-4h2l-2.5-2.5L5 13h2c0 2.76 2.24 5 5 5 .86 0 1.65-.24 2.36-.62l-.74-.74c-.49.23-1.04.36-1.62.36zm0-9c-.86 0-1.65.24-2.36.62l.74.73C10.87 9.13 11.42 9 12 9c2.21 0 4 1.79 4 4h-2l2.5 2.5L19 13h-2c0-2.76-2.24-5-5-5z" /></React.Fragment>
, 'FlipCameraIosOutlined');
|
(function( w, $ ) {
"use strict";
var $simple;
var $disclosed;
var $form;
function commonSetup(){
$(document).trigger("enhance");
$simple = $( "#simple" );
$disclosed = $( "#disclosed" );
$form = $( "form" );
}
QUnit.module( "Methods", {
beforeEach: commonSetup
});
QUnit.test("reveals disclosure target", function(assert){
assert.ok( $disclosed.is( ".hidden" ), "is hidden" );
$simple[0].checked = true;
$form.trigger( "change" );
assert.ok( !$disclosed.is( ".hidden" ), "is not hidden" );
});
QUnit.test("hides undisclosed targets", function(assert){
$disclosed.removeClass( "hidden" );
assert.ok( !$disclosed.is( ".hidden" ), "is not hidden" );
$simple[0].checked = false;
$form.trigger( "change" );
assert.ok( $disclosed.is( ".hidden" ), "is hidden" );
});
})(window, shoestring);
|
$(document).ready(function () {
$("nav").find("li").on("click", "a", function () {
$('.navbar-collapse.in').collapse('hide');
});
}); |
'use strict';
var React = require('react');
var IconBase = require(__dirname + 'components/IconBase/IconBase');
var AndroidMicrophoneOff = React.createClass({
displayName: 'AndroidMicrophoneOff',
render: function render() {
return React.createElement(
IconBase,
null,
React.createElement(
'g',
null,
React.createElement('path', { d: 'M367.951,354.654l-26.616-26.562l-9.568-9.548l-4.698-4.706L187,174.041v0.346L76.112,63.531L51.921,87.572L187,222.47 v28.816c0,37.79,31.121,68.714,68.91,68.714c8.61,0,16.952-1.62,24.565-4.545l32.389,32.274 c-17.333,8.793-36.812,13.86-56.782,13.86c-62.986,0-121.365-48.59-121.365-116.59H95.773C95.773,322,158,387.701,233,398.013V480 h46v-81.987c22-3.352,43.066-11.222,61.627-22.622l95.278,95.078l24.033-24l-33.847-33.785l-58.216-57.959l58.224,57.959 L367.951,354.654z' }),
React.createElement('path', { d: 'M325,251.286V100.714C325,62.924,293.791,32,256,32s-69,30.924-69,68.714v25.244l137.109,136.968 C324.779,259.135,325,255.247,325,251.286z' }),
React.createElement('path', { d: 'M416.439,245h-38.941c0,20.496-5.498,39.676-14.931,56.197l27.572,27.516C406.662,304.603,416.439,275.926,416.439,245z' }),
React.createElement('polygon', { points: '459.999,446.427 426.102,412.684 459.957,446.469 \t' })
)
);
}
}); |
exports.Spec = require("./lib/spec");
exports.Newton = require("./lib/newton");
|
(function($, window) {
'use strict';
var self;
window.TestWebsite = window.TestWebsite || {};
window.TestWebsite.TestRun = window.TestWebsite.TestRun || {};
self = window.TestWebsite.TestRun.IncompleteRun = {
add_handlers: function () {
$("body").on("change keyup", ".testrunfilter", function(e) {
self.submit_form();
});
},
submit_form: function () {
var form = $('form'),
action = form.attr('action');
$.get(action, form.serializeArray()).done(function (content) {
var newData = $(content),
newTable = newData.find('table');
form.replaceWith(newData.find('form'));
if (newTable.length !== 0) {
$('table').replaceWith(newTable);
}
});
}
};
self.add_handlers();
})(jQuery, window); |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupIntl } from 'ember-intl/test-support';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
const s = '[data-test-weekly-calendar-event]';
import { setupMirage } from 'ember-cli-mirage/test-support';
module('Integration | Component | weekly-calendar-event', function (hooks) {
setupRenderingTest(hooks);
setupIntl(hooks, 'en-us');
setupMirage(hooks);
this.createEvent = function (startDate, endDate) {
const lastModified = '2012-01-09 08:00:00';
const color = '#00cc65';
this.server.create('userevent', {
startDate,
endDate,
color,
lastModified,
});
};
this.getStyle = function (rowStart, minutes, columnSpan) {
return {
'background-color': 'rgb(0, 204, 101)',
'border-left-style': 'solid',
'border-left-color': 'rgb(0, 173, 86)',
'grid-row-start': `${rowStart}`,
'grid-row-end': `span ${minutes}`,
'grid-column-start': `span ${columnSpan}`,
};
};
module('A complicated event list', function (hooks) {
hooks.beforeEach(function () {
this.createEvent('2019-01-09 08:00:00', '2019-01-09 09:00:00');
this.createEvent('2019-01-09 08:00:00', '2019-01-09 11:30:00');
this.createEvent('2019-01-09 08:10:00', '2019-01-09 10:00:00');
this.createEvent('2019-01-09 10:00:00', '2019-01-09 12:00:00');
this.createEvent('2019-01-09 10:10:00', '2019-01-09 12:00:00');
this.createEvent('2019-01-09 12:00:00', '2019-01-09 13:00:00');
this.events = this.server.db.userevents;
});
test('it renders alone', async function (assert) {
this.set('event', this.events[0]);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{array this.event}}
/>`);
assert.dom(s).hasStyle(this.getStyle(97, 12, 50));
assert.dom(s).hasText('8:00 AM event 0');
});
test('check event 0', async function (assert) {
this.set('event', this.events[0]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(97, 12, 16));
assert.dom(s).hasText('8:00 AM event 0');
});
test('check event 1', async function (assert) {
this.set('event', this.events[1]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(97, 42, 16));
assert.dom(s).hasText('8:00 AM event 1');
});
test('check event 2', async function (assert) {
this.set('event', this.events[2]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(99, 22, 16));
assert.dom(s).hasText('8:10 AM event 2');
});
test('check event 3', async function (assert) {
this.set('event', this.events[3]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(121, 24, 16));
assert.dom(s).hasText('10:00 AM event 3');
});
test('check event 4', async function (assert) {
this.set('event', this.events[4]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(123, 22, 16));
assert.dom(s).hasText('10:10 AM event 4');
});
test('check event 5', async function (assert) {
this.set('event', this.events[5]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(145, 12, 50));
assert.dom(s).hasText('12:00 PM event 5');
});
});
module('Second complicated event list', function (hooks) {
hooks.beforeEach(function () {
this.createEvent('2020-02-10 08:10:00', '2020-02-10 10:00:00');
this.createEvent('2020-02-10 08:10:00', '2020-02-10 09:20:00');
this.createEvent('2020-02-10 09:40:00', '2020-02-10 10:30:00');
this.createEvent('2020-02-10 10:10:00', '2020-02-10 12:00:00');
this.createEvent('2020-02-10 10:40:00', '2020-02-10 12:30:00');
this.createEvent('2020-02-10 10:40:00', '2020-02-10 12:30:00');
this.createEvent('2020-02-10 10:40:00', '2020-02-10 12:30:00');
this.createEvent('2020-02-10 10:40:00', '2020-02-10 12:30:00');
this.createEvent('2020-02-10 10:40:00', '2020-02-10 12:30:00');
this.createEvent('2020-02-10 10:40:00', '2020-02-10 12:30:00');
this.createEvent('2020-02-10 12:00:00', '2020-02-10 13:00:00');
this.events = this.server.db.userevents;
});
test('check event 0', async function (assert) {
this.set('event', this.events[0]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(99, 22, 25));
assert.dom(s).hasText('8:10 AM event 0');
});
test('check event 1', async function (assert) {
this.set('event', this.events[1]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(99, 14, 25));
assert.dom(s).hasText('8:10 AM event 1');
});
test('check event 2', async function (assert) {
this.set('event', this.events[2]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(117, 10, 25));
assert.dom(s).hasText('9:40 AM event 2');
});
test('check event 3', async function (assert) {
this.set('event', this.events[3]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(123, 22, 7));
assert.dom(s).hasText('10:10 AM event 3');
});
test('check event 4', async function (assert) {
this.set('event', this.events[4]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(129, 22, 6));
assert.dom(s).hasText('10:40 AM event 4');
});
test('check event 5', async function (assert) {
this.set('event', this.events[5]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(129, 22, 6));
assert.dom(s).hasText('10:40 AM event 5');
});
test('check event 6', async function (assert) {
this.set('event', this.events[6]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(129, 22, 6));
assert.dom(s).hasText('10:40 AM event 6');
});
test('check event 7', async function (assert) {
this.set('event', this.events[7]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(129, 22, 6));
assert.dom(s).hasText('10:40 AM event 7');
});
test('check event 8', async function (assert) {
this.set('event', this.events[8]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(129, 22, 6));
assert.dom(s).hasText('10:40 AM event 8');
});
test('check event 9', async function (assert) {
this.set('event', this.events[9]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(129, 22, 6));
assert.dom(s).hasText('10:40 AM event 9');
});
test('check event 10', async function (assert) {
this.set('event', this.events[10]);
this.set('events', this.events);
await render(hbs`<WeeklyCalendarEvent
@event={{this.event}}
@allDayEvents={{this.events}}
/>`);
assert.dom(s).hasStyle(this.getStyle(145, 12, 7));
assert.dom(s).hasText('12:00 PM event 10');
});
});
});
|
AUTH0_CLIENT_ID = '2BGFav69I7MyFUW8gzn8p69HWIszklnN';
AUTH0_DOMAIN = 'willowcorp.auth0.com';
AUTH0_CALLBACK_URL = location.href || 'https://willowcorp.auth0.com/login/callback'; |
// Reference https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
var storageAvailable = function (type) {
try {
var
storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch (e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0;
}
};
// Construction below, is the shorthand of $(document).ready() already.
$(function () {
$('body').on('click', '[data-toggle="lang"]', function (e) {
e.preventDefault();
var selected = $(this);
var locale = selected.attr('lang');
var form = selected.closest('form');
var toggles = form.find('[data-toggle="lang"][lang="' + locale + '"]');
var triggers = form.find('[data-toggle="lang"]');
var group = triggers.closest('.btn-group');
var toggle = group.find('.dropdown-toggle');
var dropdown = group.find('.dropdown-menu');
toggle.text(selected.text());
dropdown.find('a').removeClass('active');
selected.addClass('active');
form.find('.form-group[lang]').addClass('hidden');
form.find('.form-group[lang="' + locale + '"]').removeClass('hidden');
toggles.addClass('active');
if (storageAvailable('localStorage')) {
localStorage.setItem('formTranslations', locale);
}
});
if (storageAvailable('localStorage') && !!localStorage.getItem('formTranslations')) {
$('[data-toggle="lang"][lang="' + localStorage.getItem('formTranslations') + '"]').first().click();
}
});
|
import MediumEditorAutofocus from '../src/Plugin';
describe('Plugin', () => {
let container, editor, plugin;
beforeEach(() => {
container = document.createElement('div');
container.classList.add('editable');
document.body.appendChild(container);
});
afterEach(() => {
editor.destroy();
});
it('Simple init should not fail', () => {
expect(document.activeElement.classList.contains('editable')).toBe(false);
plugin = new MediumEditorAutofocus();
editor = new MediumEditor('.editable', {
extensions: {
insert: plugin
}
});
expect(document.activeElement.classList.contains('editable')).toBe(true);
});
});
|
import url from "url";
import { createPromiseThunkAction } from "./promise-thunk-action";
import fetch from "../utils/fetch";
export default createPromiseThunkAction(
"LOAD_SCHEMA",
async (_, __, getState) => {
const response = await fetch(`${prefix(getState().base)}/api/state.json`);
return response.json();
}
);
function prefix(base) {
return base.charAt(base.length - 1) === "/"
? base.slice(0, base.length - 1)
: base;
}
|
module.exports = {
siteMetadata: {
title: "Marvin's site",
},
plugins: ['gatsby-plugin-react-helmet'],
pathPrefix: `/geeky.rocks`
}
|
modes = ['RGB','RGB','Breathe','Flash','White','Hue'];
needCover = [0,0,0,0,1,1];
$(document).ready(function() {
$('.arrowClose').hide();
// load data
setFromDB();
iterate();
});
function iterate() {
// show and hide the smaller controllers for each area.
$('.arrowOpen').click(function() {
area = $(this).prev().attr('class');
hideAndShow(area,1);
$(this).hide().next().show();
});
$('.arrowClose').click(function() {
area = $(this).prev().prev().attr('class');
hideAndShow(area,-1);
$(this).hide().prev().show();
});
// color slider
$('.controller .ColorSlider').each(function() {
$(this).slider({
orientation:'vertical',
max:255,
min:0,
// slide updates the local display but does not send an update to the DB
slide: function( event, ui ) {
value = $(this).slider("value");
color = $(this).parent().attr('class');
name = $(this).parent().parent().parent().parent().attr('id');
area = $(this).parent().parent().parent().parent().parent().attr('class');
setColor(area,name,color,value,'slider',0);
},
// stop updates the DB and local display
stop: function( event, ui ) {
value = $(this).slider("value");
color = $(this).parent().attr('class');
name = $(this).parent().parent().parent().parent().attr('id');
area = $(this).parent().parent().parent().parent().parent().attr('class');
setColor(area,name,color,value,'slider',1);
}
});
});
// mode slider
$('.mode').each(function() {
$(this).slider({
max:5,
min:0,
// slide updates the local display but does not send an update to the DB
slide: function( event, ui ) {
value = $(this).slider("value");
name = $(this).parent().parent().attr('id');
area = (this).parent().parent().parent().attr('class');
setMode(area,name,value);
},
// stop updates the DB and local display
stop: function( event, ui ) {
value = $(this).slider("value");
name = $(this).parent().parent().attr('id');
area = $(this).parent().parent().parent().attr('class');
setMode(area,name,value);
}
});
});
// min/max buttons
$('button').click(function() {
color = $(this).parent().attr('class');
name = $(this).parent().parent().parent().parent().attr('id');
area = $(this).parent().parent().parent().parent().parent().attr('class');
minOrMax = $(this).attr('class');
if (minOrMax == 'maxBut') {
setColor(area,name,color,255,'button',1);
} else if (minOrMax == 'minBut') {
setColor(area,name,color,0,'button',1);
}
});
}
function testDisplay(arr) {
$('#testDisplay').text(arr);
}
// set the appropriate text below the color and the small single color display.
function setValue(area,name,color,val) {
// if area == name that means it was the master slider and should update the values for all the children
if(area == name) {
$('.'+area).each(function() {
id = $(this).children().attr('id');
setValue(null,id,color,val);
});
} else {
$('#'+name+' .'+color+ ' .ColorVal').text(val);
if(color == 'red') {
$('#'+name+' .red .mini').css('background-color','#'+toHex(val)+'0000');
} else if (color == 'green') {
$('#'+name+' .green .mini').css('background-color','#00'+toHex(val)+'00');
} else {
$('#'+name+' .blue .mini').css('background-color','#0000'+toHex(val));
}
}
}
// sets the RGB display
function setDisplay(area,name) {
// if area == name that means it was the master slider and should update the displays for all the children
if(area == name) {
$('.'+area).each(function() {
id = $(this).children().attr('id');
setDisplay('',id);
});
} else {
r = $('#'+name+' .red .ColorSlider').slider("value");
g = $('#'+name+' .green .ColorSlider').slider("value");
b = $('#'+name+' .blue .ColorSlider').slider("value" );
rgb = rgbToHex(r,g,b);
$('#'+name+' .colorpicker .display').css('background-color','#'+rgb);
}
}
// set the slider if the value was updated by another means
function setSlider(area,name,color,val) {
if(area == name) {
$('.'+area).each(function() {
id = $(this).children().attr('id');
$('#'+id+' .'+color+' .ColorSlider').slider('value',val);
});
} else {
$('#'+name+' .'+color+' .ColorSlider').slider('value',val);
}
}
// send update to DB
function setDB(area,name,color,val) {
if (area) {
url = 'lightingController.php?area=' + area + '&' + color + '=' + val;
$.ajax({
url: url
});
} else {
url = 'lightingController.php?name=' + name + '&' + color + '=' + val;
$.ajax({
url: url
});
}
}
// set the mode
function setMode(area,name,mode) {
// if area == name that means it was the master slider and should update the mode for all the children
if(area == name) {
$('.'+area).each(function() {
id = $(this).children().attr('id');
$('#'+id+' .mode').slider('value',mode);
setCover(id,mode);
setModeName(id,mode);
});
setDB(area,null,'mode',mode);
} else {
$('#'+name+' .mode').slider('value',mode);
setCover(name,mode);
setDB(null,name,'mode',mode);
setModeName(name,mode);
}
}
// covers the sliders because the mode overrides it.
function setCover(name,val) {
if(!needCover[val]) {
$('#'+name+' .cover').css('visibility','hidden');
$('#'+name+' .red .ColorSlider').slider('enable');
$('#'+name+' .green .ColorSlider').slider('enable');
$('#'+name+' .blue .ColorSlider').slider('enable');
} else {
$('#'+name+' .cover').css('visibility','visible');
$('#'+name+' .red .ColorSlider').slider('disable');
$('#'+name+' .green .ColorSlider').slider('disable');
$('#'+name+' .blue .ColorSlider').slider('disable');
}
}
// sets the name of the mode from the array at the top of this document.
function setModeName(name,mode) {
$('#'+name+' .modeName').text('Mode:'+modes[mode]);
}
// set up function to set all values
function setAll(area,name,r,g,b,m) {
var rgb = [r,g,b];
var colors = ['red','green','blue'];
for (var j = 0; j < colors.length;j++){
setSlider(area,name,colors[j],rgb[j]);
setValue(area,name,colors[j],rgb[j]);
}
setDisplay(area,name);
setMode(area,name,m);
}
// master set functions determines which other sets are needed in each case.
function setColor(area,name,color,val,from,stop) {
if(from == 'slider') {
if(area) {
setSlider(area,name,color,val);
}
setValue(area,name,color,val);
} else if (from == 'button') {
setSlider(area,name,color,val);
setValue(area,name,color,val);
} else {
setSlider(area,name,color,val);
setValue(area,name,color,val);
}
setDisplay(area,name);
if(stop) {
if(area == name) {
setDB(area,name,color,val);
} else {
setDB(null,name,color,val);
}
}
}
// initial setup. gets values from DB, then calls setAll() to output
function setFromDB() {
$.get({
url: 'lightingController.php',
data: {unique:1},
success: function(data) {
arr = data.split(',');
for(var i = 0; i <arr.length;i+=6) {
setAll('',arr[i],arr[i+2],arr[i+3],arr[i+4],arr[i+5]);
hideAndShow(arr[i],-1);
setCover(arr[i],0);
}
}
});
$.ajax({
url: 'lightingController.php',
success: function(data) {
arr = data.split(',');
for(var i = 0; i <arr.length;i+=6) {
setAll(arr[i],arr[i+1],arr[i+2],arr[i+3],arr[i+4],arr[i+5]);
}
}
});
$('#loading').hide();
}
// hides or shows the smaller controllers
function hideAndShow(area,hide) {
var index = 1;
var dis = 14.1;
if(hide > 0) {
$('.'+area).each(function() {
id = $(this).children().attr('id');
if(id != area) {
str = '+=' + (index*dis) + 'em';
$('#'+id).animate({left:str});
index++;
}
});
} else {
$('.'+area).each(function() {
id = $(this).children().attr('id');
if(id != area) {
str = '-=' + (index*dis) + 'em';
$('#'+id).animate({left:str});
index++;
}
});
}
}
// from http://www.javascripter.net/faq/rgbtohex.htm
// convert from RGB to Hex, or from Hex to RGB
function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(n) {
n = parseInt(n,10);
if (isNaN(n)) return "00";
n = Math.max(0,Math.min(n,255));
return "0123456789ABCDEF".charAt((n-n%16)/16)
+ "0123456789ABCDEF".charAt(n%16);
}
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} |
import { registerEnumeration } from "lib/misc/factories";
import {BinaryStream} from "lib/misc/binaryStream";
import assert from "better-assert";
const EnumBrowseDirection_Schema = {
name: "BrowseDirection",
enumValues: {
Invalid: -1, //
Forward: 0, // Return forward references.
Inverse: 1, //Return inverse references.
Both: 2 // Return forward and inverse references.
},
decode: function(stream) {
assert(stream instanceof BinaryStream);
const value = stream.readInteger();
if (value<0 || value>2) {
return exports.BrowseDirection.Invalid;
}
return exports.BrowseDirection.get(value);
}
};
export {EnumBrowseDirection_Schema};
export const BrowseDirection = registerEnumeration(EnumBrowseDirection_Schema);
|
var app = app || {};
/**
* @name slider
* @author Pascal Franzke <pascal.franzke@googlemail.com>
* @namespace slider
* @memberof app
* @param {window} Object - Das window-Objekt
* @param {$} function - jQuery
* @requires jQuery
* @return Object - Die Public-API des Modules
*/
app.slider = (function () { // use data-module="slider" to start this script
'use strict';
var options = {
owlClass: 'owl-carousel',
owlFixClass: 'owl-fix' //sorgt dafür das das Owlcarousel nicht standartmäíg ausgeblendet wird und somit springt!
};
/**
* Default Owl Option
*/
var owloptions = {
nav: true,
loop: true,
dots: false,
items: 2,
margin: 10,
autoplay: true,
mouseDrag: false,
autoHeight: true,
autoplayTimeout: 4000,
autoplayHoverPause: true,
responsive: {
items: 2,
0: {
items: 1
},
640: {
items: 2
}
},
navText: [
'<span class="audible">Back</span><span class="icon icon--angle-left nav__icon"></span>',
'<span class="audible">Next</span><span class="icon icon--angle-right nav__icon"></span>'
]
};
/**
* typebase Owl Options
*/
var owloptionsTypes = {
noAutoplay: {
autoplay: false
},
};
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1 + mergest Array if a point is an Array! (but not insed the array merges things)
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
var merge = function _merge(def, obj) {
if (typeof obj === 'undefined') {
return def;
} else if (typeof def === 'undefined') {
return obj;
}
for (var i in obj) {
if (obj[i] !== null && obj[i].constructor === Object) {
def[i] = merge(def[i], obj[i]);
} else if (obj[i] !== null && obj[i].constructor === Array) {
def[i] = def[i].concat(obj[i]);
} else {
def[i] = obj[i];
}
}
return def;
};
var getOptionFor = function getOptionFor(type) {
if (typeof owloptionsTypes[type] !== 'object') {
return owloptions;
}
return merge(owloptions, owloptionsTypes[type]);
};
/**
* slider->init(elements)
* creates an owl carousel on all given elements
*
* @param {array} elements[{HTMLElement}]
* @return {boolen}
* @memberOf app.slider
*/
var init = function _init() {
return true;
};
/**
* slider->initOwl(element)
* creates an owl carousel on given element
*
* @private
* @param {HTMLElement} element
* @memberOf app.slider
*/
var newEl = function _newEl(element) {
var $el = $(element);
if (!$el.hasClass(options.owlClass)) {
$el.addClass(options.owlClass);
}
var typeBasedOptions = getOptionFor($el.attr('data-type'));
var $owl = $el.owlCarousel(typeBasedOptions);
if ($el.hasClass(options.owlFixClass)) {
$el.removeClass(options.owlFixClass);
}
return $owl;
};
/**
* slider->destroy(element)
* removes owl carousel on given element
*
* @private
* @param {HTMLElement} element
* @memberOf app.slider
*/
var destroy = function _destroy(element) {
return $(element).data('owlCarousel').destroy();
};
/**
* slider->owlChromeFix()
* Fixs a 3d Transition problem with chrome and images
*
* @private
* @return {boolen}
* @memberOf app.owlChromeFix
*/
var owlChromeFix = function _owlChromeFix() {
$.fn.owlCarousel.Constructor.prototype.animate = function (coordinate) {
var animate = this.speed() > 0;
this.is('animating') && this.onTransitionEnd();
if (animate) {
this.enter('animating');
this.trigger('translate');
}
if ($.support.transform3d && $.support.transition) {
this.$slider.css({
transform: 'translate(' + coordinate + 'px,0px)',
transition: (this.speed() / 1000) + 's'
});
} else if (animate) {
this.$slider.animate({
left: coordinate + 'px'
}, this.speed(), this.settings.fallbackEasing, $.proxy(this.onTransitionEnd, this));
} else {
this.$slider.css({
left: coordinate + 'px'
});
}
};
return true;
};
return {
init: init,
new: newEl,
owlChromeFix: owlChromeFix,
destroy: destroy
};
})();
|
define( [ 'js/app', 'marionette', 'handlebars', 'js/views/Argazkiak/ArgazkiakView'],
function( App, Marionette, Handlebars, ArgazkiakView) {
//ItemView provides some default rendering logic
return Marionette.CollectionView.extend( {
childView: ArgazkiakView
});
}); |
/*
Report posts you don't like
*/
const main = require('./main'),
{$, $script, _, Backbone, common, lang} = main;
// TODO: Rewrite this and move to API v2
const pubKey = main.config.RECAPTCHA_PUBLIC_KEY,
captchaTimeout = 5 * 60 * 1000,
repLang = lang.reports,
reports = {};
let panel;
let Report = Backbone.Model.extend({
defaults: {
status: 'setup',
hideAfter: true
},
request_new() {
Recaptcha.create(pubKey, 'captcha', {
theme: 'clean',
callback: () => this.set('status', 'ready')
});
if (this.get('timeout'))
clearTimeout(this.get('timeout'));
this.set('timeout', setTimeout(() => {
this.set('timeout', 0);
this.request_new();
}, captchaTimeout));
},
did_report() {
delete reports[this.id];
if (this.get('timeout')) {
clearTimeout(this.get('timeout'));
this.set('timeout', 0);
}
setTimeout(() => this.trigger('destroy'), 1500);
if (this.get('hideAfter'))
this.get('post').set('hide', true);
}
});
var ReportPanel = Backbone.View.extend({
id: 'report-panel',
tagName: 'form',
className: 'modal',
events: {
submit: 'submit',
'click .close': 'remove',
'click .hideAfter': 'hide_after_changed'
},
initialize() {
this.$captcha = $('<div id="captcha"/>');
this.$message = $('<div class="message"/>');
this.$submit = $('<input>', {
type: 'submit',
val: 'Report'
});
let $hideAfter = $('<input>', {
class: 'hideAfter',
type: 'checkbox',
checked: this.model.get('hideAfter')
});
let $hideLabel = $('<label>and hide</label>').append($hideAfter);
const num = this.model.get('post').get('num');
this.$el.append(
repLang.post + ' ',
main.oneeSama.postRef(num).safe,
'<a class="close" href="#">x</a>',
this.$message,
this.$captcha,
this.$submit,
' ',
$hideLabel
);
/* HACK */
if (window.x_csrf) {
this.model.set('hideAfter', false);
$hideLabel.remove();
}
this.listenTo(this.model, {
'change:error': this.error_changed,
'change:status': this.status_changed,
destroy: this.remove
});
},
render() {
this.error_changed();
this.status_changed();
return this;
},
submit() {
if (this.model.get('status') != 'ready')
return false;
main.send([
common.REPORT_POST,
parseInt(this.model.get('post').get('num'), 10),
Recaptcha.get_challenge(),
Recaptcha.get_response()
]);
this.model.set('status', 'reporting');
return false;
},
error_changed() {
this.$message.text(this.model.get('error'));
},
status_changed() {
const status = this.model.get('status');
this.$submit
.prop('disabled', status != 'ready')
.toggle(status !== 'done')
.val(status === 'reporting' ? repLang.reporting : lang.report);
this.$captcha.toggle(
_.contains(['ready', 'reporting', 'error'], status)
);
if (status === 'done')
this.$('label').remove();
let msg;
if (status === 'done')
msg = repLang.submitted;
else if (status == 'setup')
msg = repLang.setup;
else if (status == 'error'
|| (status == 'ready' && this.model.get('error')))
msg = 'E';
this.$message.text(msg === 'E' ? this.model.get('error') : msg);
this.$message.toggle(!!msg).toggleClass('error', msg == 'E');
// not strictly view logic, but only relevant when visible
if (status == 'ready')
this.focus();
else if (status == 'done')
this.model.did_report();
else if (status == 'error')
this.model.request_new();
},
hide_after_changed(e) {
this.model.set('hideAfter', e.target.checked);
},
focus() {
Recaptcha.focus_response_field();
},
remove() {
Backbone.View.prototype.remove.call(this);
if (panel === this) {
panel = null;
Recaptcha.destroy();
}
return false;
}
});
main.reply('report', function(post) {
const url = 'https://www.google.com/recaptcha/api/js/recaptcha_ajax.js';
$script(url, function () {
const num = post.get('num');
let model = reports[num];
if (!model) {
reports[num] = model = new Report({
id: num,
post: post
});
}
if (panel) {
if (panel.model === model) {
panel.focus();
return;
}
panel.remove();
}
panel = new ReportPanel({model: model});
panel.render().$el.appendTo('body');
if (window.Recaptcha)
model.request_new();
else {
model.set({
status: 'error',
error: repLang.loadError
});
}
});
});
main.dispatcher[common.REPORT_POST] = function(msg) {
const report = reports[msg[0]];
if (report)
report.set(msg[1] || {status: 'done'});
};
|
(function (global) {
global.window = global; // Fake the window
var sinonChai = require('sinon-chai'),
TWEEN = require('tween.js'),
_ = require('lodash'),
chai = require('chai'),
sinon = require('sinon');
global.chai = chai;
global.sinon = undefined;
global.expect = chai.expect;
global.AssertionError = chai.AssertionError;
require('sinon-mocha').enhance(sinon);
chai.use(sinonChai);
beforeEach(function () {
global.sinon = sinon.sandbox.create({
useFakeTimers: true
});
});
afterEach(function () {
global.sinon.restore();
});
global.playAnimation = function playAnimation(millis, fps) {
TWEEN.update();
_.times(fps * (millis / 1000), function () {
sinon.clock.tick(Math.round(1000 / fps));
TWEEN.update();
});
};
global.playAnimation.cleanUp = TWEEN.removeAll;
})(global);
|
'use strict';
//Product categories service used to communicate Product categories REST endpoints
angular.module('product-categories').factory('ProductCategories', ['$resource',
function($resource) {
return $resource('product-categories/:productCategoryId', { productCategoryId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]); |
module.exports = function (obj) {
var out = {};
var ary = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ary.push(key);
}
}
ary.sort();
for (var i = 0; i < ary.length; i++) {
out[ary[i]] = obj[ary[i]];
}
return out;
};
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define({title:"Trova posizione personale"}); |
#!/usr/bin/env node
/**
* Git COMMIT-MSG hook for validating commit message
* See https://docs.google.com/document/d/1rk04jEuGfk9kYzfqCuOlPTSJw3hEDZJTBN5E5f1SALo/edit
*
* Installation:
* >> cd <angular-repo>
* >> ln -s validate-commit-msg.js .git/hooks/commit-msg
*/
var fs = require('fs');
var util = require('util');
var MAX_LENGTH = 70;
var PATTERN = /^(?:fixup!\s*)?(\w*)(\((\w+)\))?\: (.*)$/;
var IGNORED = /^WIP\:/;
var TYPES = {
chore: true,
demo: true,
docs: true,
feat: true,
fix: true,
refactor: true,
revert: true,
style: true,
test: true
};
var error = function() {
// gitx does not display it
// http://gitx.lighthouseapp.com/projects/17830/tickets/294-feature-display-hook-error-message-when-hook-fails
// https://groups.google.com/group/gitx/browse_thread/thread/a03bcab60844b812
console.error('INVALID COMMIT MSG: ' + util.format.apply(null, arguments));
};
var validateMessage = function(message) {
var isValid = true;
if (IGNORED.test(message)) {
console.log('Commit message validation ignored.');
return true;
}
if (message.length > MAX_LENGTH) {
error('is longer than %d characters !', MAX_LENGTH);
isValid = false;
}
var match = PATTERN.exec(message);
if (!match) {
error('does not match "<type>(<scope>): <subject>" ! was: "' + message + '"\nNote: <scope> must be only letters.');
return false;
}
var type = match[1];
var scope = match[3];
var subject = match[4];
if (!TYPES.hasOwnProperty(type)) {
error('"%s" is not allowed type !', type);
return false;
}
// Some more ideas, do want anything like this ?
// - allow only specific scopes (eg. fix(docs) should not be allowed ?
// - auto correct the type to lower case ?
// - auto correct first letter of the subject to lower case ?
// - auto add empty line after subject ?
// - auto remove empty () ?
// - auto correct typos in type ?
// - store incorrect messages, so that we can learn
return isValid;
};
var firstLineFromBuffer = function(buffer) {
return buffer.toString().split('\n').shift();
};
// publish for testing
exports.validateMessage = validateMessage;
// hacky start if not run by jasmine :-D
if (process.argv.join('').indexOf('jasmine-node') === -1) {
var commitMsgFile = process.argv[2] || process.env.GIT_PARAMS;
var incorrectLogFile = commitMsgFile.replace('COMMIT_EDITMSG', 'logs/incorrect-commit-msgs');
fs.readFile(commitMsgFile, function(err, buffer) {
var msg = firstLineFromBuffer(buffer);
if (!validateMessage(msg)) {
fs.appendFile(incorrectLogFile, msg + '\n', function() {
process.exit(1);
});
} else {
process.exit(0);
}
});
}
|
const prependFile = require('prepend-file');
const path = require('path');
const APP_DIR = path.resolve(__dirname, "./src/");
const OUT_DIR = path.resolve(__dirname, "./dist/");
const MODULES_DIR = path.resolve(__dirname, "./node_modules/");
// required for legal reuse of components
var header = "/*\n" +
` * ${process.env.npm_package_name} - v${process.env.npm_package_version}\n` +
` * ${process.env.npm_package_description}\n` +
` * ${process.env.npm_package_homepage}\n` +
" *\n" +
` * Made by ${process.env.npm_package_author_name}\n` +
` * Under ${process.env.npm_package_license} License\n` +
" *\n" +
" * Thanks to https://github.com/jquery-boilerplate/jquery-boilerplate, MIT License © Zeno Rocha\n" +
" */\n";
require('laravel-mix')
.setResourceRoot('../')
.setPublicPath('dist')
.copy(`${APP_DIR}/jquery.eclipsefdn-api.js`, `${OUT_DIR}/jquery.eclipsefdn-api.js`)
.copy(`${APP_DIR}/jquery.eclipsefdn-igc.js`, `${OUT_DIR}/jquery.eclipsefdn-igc.js`)
.scripts([
`${APP_DIR}/jquery.eclipsefdn-api.js`,
`${MODULES_DIR}/mustache/mustache.min.js`
], `${OUT_DIR}/jquery.eclipsefdn-api.min.js`)
.scripts(`${APP_DIR}/jquery.eclipsefdn-igc.js`, `${OUT_DIR}/jquery.eclipsefdn-igc.min.js`)
.then(function () {
prependFile(`${OUT_DIR}/jquery.eclipsefdn-api.js`, header, function(err) {
if (err) {
console.log(err);
System.exit(1);
}
});
prependFile(`${OUT_DIR}/jquery.eclipsefdn-igc.js`, header, function(err) {
if (err) {
console.log(err);
System.exit(1);
}
});
prependFile(`${OUT_DIR}/jquery.eclipsefdn-api.min.js`, header, function(err) {
if (err) {
console.log(err);
System.exit(1);
}
});
prependFile(`${OUT_DIR}/jquery.eclipsefdn-igc.min.js`, header, function(err) {
if (err) {
console.log(err);
System.exit(1);
}
});
}); |
var LetExpCodeGenMixin = (Base) => class extends Base {
getType() {
return "LetExp";
}
genJson() {
let json = Object.assign(super.genJson());
json.type = "";
return json;
}
}
module.exports = LetExpCodeGenMixin;
|
/**
* @file 绘制contour曲线
* @author mengke01(kekee000@gmail.com)
*/
/**
* ctx绘制轮廓
*
* @param {CanvasRenderingContext2D} ctx canvas会话
* @param {Array} contour 轮廓序列
*/
export default function drawPath(ctx, contour) {
let curPoint;
let prevPoint;
let nextPoint;
let i;
let l;
for (i = 0, l = contour.length; i < l; i++) {
curPoint = contour[i];
prevPoint = i === 0 ? contour[l - 1] : contour[i - 1];
nextPoint = i === l - 1 ? contour[0] : contour[i + 1];
// 起始坐标
if (i === 0) {
if (curPoint.onCurve) {
ctx.moveTo(curPoint.x, curPoint.y);
}
else {
if (prevPoint.onCurve) {
ctx.moveTo(prevPoint.x, prevPoint.y);
}
else {
ctx.moveTo((prevPoint.x + curPoint.x) / 2, (prevPoint.y + curPoint.y) / 2);
}
}
}
// 直线
if (curPoint.onCurve && nextPoint.onCurve) {
ctx.lineTo(nextPoint.x, nextPoint.y);
}
else if (!curPoint.onCurve) {
if (nextPoint.onCurve) {
ctx.quadraticCurveTo(curPoint.x, curPoint.y, nextPoint.x, nextPoint.y);
}
else {
ctx.quadraticCurveTo(
curPoint.x, curPoint.y,
(curPoint.x + nextPoint.x) / 2, (curPoint.y + nextPoint.y) / 2
);
}
}
}
}
|
'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('Berserk', function () {
afterEach(function () {
battle.destroy();
});
it(`should activate prior to healing from Sitrus Berry`, function () {
battle = common.createBattle([[
{species: "Drampa", item: 'sitrusberry', ability: 'berserk', evs: {hp: 4}, moves: ['sleeptalk']},
], [
{species: "wynaut", ability: 'compoundeyes', moves: ['superfang']},
]]);
battle.makeChoices();
const drampa = battle.p1.active[0];
assert.statStage(drampa, 'spa', 1);
assert.equal(drampa.hp, Math.floor(drampa.maxhp / 2) + Math.floor(drampa.maxhp / 4));
});
it(`should not activate prior to healing from Sitrus Berry after a multi-hit move`, function () {
battle = common.createBattle([[
{species: "Drampa", item: 'sitrusberry', ability: 'berserk', evs: {hp: 4}, moves: ['sleeptalk']},
], [
{species: "wynaut", ability: 'parentalbond', moves: ['seismictoss']},
]]);
battle.makeChoices();
const drampa = battle.p1.active[0];
assert.statStage(drampa, 'spa', 0);
assert.equal(drampa.hp, drampa.maxhp - 200 + Math.floor(drampa.maxhp / 4));
});
});
|
// Generate Module Template
const toCapitalize = require('../helper.js').toCapitalize;
/**
* @param {String} name
*/
module.exports = function (name) {
return `import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
class ${toCapitalize(name)} extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div>${name} Module</div>
)
}
}
const mapStateToProps = state => ({})
const mapDispatchToProps = dispatch => ({})
${toCapitalize(name)}.propTypes = {}
export default connect(mapStateToProps, mapDispatchToProps)(${toCapitalize(name)})`;
} |
const { app, BrowserWindow, Menu, ipcMain, shell } = require('electron');
const path = require('path');
const Store = require('electron-store');
const Window = require('./Window');
const portalWindow = require('./portal-window');
const settingsWindow = require('./settings-window');
class CompetitionWindow extends Window {
constructor() {
super();
this.sizes = {
58.8: {
width: 1264,
height: 758,
},
84.286: {
width: 1184,
height: 894,
},
};
}
open(competition) {
if (this.window !== null) {
this.window.focus();
return;
}
const size = this.sizes[competition.matchViewerPercentage] || this.sizes[58.8];
this.window = new BrowserWindow({
width: size.width,
height: size.height,
useContentSize: true,
icon: this.iconPath,
show: false,
});
portalWindow.close();
this.window.competition = competition;
this.window.store = new Store({ name: competition.id });
this.window.version = require('../../package.json').version;
this.window.resultFileDirectory = app.getPath('temp');
this.window.matchViewerPath = path.resolve(app.getPath('temp'), 'match-viewer.html');
this.setMenu(this.getMenu(competition));
this.window.loadURL('file:///' + path.resolve(__dirname, '../public/competition.html'));
this.attachEvents();
this.window.on('show', () => this.window.maximize());
}
getMenu(competition) {
const settingsItem = {
label: 'Settings',
accelerator: 'CmdOrCtrl+,',
click: () => settingsWindow.open(competition),
};
const openPortalItem = {
label: 'Back to the portal',
click: () => {
ipcMain.once('ready-to-close', () => {
portalWindow.open();
settingsWindow.close();
this.close();
});
this.window.webContents.send('close');
},
};
const openCompetitionPageItem = {
label: 'Competition page',
click: () => shell.openExternal(competition.url),
};
const template = [
{
label: 'File',
submenu: [
settingsItem,
openPortalItem,
{ type: 'separator' },
{ role: 'quit' },
],
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteandmatchstyle' },
{ role: 'delete' },
{ role: 'selectall' },
],
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forcereload' },
{ role: 'toggledevtools' },
{ type: 'separator' },
{ role: 'resetzoom' },
{ role: 'zoomin' },
{ role: 'zoomout' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
},
{
role: 'window',
submenu: [
{ role: 'minimize' },
{ role: 'close' },
]
},
{
label: 'Help',
submenu: [
openCompetitionPageItem,
],
},
];
if (process.platform === 'darwin') {
template[0] = {
label: app.getName(),
submenu: [
{ role: 'about' },
{ type: 'separator' },
settingsItem,
openPortalItem,
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideothers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' },
],
};
template[3].submenu = [
{ role: 'close' },
{ role: 'minimize' },
{ role: 'zoom' },
{ type: 'separator' },
{ role: 'front' },
];
}
return Menu.buildFromTemplate(template);
}
}
module.exports = new CompetitionWindow();
|
import React from 'react';
import Immutable, { Map } from 'immutable';
import { format } from 'util';
import sync from './sync';
import * as l from './core/index';
import { dataFns } from './utils/data_utils';
const { get, set } = dataFns(['i18n']);
import enDictionary from './i18n/en';
import { load, preload } from './utils/cdn_utils';
export function str(m, keyPath, ...args) {
return format(get(m, ['strings'].concat(keyPath), ''), ...args);
}
export function html(m, keyPath, ...args) {
const html = str(m, keyPath, ...args);
return html ? React.createElement('span', { dangerouslySetInnerHTML: { __html: html } }) : null;
}
export function group(m, keyPath) {
return get(m, ['strings'].concat(keyPath), Map()).toJS();
}
export function initI18n(m) {
const language = l.ui.language(m);
const overrides = l.ui.dict(m);
const defaultDictionary = Immutable.fromJS(enDictionary);
let base = languageDictionaries[language] || Map({});
if (base.isEmpty()) {
base = overrides;
m = sync(m, 'i18n', {
syncFn: (_, cb) => syncLang(m, language, cb),
successFn: (m, result) => {
registerLanguageDictionary(language, result);
const overrided = Immutable.fromJS(result).mergeDeep(overrides);
assertLanguage(m, overrided.toJS(), enDictionary);
return set(m, 'strings', defaultDictionary.mergeDeep(overrided));
}
});
} else {
assertLanguage(m, base.toJS(), enDictionary);
}
base = defaultDictionary.mergeDeep(base).mergeDeep(overrides);
return set(m, 'strings', base);
}
function assertLanguage(m, language, base, path = '') {
Object.keys(base).forEach(key => {
if (!language.hasOwnProperty(key)) {
l.warn(m, `language does not have property ${path}${key}`);
} else {
if (typeof base[key] === 'object') {
assertLanguage(m, language[key], base[key], `${path}${key}.`);
}
}
});
}
// sync
function syncLang(m, language, cb) {
load({
method: 'registerLanguageDictionary',
url: `${l.languageBaseUrl(m)}/js/lock/${__VERSION__}/${language}.js`,
check: str => str && str === language,
cb: (err, _, dictionary) => {
cb(err, dictionary);
}
});
}
const languageDictionaries = [];
function registerLanguageDictionary(language, dictionary) {
languageDictionaries[language] = Immutable.fromJS(dictionary);
}
registerLanguageDictionary('en', enDictionary);
preload({
method: 'registerLanguageDictionary',
cb: registerLanguageDictionary
});
|
(function () {
"use strict";
angular.module('ngSeApi').factory('seaCustomerApiKey', ['SeaRequest',
function seaCustomerTag(SeaRequest) {
var request = new SeaRequest('customer/{cId}/apiKey/{apiKey}'),
requestDistri = new SeaRequest('customer/apiKey/{apiKey}');
function format(apiKey) {
if(apiKey.validUntil) {
apiKey.validUntil = new Date(apiKey.validUntil);
}
if(apiKey.createdOn) {
apiKey.createdOn = new Date(apiKey.createdOn);
}
return apiKey;
}
function list(cId) {
var p;
if(!cId) {
p = requestDistri.get();
} else {
p = request.get({
cId: cId
});
}
return p.then(function (apiKeys) {
angular.forEach(apiKeys, format);
return apiKeys;
});
}
function get(cId, query) {
query = query || {};
query.cId = cId;
return request.get(query).then(format);
}
function destroy(cId, apiKey) {
return request.del({
cId: cId,
apiKey: apiKey
});
}
return {
/**
* list all api keys of a customer or all your customers
* @param {String} cId empty or customerId
*/
list: function (cId) {
return list(cId);
},
get: function (cId, query) {
return get(cId, query);
},
destroy: function (cId, apiKey) {
return destroy(cId, apiKey);
}
};
}]);
})(); |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var platform_browser_1 = require('@angular/platform-browser');
var http_1 = require('@angular/http');
var router_1 = require('@angular/router');
var forms_1 = require('@angular/forms');
var app_component_1 = require('./components/app.component');
var courses_component_1 = require('./components/courses.component');
var coursebox_component_1 = require('./components/coursebox.component');
var cart_component_1 = require('./components/cart.component');
var welcome_component_1 = require('./components/welcome.component');
var details_component_1 = require('./components/details.component');
var login_component_1 = require('./components/login.component');
var routes = [
{
path: '',
component: welcome_component_1.WelcomeComponent
},
{
path: 'courses',
component: courses_component_1.CoursesComponent
},
{
path: 'course/:id',
component: details_component_1.CourseDetail
},
{
path: 'login',
component: login_component_1.LoginComponent
}
];
var AppModule = (function () {
function AppModule() {
}
AppModule = __decorate([
core_1.NgModule({
imports: [platform_browser_1.BrowserModule,
http_1.HttpModule,
router_1.RouterModule.forRoot(routes),
forms_1.FormsModule],
declarations: [app_component_1.AppComponent,
courses_component_1.CoursesComponent,
coursebox_component_1.CourseBoxComponent,
cart_component_1.CartComponent,
welcome_component_1.WelcomeComponent,
details_component_1.CourseDetail,
login_component_1.LoginComponent],
bootstrap: [app_component_1.AppComponent]
}),
__metadata('design:paramtypes', [])
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
//# sourceMappingURL=app.module.js.map |
/**
* Created by pi on 8/2/16.
*/
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
*
* @param {function} proto is the prototype of the function which needs to inherit.
* @param {function} superProto the prototype of the function to inherit from.
* @throws {TypeError} Will error if either constructor is null, or if
* the super constructor lacks a prototype.
*
*/
exports.inherits = function (proto, superProto) {
if (proto === undefined || proto === null)
throw new TypeError('The prototype to `inherits` must not be ' +
'null or undefined.');
if (superProto === undefined || superProto === null)
throw new TypeError('The super prototype to `inherits` must not ' +
'be null or undefined.');
for (var p in superProto) {
// console.log('try to inherits p: ' + p);
// console.log('type p: ' + typeof (superProto[p]) );
if (typeof (superProto[p]) === 'function') {
// console.log('inherits p: ' + p);
proto[p] = superProto[p];
}
}
};
exports.pad = function (num, size) {
var s = "000000000" + num;
return s.substr(s.length - size);
};
exports.getDisplayState = function (StateEnum, stateValue) {
var displayState ='';
for(var stateName in StateEnum){
if(StateEnum.hasOwnProperty(stateName)){
if(StateEnum[stateName]==stateValue){
// displayState = i18n.__(stateName);
console.log('stateName: ' + stateName);
displayState = stateName;
return displayState;
}
}
}
if(displayState ==''){
return stateValue;
}
};
|
var iquery_8php =
[
[ "network_query", "iquery_8php.html#aa41c07bf856eb8b386430cc53d80d4ac", null ]
]; |
'use strict'
var koa = require('koa')
, route = require('koa-route')
, thunkify = require('thunkify')
var qs = require('qs')
var config = require('../config')
var f = {
1: require('../flow/oauth1'),
2: require('../flow/oauth2'),
3: require('../flow/getpocket')
}
var flows = {
1:{step1:thunkify(f[1].step1), step2:f[1].step2, step3:thunkify(f[1].step3)},
2:{step1:f[2].step1, step2:thunkify(f[2].step2), step3:f[2].step3},
getpocket:{step1:thunkify(f[3].step1), step2:f[3].step2, step3:thunkify(f[3].step3)}
}
function Grant (_config) {
var app = koa()
app.config = config.init(_config)
app._config = config
app.use(route.all('/connect/:provider/:override?', function *(provider, override, next) {
if (!this.session)
throw new Error('Grant: mount session middleware first')
if (this.method == 'POST' && !this.request.body)
throw new Error('Grant: mount body parser middleware first')
yield next
}))
app.use(route.get('/connect/:provider/:override?', function *(provider, override) {
if (override == 'callback') return yield callback
this.session.grant = {
provider:provider,
override:override,
dynamic:this.request.query
}
yield connect
}))
app.use(route.post('/connect/:provider/:override?', function *(provider, override) {
this.session.grant = {
provider:provider,
override:override,
dynamic:this.request.body
}
yield connect
}))
function* connect () {
var grant = this.session.grant
var provider = config.provider(app.config, grant)
var flow = flows[provider.oauth]
if (provider.oauth == 1) {
var data
try {
data = yield flow.step1(provider)
} catch (err) {
return this.response.redirect(provider.callback + '?' + err)
}
grant.step1 = data
var url = flow.step2(provider, data)
this.response.redirect(url)
}
else if (provider.oauth == 2) {
grant.state = provider.state
var url = flow.step1(provider)
this.response.redirect(url)
}
else if (flow) {
try {
var data = yield flow.step1(provider)
} catch (err) {
return this.response.redirect(provider.callback + '?' + err)
}
grant.step1 = data
var url = flow.step2(provider, data)
this.response.redirect(url)
}
}
function* callback () {
var grant = this.session.grant
var provider = config.provider(app.config, grant)
var flow = flows[provider.oauth]
var callback = function (response) {
if (!provider.transport || provider.transport == 'querystring') {
this.response.redirect(provider.callback + '?' + response)
}
else if (provider.transport == 'session') {
this.session.grant.response = qs.parse(response)
this.response.redirect(provider.callback)
}
}.bind(this)
if (provider.oauth == 1) {
try {
var response = yield flow.step3(provider, grant.step1, this.query)
} catch (err) {
return this.response.redirect(provider.callback + '?' + err)
}
callback(response)
}
else if (provider.oauth == 2) {
try {
var data = yield flow.step2(provider, this.query, grant)
} catch (err) {
return this.response.redirect(provider.callback + '?' + err)
}
var response = flow.step3(provider, data)
callback(response)
}
else if (flow) {
try {
var response = yield flow.step3(provider, grant.step1)
} catch (err) {
return this.reponse.redirect(provider.callback + '?' + err)
}
callback(response)
}
}
return app
}
exports = module.exports = Grant
|
/**
* WEBPACK CONFIG
*
* Notes on config properties:
*
* 'entry'
* Entry point for the bundle.
*
* 'output'
* If you pass an array - the modules are loaded on startup. The last one is exported.
*
* 'resolve'
* Array of file extensions used to resolve modules.
*
* devtool: 'eval-source-map'
* http://www.cnblogs.com/Answer1215/p/4312265.html
* The source map file will only be downloaded if you have source maps enabled
* and your dev tools open.
*
* OccurrenceOrderPlugin
* Assign the module and chunk ids by occurrence count. Ids that are used often
* get lower (shorter) ids. This make ids predictable, reduces to total file size
* and is recommended.
*
* UglifyJsPlugin
* Minimize all JavaScript output of chunks. Loaders are switched into minimizing mode.
* - 'compress'
* Compressor is a tree transformer which reduces the code size by applying
* various optimizations on the AST.
*
* 'NODE_ENV'
* React relies on process.env.NODE_ENV based optimizations.
* If we force it to production, React will get in an optimized manner.
* This will disable some checks (eg. property type checks) and give you a smaller
* build and improved performance.
*
* Note: That JSON.stringify is needed as webpack will perform string replace
* "as is". In this case we'll want to end up with strings as that's what
* various comparisons expect, not just production. Latter would just cause
* an error.
*
* 'babel'
* Babel enables the use of ES6 today by transpiling your ES6 JavaScript into
* equivalent ES5 source that is actually delivered to the end user browser.
*/
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './scripts/index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devtool: 'source-map',
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel'],
include: path.join(__dirname, 'scripts')
}
]
}
};
|
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var assets = 'assets';
module.exports = {
entry: {
app: './src/main'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
chunkFilename: '[id].js',
publicPath: '/'
},
plugins: [
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin(assets + '/[name].css', { allChunks: true }),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
},
__DEV_TOOLS__: false
}),
new HtmlWebpackPlugin({
title: 'Slack Frame',
filename: 'index.html',
template: 'index.template.html',
favicon: path.join(__dirname, assets + '/images/favicon.ico')
}),
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
})
],
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css!cssnext')
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract('style', 'css!cssnext!less')
},
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?digest=hex&name=' + assets + '/[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{
test: /\.(ttf|eot|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file?name=' + assets + '/[hash].[ext]'
},
{
test: /\.(wav|mp3)$/i,
loader: 'file?name=' + assets + '/[hash].[ext]'
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
cssnext: {
browsers: 'last 2 versions'
}
};
|
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function (nums, target) {
nums.sort(function (a, b) {
return a - b;
});
// used code from question 15, made some small changes
const threeSum = (start, nums, target)=> {
var i = start + 1;
while (i < nums.length - 2) {
var j = i + 1;
var k = nums.length - 1;
while (j < k) {
var sum = nums[i] + nums[j] + nums[k];
if (sum === target) {
result.push([nums[start], nums[i], nums[j], nums[k]]);
}
if (sum <= target) while (nums[j] === nums[++j] && j < k);
if (sum >= target) while (nums[k--] === nums[k] && j < k);
}
while (nums[i] === nums[++i] && i < nums.length - 2);
}
};
var result = [];
var i = 0;
while (i <= nums.length - 4) {
threeSum(i, nums, target - nums[i]);
while (nums[i] === nums[++i] && i <= nums.length - 4);
}
return result;
}; |
'use strict';
const logger = require('./logger')();
module.exports = (dates, fs) => {
function saveReportOnDisk(report) {
const reportsDir = 'reports/';
const date = dates.getDate();
const filename = `report-${date}.txt`;
try {
if (!fs.existsSync(reportsDir)){
fs.mkdirSync(reportsDir);
}
fs.writeFileSync(reportsDir + filename, report);
logger.write('Report was successfully saved to disk');
} catch (e) {
logger.write('Report wasn\'t saved to disk!');
}
}
return {
makeReport: (lines) => {
const report = lines.reduce((report, line) => {
// 12/07/2017 10:23:52 - 19:22:36 08:58 / 08:07
let lineOfReport = line.match(/((\d{2})\/(\d{2})\/(\d{4})\s+\d{2}\:\d{2}\:\d{2}\s+\-\s+\d{2}\:\d{2}\:\d{2}\s+\d{2}\:\d{2}\s+\/\s+(\d{2})\:\d{2})/);
const day = lineOfReport[2];
const month = lineOfReport[3];
const year = lineOfReport[4];
const hours = lineOfReport[5];
report += lineOfReport[1];
dates.isHoliday(year, month, day)
? report += ' - Выходной\n'
: hours < 8
? report += ' - Сбой трекера\n'
: report += '\n';
return report;
}, '');
saveReportOnDisk(report);
return report;
}
};
}; |
//import warning from 'warning'
function deprecate(fn) {
return fn
//return function () {
// warning(false, '[history] ' + message)
// return fn.apply(this, arguments)
//}
}
export default deprecate
|
module.exports = {
init: function(app, bot, ftp, config) {
var base = config.BASE;
var passwords = config.PASSWORDS || ["password", "thissupersecurepasswordisneededtodosupersecretstuff", "916154e5dadca8295894fdc961d3ca4849f84eff27edf9913c4d688adf9ea6905875b637c8966e3b4154b2d70d7fe69f5ebabc4fccd085c002625c881ac2bdf5", "I4BywAZWHSXhib2BPMjvBaQ1S.HKY.eBNqArmDS66rYgpQ6cGO"];
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
for (let dir of fs.readdirSync(__dirname)) {
if((!/^.+\.js$/i.test(dir) && !/^.+\.disabled$/i.test(dir)) || (/^.+\.folder\.js$/i.test(dir) && !/^.+\.disabled$/i.test(dir))) {
require(path.join(__dirname, dir, "index.js")).init(app, bot, ftp, {
BASE: base + ((/^.+\.unstable$/i.test(dir)) ? "unstable/" : "") + dir.replace(/\.folder\.js$/i, ".js").replace(/\.unstable$/i, "") + "/",
PASSWORDS: passwords,
MISC: config.MISC
});
}
}
config.MISC.IO.of(base).on("connection", function(socket) {
let meta = _.times(10, v => String(Math.random() * 10).replace(/\./, "")).join``;
socket.emit("connected", {
meta: meta
});
socket.on("heartbeat", function(message) {
if (message.meta === meta) {
socket.emit("acknowledged", {
meta: message.meta
});
}
});
});
app.get(new RegExp("^" + _.escapeRegExp(base) + "{0}\\.?(?:(?:html?)|(?:pug)|(?:jade)|(?:txt))?$"), function(req, res) {
res.render("pages/heartbeat");
});
}
}; |
const BasicTypeTool = require('../basic-type-tool');
console.log(BasicTypeTool.isEven(16));
console.log(BasicTypeTool.countChar('adjlajdkfaldgjdsakjk', 'm'));
console.log(BasicTypeTool.trim(' \n hello world, we are happy \t \n ')); |
/**
* VIEW: Project
*
*/
var template = require('./templates/edit.hbs');
module.exports = Backbone.Marionette.ItemView.extend({
//--------------------------------------
//+ PUBLIC PROPERTIES / CONSTANTS
//--------------------------------------
className: "page-ctn project edition",
template: template,
ui: {
"title": "input[name=title]",
"description": "textarea[name=description]",
"link": "input[name=link]",
"tags": "input[name=tags]",
"status": "select[name=status]"
},
events: {
"click #ghImportBtn": "showGhImport",
"click #searchGh": "searchRepo",
"click #save": "save",
"click #cancel": "cancel"
},
templateHelpers: {
getTags: function(){
if (this.tags){
return this.tags.join(',');
}
},
statuses: function(){
return window.hackdash.statuses.split(",");
}
},
modelEvents: {
"change": "render"
},
//--------------------------------------
//+ INHERITED / OVERRIDES
//--------------------------------------
onShow: function(){
this.initSelect2();
this.initImageDrop();
},
//--------------------------------------
//+ PUBLIC METHODS / GETTERS / SETTERS
//--------------------------------------
//--------------------------------------
//+ EVENT HANDLERS
//--------------------------------------
showGhImport: function(e){
$(".gh-import", this.$el).removeClass('hide');
this.ui.description.css('margin-top', '30px');
e.preventDefault();
},
searchRepo: function(e){
var $repo = $("#txt-repo", this.$el),
$btn = $("#searchGh", this.$el),
repo = $repo.val();
$repo.removeClass('btn-danger');
$btn.button('loading');
if(repo.length) {
$.ajax({
url: 'https://api.github.com/repos/' + repo,
dataType: 'json',
contentType: 'json',
context: this
})
.done(this.fillGhProjectForm)
.error(function(){
$repo.addClass('btn-danger');
$btn.button('reset');
});
}
else {
$repo.addClass('btn-danger');
$btn.button('reset');
}
e.preventDefault();
},
save: function(){
var toSave = {
title: this.ui.title.val(),
description: this.ui.description.val(),
link: this.ui.link.val(),
tags: this.ui.tags.val().split(','),
status: this.ui.status.val(),
cover: this.model.get('cover')
};
this.cleanErrors();
$("#save", this.$el).button('loading');
this.model
.save(toSave, { patch: true, silent: true })
.success(this.redirect.bind(this))
.error(this.showError.bind(this));
},
cancel: function(){
this.redirect();
},
redirect: function(){
var url = "/dashboards/" + this.model.get('domain');
if (!this.model.isNew()){
url = "/projects/" + this.model.get('_id');
}
hackdash.app.router.navigate(url, { trigger: true, replace: true });
},
//--------------------------------------
//+ PRIVATE AND PROTECTED METHODS
//--------------------------------------
errors: {
"title_required": "Title is required",
"description_required": "Description is required"
},
showError: function(err){
$("#save", this.$el).button('reset');
if (err.responseText === "OK"){
this.redirect();
return;
}
var error = JSON.parse(err.responseText).error;
var ctrl = error.split("_")[0];
this.ui[ctrl].parents('.control-group').addClass('error');
this.ui[ctrl].after('<span class="help-inline">' + this.errors[error] + '</span>');
},
cleanErrors: function(){
$(".error", this.$el).removeClass("error");
$("span.help-inline", this.$el).remove();
},
initSelect2: function(){
if (this.model.get('status')){
this.ui.status.val(this.model.get('status'));
}
this.ui.status.select2({
minimumResultsForSearch: 10
});
$('a.select2-choice').attr('href', null);
this.ui.tags.select2({
tags:[],
formatNoMatches: function(){ return ''; },
maximumInputLength: 20,
tokenSeparators: [","]
});
},
initImageDrop: function(){
var self = this;
var $dragdrop = $('#dragdrop', this.$el);
var coverZone = new Dropzone("#dragdrop", {
url: hackdash.apiURL + '/projects/cover',
paramName: 'cover',
maxFiles: 1,
maxFilesize: 3, // MB
acceptedFiles: 'image/jpeg,image/png,image/gif',
uploadMultiple: false,
clickable: true,
dictDefaultMessage: 'Drop Image Here'
});
coverZone.on("complete", function(file) {
var url = JSON.parse(file.xhr.response).href;
self.model.set({ "cover": url }, { silent: true });
coverZone.removeFile(file);
$dragdrop
.css('background-image', 'url(' + url + ')');
$('.dz-message span', $dragdrop).css('opacity', '0.6');
});
},
fillGhProjectForm: function(project) {
this.ui.title.val(project.name);
this.ui.description.text(project.description);
this.ui.link.val(project.html_url);
this.ui.tags.select2("data", [{id: project.language, text:project.language}]);
this.ui.status.select2("val", "building");
$("#searchGh", this.$el).button('reset');
$("#txt-repo", this.$el).val('');
}
}); |
module.exports = function (grunt) {
// time
require('time-grunt')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Compress and zip only the files required for deployment to the server. Exclude all dev dependencies.
compress: {
main: {
options: {
archive: 'packaged/<%= pkg.name %>.zip'
},
expand: true,
cwd: '.',
src: [
'**/*',
'!**/node_modules/**',
'!**/components/**',
'!**/scss/**',
'!**/bower.json',
'!**/Gruntfile.js',
'!**/package.json',
'!**/composer.json',
'!**/composer.lock',
'!**/codesniffer.ruleset.xml'
],
dest: '<%= pkg.name %>'
},
},
sass: {
options: {
// If you can't get source maps to work, run the following command in your terminal:
// $ sass scss/foundation.scss:css/foundation.css --sourcemap
// (see this link for details: http://thesassway.com/intermediate/using-source-maps-with-sass )
sourceMap: true
},
dist: {
options: {
outputStyle: 'compressed'
},
files: {
'assets/stylesheets/foundation.css': 'assets/scss/foundation.scss'
}
}
},
copy: {
scripts: {
expand: true,
cwd: 'assets/components/foundation/js/vendor/',
src: '**',
flatten: 'true',
dest: 'assets/javascript/vendor/'
},
iconfonts: {
expand: true,
cwd: 'assets/components/fontawesome/fonts',
src: ['**'],
dest: 'assets/fonts/'
}
},
'string-replace': {
fontawesome: {
files: {
'assets/fontawesome/scss/_variables.scss': 'assets/fontawesome/scss/_variables.scss'
},
options: {
replacements: [
{
pattern: '../fonts',
replacement: '../assets/fonts'
}
]
}
}
},
concat: {
options: {
separator: ';'
},
dist: {
src: [
// Foundation core
'assets/components/foundation/js/foundation/foundation.js',
// Pick the components you need in your project
'assets/components/foundation/js/foundation/foundation.abide.js',
'assets/components/foundation/js/foundation/foundation.accordion.js',
'assets/components/foundation/js/foundation/foundation.alert.js',
'assets/components/foundation/js/foundation/foundation.clearing.js',
'assets/components/foundation/js/foundation/foundation.dropdown.js',
'assets/components/foundation/js/foundation/foundation.equalizer.js',
'assets/components/foundation/js/foundation/foundation.interchange.js',
'assets/components/foundation/js/foundation/foundation.joyride.js',
'assets/components/foundation/js/foundation/foundation.magellan.js',
'assets/components/foundation/js/foundation/foundation.offcanvas.js',
'assets/components/foundation/js/foundation/foundation.orbit.js',
'assets/components/foundation/js/foundation/foundation.reveal.js',
'assets/components/foundation/js/foundation/foundation.slider.js',
'assets/components/foundation/js/foundation/foundation.tab.js',
'assets/components/foundation/js/foundation/foundation.tooltip.js',
'assets/components/foundation/js/foundation/foundation.topbar.js',
// Include your own custom scripts (located in the custom folder)
'assets/javascript/custom/*.js'
],
// Finally, concatenate all the files above into one single file
dest: 'assets/javascript/foundation.js'
}
},
uglify: {
dist: {
files: {
// Shrink the file size by removing spaces
'assets/javascript/foundation.js': ['assets/javascript/foundation.js']
}
}
},
watch: {
grunt: {files: ['Gruntfile.js']},
sass: {
files: 'assets/scss/**/*.scss',
tasks: ['sass'],
options: {
livereload: true
}
},
js: {
files: 'assets/javascript/custom/**/*.js',
tasks: ['concat', 'uglify'],
options: {
livereload: true
}
},
all: {
files: '**/*.php',
options: {
livereload: true
}
}
},
browserSync: {
dev: {
bsFiles: {
src : [
'assets/stylesheets/*.css',
'**/*.php',
'assets/javascript/**/*.js'
]
},
options: {
watchTask: true,
// fill in proxy address of local WP server
proxy: "http://localhost/wordpress/"
}
}
}
});
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-string-replace');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-browser-sync');
grunt.registerTask('package', ['compress:main']);
grunt.registerTask('build', ['copy', 'string-replace:fontawesome', 'sass', 'concat', 'uglify']);
grunt.registerTask('browser-sync', ['browserSync', 'watch']);
grunt.registerTask('default', ['watch']);
};
|
import EmberRouter from '@ember/routing/router';
import config from 'dummy/config/environment';
export default class Router extends EmberRouter {
location = config.locationType;
rootURL = config.rootURL;
}
Router.map(function () {
this.route('gettingstarted');
this.route('simple');
this.route('async');
this.route('hoveredactions');
this.route('expand');
this.route('multiselection');
this.route('noderefresh');
});
|
// flow-typed signature: de185c5c79662f63582bcd30ef7ba011
// flow-typed version: <<STUB>>/bugsnag-sourcemaps_v1.0.3/flow_v0.65.0
/**
* This is an autogenerated libdef stub for:
*
* 'bugsnag-sourcemaps'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'bugsnag-sourcemaps' {
declare module.exports: any;
}
|
'use strict'
const u = require('./util')
function toArray (str) {
return Array.isArray(str) ? str : str.split('.')
}
function isPerms (p) {
return (
p &&
typeof p.pre === 'function' &&
typeof p.test === 'function' &&
typeof p.post === 'function'
)
}
/*
perms:
a given capability may be permitted to call a particular api.
but only if a perms function returns true for the arguments
it passes.
suppose, an app may be given access, but may only create functions
with it's own properties.
create perms:
{
allow: ['add', 'query'], deny: [...],
rules: {
add: {
call: function (value) {
return (value.type === 'task' || value.type === '_task')
},
query: {
call: function (value) {
safe.contains(value, {path: ['content', 'type'], eq: 'task'}) ||
safe.contains(value, {path: ['content', 'type'], eq: '_task'})
},
filter: function (value) {
return (value.type === 'task' || value.type === '_task')
}
}
}
}
*/
module.exports = function Permissions (opts) {
if (isPerms(opts)) return opts
if (typeof opts === 'function') return { pre: opts }
let allow = null
let deny = {}
function perms (opts) {
if (opts.allow) {
allow = {}
for (const path of opts.allow) {
u.set(allow, toArray(path), true)
}
} else {
allow = null
}
if (opts.deny) {
for (const path of opts.deny) {
u.set(deny, toArray(path), true)
}
} else {
deny = {}
}
return this
}
if (opts) perms(opts)
perms.pre = (name) => {
name = Array.isArray(name) ? name : [name]
if (allow && !u.prefix(allow, name)) {
return new Error(`method:${name} is not in list of allowed methods`)
}
if (deny && u.prefix(deny, name)) {
return new Error(`method:${name} is on list of disallowed methods`)
}
}
perms.post = () => {
// TODO
}
// alias for pre, used in tests.
perms.test = (name) => perms.pre(name)
perms.get = () => ({ allow, deny })
return perms
}
|
!function($) {
'use strict';
var TypeaheadMultiple = {
select: function () {
var element = this.$element[0];
var val = this.$menu.find('.active').attr('data-value');
var offset = val.length - this.length_of_query;
var position = getCaretPosition(element) + offset;
if (this.autoSelect || val) {
this.$element
.val(this.updater(val))
.change();
}
setCaretPosition(element, position);
$(element).trigger('input');
return this.hide();
},
updater: function(item) {
var caretPos = getCaretPosition(this.$element[0]);
// Is user typing at end of textbox?
if (caretPos === this.query.length) {
// User is typing at end of textbox, just append the item
return this.$element.val().replace(/[^\W]*$/,'')+item;
}
else {
// Find and remove user's input, then insert the item
var queryBeforeCarat = this.query.substring(0, caretPos);
var lastNonAlphanumeric = doLastNonAlphaNumericCharRegEx(queryBeforeCarat);
var inputToReplace;
if (lastNonAlphanumeric) {
inputToReplace = queryBeforeCarat.substring(lastNonAlphanumeric.index + 1);
var startPosOfUserInput = caretPos - inputToReplace.length;
return this.query.substring(0, startPosOfUserInput) + item + this.query.substring(caretPos);
}
else {
// User was typing at beginning of box, just insert at beginning
return item + this.query.substring(caretPos);
}
}
},
matcher: function (item) {
var usersCurrentQuery = '';
var caretPos = getCaretPosition(this.$element[0]);
// Is user typing at end of textbox?
if (caretPos === this.query.length) {
usersCurrentQuery = extractUserInputAtTextBoxEnd(this.query);
}
else {
// The user's current input is between the caret and the last non-alphanumeric char before it
var queryBeforeCarat = this.query.substring(0, caretPos);
var lastNonAlphanumeric = doLastNonAlphaNumericCharRegEx(queryBeforeCarat);
if (lastNonAlphanumeric) {
usersCurrentQuery = queryBeforeCarat.substring(lastNonAlphanumeric.index + 1);
}
else {
// If there are no non-alphanumerics before the carat, they started typing
// at the beginning of the textbox and we just evaluate up to the caret
usersCurrentQuery = queryBeforeCarat;
}
}
if (!usersCurrentQuery) {
return false;
}
this.length_of_query = usersCurrentQuery.length;
return !item.toLowerCase().indexOf(usersCurrentQuery.toLowerCase());
},
highlighter: function (item) {
var query = extractUserInputAtTextBoxEnd(this.query);
query = query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
});
}
};
function doLastNonAlphaNumericCharRegEx(query) {
return (/\W(?!.*\W)/).exec(query);
}
function extractUserInputAtTextBoxEnd(query) {
var result = /([^\W]+)$/.exec(query);
if (result && result[1]) {
return result[1].trim();
}
return '';
}
function getCaretPosition(element) {
if (element.selectionStart) {
return element.selectionStart;
} else if (document.selection) {
element.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = element.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
function setCaretPosition(element, caretPos) {
if (element != null) {
if (element.createTextRange) {
var range = element.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if (element.selectionStart) {
element.focus();
element.setSelectionRange(caretPos, caretPos);
}
else {
element.focus();
}
}
}
}
$.extend($.fn.typeahead.Constructor.prototype, TypeaheadMultiple);
}(window.jQuery);
|
// updated 1/12/17, passed testing
(function () {
'use strict';
angular
.module('root')
.factory('UtilityFactory', function($mdToast, $filter, UtilityService, Gparams) {
var _family;
return {
/* public functions */
getTodayInHistory: function() {
/* DatabaseService.getHistoryFact()
.then(function successCallback(response) {
var blurb;
var content;
var whichOne;
var tmp;
try {
if (response.status==200) {
blurb = $('#infoDetail').html(response.data.parse.text["*"]);
blurb.find('a').each(function() { $(this).replaceWith($(this).html()); }); // remove links as they will not work
blurb.find('sup').remove(); // remove any references
blurb.find('.mw-ext-cite-error').remove(); // remove cite error
content = $('#infoDetail').html().split("<ul>");
content.unshift();
$('#infoDetail').html(content);
content = $('#infoDetail').html().split("<li>");
whichOne = Math.floor((Math.random() * content.length) + 1);
tmp = content[whichOne].replace("</li>","");
$('#article1').html("On this date in "+tmp);
$('#infoDetail').html(" ");
} else {
$('#article1').html("<p>An error occured while retrieving 'Today In History' from Wikipedia.</p>");
}
} catch(err) {
$('#article1').html('</p>The Wikipedia "today in history" is unavailable.</p>')
}
});
/* },
getNameHistory: function(theName) {
/* DatabaseService.getNameFact(theName)
.then(function successCallback(response) {
var blurb;
var content;
var def;
var tmp;
try {
if (response.status==200) {
blurb = $('#nameDetail').html(response.data.parse.text["*"]);
blurb.find('div').remove();
blurb.find('h2').remove();
blurb.find('table').remove();
blurb.find('a').each(function() { $(this).replaceWith($(this).html()); }); // remove links as they will not work
ontent = $('#nameDetail').html().split("<ul>");
content.unshift();
$('#nameDetail').html(content);
content = $('#nameDetail').html().split("<li>");
def = $('#nameDetail p').detach().text();
tmp = def.split(".");
tmp.pop();
$('#article2').append(tmp);
tmp = $('#nameDetail').text();
tmp = tmp.replace(/(\r\n|\r|\n){2,}/g, '$1<br />'); // replace multiple \n
tmp = tmp.replace(/(\r\n|\r|\n)/g, '$1<br />'); // replace multiple \n
tmp = 'The following notable people are named Johnson:' + tmp;
$('#myDialogContent').html(tmp);
} else {
$('#infoDetail').html("<p>An error occured while retrieving the 'Name History' from Wikipedia.</p>");
}
} catch(err) {
$('#infoDetail').html('</p>The Wikipedia "name history" is unavailable.</p>')
}
});
*/ },
setFamily: function(id) {
return UtilityService.getFamily(parseInt(id))
.then(function successCallback(response) {
_family = response;
return response;
});
},
getFamily: function() {
return _family;
},
showTemplateToast: function(template) {
$mdToast.show({
template : template,
position : 'top right',
hideDelay : 3000,
parent : $('#toastLocation')
});
},
showAlertToast: function(template) {
$mdToast.show({
template : template,
position : 'top left',
hideDelay : 3000,
toastClass : 'md-error-toast-theme',
parent : $('#toastLocation')
});
},
formatDates: function(theDate) {
var exports;
var tmp;
if(theDate != '0000-00-00') {
tmp = $filter('date')(theDate, 'MMMM dd, yyyy');
} else {
tmp = '';
}
exports.theDate = tmp;
return exports.theDate;
},
getLength: function(obj) {
var exports = 0;
var o;
for (o in obj) {exports++;}
return exports;
},
getBirthInfo: function () {
city = 'Paris'; // get lat and lng of 'city'
var geocoder =new google.maps.Geocoder();
geocoder.geocode( { 'address': city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something went wrong " + status);
}
});
},
between: function(a,b,val) {
if(val>=a && val<=b ) return true;
return false;
}
};
// Private Functions
/* possible future features:
https://en.wikipedia.org/wiki/Category:People_from_Muskegon,_Michigan
weather
lat/long
map
*/
});
})(); |
var wechat = require('wechat-enterprise'),
api = new wechat.API($.config.enterprise.corpId, $.config.enterprise.corpsecret,$.config.agentid),
async = $.async,
util = require('util'),
redis = $.plug.redis.redisserver;
var KEY = {
USER : 'users:%s',
Reg: 'user_reg:%s',
Table: 'user_table:%s'
};
/*
* 获取已签到人员的信息
*/
exports.getreguserlist = function(req, res) {
var data = [];
redis.keys(util.format(KEY.USER,"*"), function (err, replies) {
async.each(replies, (userid, rcallback) => {
redis.hgetall(userid, (err, result) => {
if(parseInt(result.issign)==1){
data.push(result);
}
rcallback();
});
}, function (err){
res.send(data);
});
});
};
/*
* 获取已签到人员的信息(抽奖页面专用 排除了一些人)
*/
exports.getlotteryuserlist = function(req, res) {
var array1 = [];
var data = [];
async.waterfall([
// 记录所有的人的userid
function(cb){
redis.keys(util.format(KEY.USER,"*"), function (err, replies) {
array1 = replies;
cb();
})
},
// 将已排除人员的名单 作为临时数组的key值
function(cb){
var tempArray1 = [];
var array2 = $.config.excludedpeople;
async.each(array2, (userid, rcallback) => {
tempArray1[userid]=true;//将数array2 中的元素值作为tempArray1 中的键,值为true
rcallback();
}, function (err){
cb(null,tempArray1);
});
},
// 从所有人员的userid中剔除已排除人员
function(tempArray1, cb){
var tempArray2 = [];
async.each(array1, (userid, rcallback) => {
if(!tempArray1[userid]){
tempArray2.push(userid);//过滤array1 中与array2 相同的元素;
}
rcallback();
}, function (err){
cb(null,tempArray2);
});
},
// 查询剩余的userid 中已经签到的人的信息
function(tempArray2, cb){
async.each(tempArray2, (userid, rcallback) => {
redis.hgetall(userid, (err, result) => {
if(parseInt(result.issign)==1){
data.push(result);
}
rcallback();
});
}, function (err){
cb(null,data);
});
}],function(error, data){
if(error) return res.send({errcode:1, retults: error });
res.send({errcode:0, data: data });
}
);
};
/*
* 重新拉取用户数据
*/
exports.getfetchallusers =function (req, res){
var x=1;
api.getDepartmentUsersDetail(1, 1, 1, (err, data)=>{
async.each(data.userlist,(user, rcallback) => {
api.getUserOpenId({"userid": user.userid,"agentid":41},(err,reply)=>{
$.extend(user, {
//table: 0,
//issign:0,
isaward:0,
openid: reply.openid,
appid:reply.appid,
num:x++,
//增加字段 记录哪个页面中奖了 不能重复在一个活动中中奖 0代表未中奖 1 代表已中奖
headaward:0,
luckyaward:0,
chataward:0,
awardofchen:0,
awardofzhu:0
})
user.department = JSON.stringify(user.department);
//保存数据
redis.hmset(util.format(KEY.USER,user.userid), user, (err, result) => {
rcallback();
});
});
},(err) => {
res.send({errCode:0});
});
});
};
/*
* 签到重置
*/
exports.postresetuser = function(req, res) {
var key = util.format(KEY.USER,req.body.UserId );
redis.hgetall(key, (err, user)=>{
$.extend(user, {
issign: 0
});
redis.hmset(key, user, (err, data) => {
res.send({errCode:0,issign:0});
});
});
};
/*
* 修改全部人员签到信息
*/
exports.postisAllSignup = function(req, res) {
var issign = req.body.issign;
redis.keys(util.format(KEY.USER,"*"), function (err, replies) {
async.each(replies, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
$.extend(user, {
issign: issign
});
redis.hmset(userid, user, (err, data) => {});
});
rcallback();
}, function (err){
res.send({errCode:0});
});
});
// res.send({errCode:0});
};
/*
* 修改信息
*/
exports.postresetuserinfo = function(req, res) {
var key = util.format(KEY.USER,req.body.UserId);
var _table = req.body.table;
var department = req.body.department;
if(department == ''){
redis.hgetall(key, (err, user)=>{
$.extend(user, {
table: _table
});
redis.hmset(key, user, (err, data) => {
res.send(_table);
});
});
}
else {
var i = 1;
var data = {};
data.items = [];
redis.keys(util.format(KEY.USER,"*"), function (err, data) {
var item = [];
async.each(data, (userid, rcallback) => {
redis.hgetall(userid, (err, _user) => {
if("[{0}]".format(department) ==_user.department){
$.extend(_user,{
table: _table
});
redis.hmset(util.format(KEY.USER,_user.userid), _user, (err, data) => {});
}
});
rcallback();
}, function (err){
res.send({errCode:0});
});
});
}
};
/*
* 按照条件查找users
*/
exports.postselectUsers = function(req, res) {
var _table = req.body.table;
var _department = req.body.department;
var _issign = req.body.issign;
var _data = {};
_data.items = [];
var i=1;
// 获取到所有user 的数据
var tempData = {};
redis.keys(util.format(KEY.USER, "*"), function (err, result) {
tempData = result;
//如果查询条件全部为空的话 返回所有的数据
if(_table == '' && _department == '' && _issign ==''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
$.extend(user,{
num: i++
});
_data.items.push(user);
rcallback();
});
}, function (err){
res.send(_data);
});
}
// 只查桌号的 人员信息
else if(_table != '' && _department == '' && _issign ==''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
if(user.table == _table){
$.extend(user,{
num: i++
});
_data.items.push(user);
}
rcallback();
});
}, function (err){
res.send(_data);
});
}
//只查部门的人员信息
else if(_table == '' && _department != '' && _issign ==''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
if(user.department == "[{0}]".format(_department)){
$.extend(user,{
num: i++
});
_data.items.push(user);
}
rcallback();
});
}, function (err){
res.send(_data);
});
}
//只查寻签到情况的人员信息
else if(_table == '' && _department == '' && _issign !=''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
if(user.issign == _issign){
$.extend(user,{
num: i++
});
_data.items.push(user);
}
rcallback();
});
}, function (err){
res.send(_data);
});
}
//查询部门和桌号的信息
else if(_table != '' && _department != '' && _issign ==''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
if(user.table == _table && user.department =="[{0}]".format(_department)){
$.extend(user,{
num: i++
});
_data.items.push(user);
}
rcallback();
});
}, function (err){
res.send(_data);
});
}
// 查询桌号和部门情况的人员信息
else if(_table != '' && _department == '' && _issign !=''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
if(user.table == _table && user.issign == _issign){
$.extend(user,{
num: i++
});
_data.items.push(user);
}
rcallback();
});
}, function (err){
res.send(_data);
});
}
// 查询部门和签到情况的人员信息
else if(_table == '' && _department != '' && _issign !=''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
if(user.department == "[{0}]".format(_department) && user.issign == _issign){
$.extend(user,{
num: i++
});
_data.items.push(user);
}
rcallback();
});
}, function (err){
res.send(_data);
});
}
// 查询 桌号, 部门 和签到情况的人员信息
else if(_table != '' && _department != '' && _issign !=''){
async.each(tempData, (userid, rcallback) => {
redis.hgetall(userid, (err, user) => {
if(user.table == _table && user.department == "[{0}]".format(_department) && user.issign == _issign){
$.extend(user,{
num: i++
});
_data.items.push(user);
}
rcallback();
});
}, function (err){
res.send(_data);
});
}
})
};
/*
* 抽奖页面 记录中奖人员的信息
*/
exports.postrecordpeopleOfaward = function(req,res){
var body = {
userid : req.body.userid,
username : req.body.username,
AwardsID:req.body.AwardsID ,
department : req.body.department,
imgsrc:req.body.imgsrc,
awardimg:req.body.awardimg,
awardsname:req.body.awardsname,
prizename:req.body.prizename,
};
var id_ = parseInt(req.body.AwardsID);
redis.hgetall("award:{0}".format(id_), (err, result) => {
var _DrawedNumber = parseInt(result.DrawedNumber);
var _Number = parseInt(result.Number);
var status = parseInt(result.Status);
if(_DrawedNumber < _Number){
//记录中奖人员的信息
redis.keys("luckyaward:*",(err, data)=>{
redis.hgetall("luckyaward:{0}".format(data.length),(err, reply)=>{
if(reply == null || reply == ''){
$.extend(body,{
"luckid": 1
})
redis.hmset("luckyaward:{0}".format(1), body, (err, data) => {});
}else{
var _luckid = parseInt(reply.luckid)+1;
$.extend(body,{
"luckid": _luckid
})
redis.hmset("luckyaward:{0}".format(_luckid), body, (err, data) => {});
}
})
})
// 改变被抽中的奖品数量
result.DrawedNumber = _DrawedNumber +1;
if((_DrawedNumber +1) == _Number){
result.Status = 0;
}
redis.hmset(util.format(KEY.USER,req.body.userid ), {luckyaward:1}, (err, data) => {});
redis.hmset("award:{0}".format(id_), result, (err, data) => {
res.send({AwardsID:id_ , DrawedNumber:_DrawedNumber,status:status,msg:"恭喜中奖!"});
});
}
else{
status = 0;
result.Status = 0;
redis.hmset("award:{0}".format(id_), result, (err, data) => {
res.send({AwardsID:id_,DrawedNumber:_DrawedNumber,status:status,msg:"奖品已经抽完!"});
});
}
});
};
/*
* 获取 抽奖页面的 奖品的方法
*/
exports.getawardlist = function(req,res){
var arr = [];
var arr1 = [];
var arr2 = [];
var arr3 = [];
redis.keys("award:*",function (err,replies){
async.each(replies, (userid, rcallback) => {
redis.hgetall(userid, (err, result) => {
if(parseInt(result.AwardsLevel)==1){
arr1.push(result);
}
else if(parseInt(result.AwardsLevel)==2){
arr2.push(result);
}
else if(parseInt(result.AwardsLevel)==3){
arr3.push(result);
}
rcallback();
});
},function (err){
var a = arr.concat(arr1);
var b = a.concat(arr2);
var c = b.concat(arr3);
res.send(c);
});
})
};
/*
* 获取中奖人员的列表
*/
exports.getfetchallawardpelple = function(req, res) {
var arr = [];
var arr1 = [];
var arr2 = [];
var arr3 = [];
redis.keys("luckyaward:*",function (err,replies){
async.each(replies, (userid, rcallback) => {
redis.hgetall(userid, (err, result) => {
if(result.AwardsID == 1){
arr1.push(result);
}
else if(result.AwardsID == 2){
arr2.push(result);
}
else{
arr3.push(result);
}
rcallback();
});
},function (err){
var a = arr.concat(arr1);
var b = a.concat(arr2);
var c = b.concat(arr3);
res.send(c);
});
})
};
|
/*!
* c2-event-handler
* https://github.com/TheC2Group/event-handler
* @version 2.5.2 (c) The C2 Group (c2experience.com)
* @license MIT
*/
var eventHandler = (function () { 'use strict';
var on = function (event, fn) {
var _this = this;
if (typeof event !== 'string' || !event.length || typeof fn === 'undefined') return;
if (event.indexOf(' ') > -1) {
event.split(' ').forEach(function (eventName) {
on.call(_this, eventName, fn);
});
return;
}
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(fn);
};
var off = function (event, fn) {
var _this2 = this;
if (typeof event !== 'string' || !event.length) return;
if (event.indexOf(' ') > -1) {
event.split(' ').forEach(function (eventName) {
off.call(_this2, eventName, fn);
});
return;
}
this._events = this._events || {};
if (event in this._events === false) return;
if (typeof fn === 'undefined') {
delete this._events[event];
return;
}
var index = this._events[event].indexOf(fn);
if (index > -1) {
if (this._events[event].length === 1) {
delete this._events[event];
} else {
this._events[event].splice(index, 1);
}
}
};
var emit = function (event) {
var _this3 = this;
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var lastIndex = event.lastIndexOf(':');
if (lastIndex > -1) {
emit.call.apply(emit, [this, event.substring(0, lastIndex)].concat(args));
}
this._events = this._events || {};
if (event in this._events === false) return;
this._events[event].forEach(function (fn) {
fn.apply(_this3, args);
});
};
var EventConstructor = function () {};
var proto = EventConstructor.prototype;
proto.on = on;
proto.off = off;
proto.emit = emit;
// legacy extensions
proto.bind = on;
proto.unbind = off;
proto.trigger = emit;
var handler = function (_class) {
// constructor
if (arguments.length === 0) {
return new EventConstructor();
}
// mixin
if (typeof _class === 'function') {
_class.prototype.on = on;
_class.prototype.off = off;
_class.prototype.emit = emit;
}
if (typeof _class === 'object') {
_class.on = on;
_class.off = off;
_class.emit = emit;
}
return _class;
};
handler.EventConstructor = EventConstructor;
return handler;
})(); |
QUnit.module( "Performance", { setup: require('./setup/setup').reset } );
QUnit.test( "Creation and destruction", 0, function() {
var registerCount = 0,
unregisterCount = 0,
register = Backbone.Store.prototype.register,
unregister = Backbone.Store.prototype.unregister;
Backbone.Store.prototype.register = function( model ) {
registerCount++;
return register.apply( this, arguments );
};
Backbone.Store.prototype.unregister = function( model, coll, options ) {
unregisterCount++;
return unregister.apply( this, arguments );
};
var addHasManyCount = 0,
addHasOneCount = 0,
tryAddRelatedHasMany = Backbone.HasMany.prototype.tryAddRelated,
tryAddRelatedHasOne = Backbone.HasOne.prototype.tryAddRelated;
Backbone.Store.prototype.tryAddRelated = function( model, coll, options ) {
addHasManyCount++;
return tryAddRelatedHasMany.apply( this, arguments );
};
Backbone.HasOne.prototype.tryAddRelated = function( model, coll, options ) {
addHasOneCount++;
return tryAddRelatedHasOne.apply( this, arguments );
};
var removeHasManyCount = 0,
removeHasOneCount = 0,
removeRelatedHasMany = Backbone.HasMany.prototype.removeRelated,
removeRelatedHasOne= Backbone.HasOne.prototype.removeRelated;
Backbone.HasMany.prototype.removeRelated = function( model, coll, options ) {
removeHasManyCount++;
return removeRelatedHasMany.apply( this, arguments );
};
Backbone.HasOne.prototype.removeRelated = function( model, coll, options ) {
removeHasOneCount++;
return removeRelatedHasOne.apply( this, arguments );
};
var Child = Backbone.RelationalModel.extend({
url: '/child/',
toString: function() {
return this.id;
}
});
var Parent = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'children',
relatedModel: Child,
reverseRelation: {
key: 'parent'
}
}],
toString: function() {
return this.get( 'name' );
}
});
var Parents = Backbone.Collection.extend({
model: Parent
});
// bootstrap data
var data = [];
for ( var i = 1; i <= 300; i++ ) {
data.push({
name: 'parent-' + i,
children: [
{id: 'p-' + i + '-c1', name: 'child-1'},
{id: 'p-' + i + '-c2', name: 'child-2'},
{id: 'p-' + i + '-c3', name: 'child-3'}
]
});
}
/**
* Test 2
*/
Backbone.Relational.store.reset();
addHasManyCount = addHasOneCount = 0;
console.log('loading test 2...');
var start = new Date();
var preparedData = _.map( data, function( item ) {
item = _.clone( item );
item.children = item.children.map( function( child ) {
return new Child( child );
});
return item;
});
var parents = new Parents();
parents.on('reset', function () {
var secs = (new Date() - start) / 1000;
console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount );
});
parents.reset( preparedData );
//_.invoke( _.clone( parents.models ), 'destroy' );
/**
* Test 1
*/
Backbone.Relational.store.reset();
addHasManyCount = addHasOneCount = 0;
console.log('loading test 1...');
var start = new Date();
var parents = new Parents();
parents.on('reset', function () {
var secs = (new Date() - start) / 1000;
console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount );
});
parents.reset( data );
//_.invoke( _.clone( parents.models ), 'destroy' );
/**
* Test 2 (again)
*/
Backbone.Relational.store.reset();
addHasManyCount = addHasOneCount = removeHasManyCount = removeHasOneCount = 0;
console.log('loading test 2...');
var start = new Date();
var parents = new Parents();
parents.on('reset', function () {
var secs = (new Date() - start) / 1000;
console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount );
});
parents.reset( preparedData );
start = new Date();
parents.each( function( parent ) {
var children = _.clone( parent.get( 'children' ).models );
_.each( children, function( child ) {
child.destroy();
});
});
var secs = (new Date() - start) / 1000;
console.log( 'data loaded in %s, removeHasManyCount=%o, removeHasOneCount=%o', secs, removeHasManyCount, removeHasOneCount );
//_.invoke( _.clone( parents.models ), 'destroy' );
/**
* Test 1 (again)
*/
Backbone.Relational.store.reset();
addHasManyCount = addHasOneCount = removeHasManyCount = removeHasOneCount = 0;
console.log('loading test 1...');
var start = new Date();
var parents = new Parents();
parents.on('reset', function () {
var secs = (new Date() - start) / 1000;
console.log( 'data loaded in %s, addHasManyCount=%o, addHasOneCount=%o', secs, addHasManyCount, addHasOneCount );
});
parents.reset(data);
start = new Date();
parents.remove( parents.models );
var secs = (new Date() - start) / 1000;
console.log( 'data removed in %s, removeHasManyCount=%o, removeHasOneCount=%o', secs, removeHasManyCount, removeHasOneCount );
console.log( 'registerCount=%o, unregisterCount=%o', registerCount, unregisterCount );
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pip_services3_data_node_1 = require("pip-services3-data-node");
const PasswordsMemoryPersistence_1 = require("./PasswordsMemoryPersistence");
class PasswordsFilePersistence extends PasswordsMemoryPersistence_1.PasswordsMemoryPersistence {
constructor(path) {
super();
this._persister = new pip_services3_data_node_1.JsonFilePersister(path);
this._loader = this._persister;
this._saver = this._persister;
}
configure(config) {
super.configure(config);
this._persister.configure(config);
}
}
exports.PasswordsFilePersistence = PasswordsFilePersistence;
//# sourceMappingURL=PasswordsFilePersistence.js.map |
import Ember from 'ember';
export default Ember.Mixin.create({
token: Ember.computed.alias('accessTokenWrapper.token'),
headers: Ember.computed('token', function() {
return {
"AUTHORIZATION": 'Bearer ' + this.get('token')
};
})
});
|
$(document).ready(function () {
//Bind our data structure
var groceryList = {
title: "Grocery List",
items: []
};
//to our HTML
Shibari.bind($('.grocery-list').get(0), groceryList);
//And then just operate off the data structure ( nothing fancy yah? :) )
function createNewItem() {
var v = $('.input-new-item').val();
if (v.trim() != "") {
groceryList.items.push({name: $('.input-new-item').val(), id: Math.random()});
$('.input-new-item').val('')
$('.input-new-item').focus();
}
}
function removeItem(id) {
for (var i = 0; i < groceryList.items.length; i++) {
if (groceryList.items[i].id == id) {
groceryList.items.splice(i, 1);
return;
}
}
};
$('.button-add-new').click(function () {
createNewItem();
});
$('.input-new-item').keydown(function (e) {
//if we hit enter
if (e.keyCode == 13) {
createNewItem();
}
});
$('.grocery-list').mouseup(function (e) {
//if we mouse up off a close button
if ($(e.target).hasClass("item-close")) {
removeItem($(e.target).attr("data-id"));
}
});
//focus on input for instant typing
$('.input-new-item').focus();
}); |
// TODO: error when reachable but not connected
const events = require('events');
const hat = require('hat');
const merge = require('merge');
const winston = require('winston');
const winstonWrapper = require('winston-meta-wrapper');
/**
* UDP hole puncher
*
* @constructor
* @fires UdpHolePuncher#reachable
* @fires UdpHolePuncher#connected
* @fires UdpHolePuncher#timeout
* @fires UdpHolePuncher#error
*/
class UdpHolePuncher extends events.EventEmitter {
constructor(socket, args) {
super();
// logging
this.log = winstonWrapper(winston);
this.log.addMeta({
module: 'udp-hole-puncher',
});
// check if socket is defined
if (socket === undefined) {
const errorMsg = 'udp socket is undefined';
this.log.error(errorMsg);
throw new Error(errorMsg);
}
// merge args with defaults
const margs = merge(Object.create(UdpHolePuncher.DEFAULTS), args);
// init
this.id = hat();
this.attempts = margs.maxRequestAttempts;
this.timeout = margs.requestTimeout;
this.socket = socket;
this.initSocket();
// done
this.log.addMeta({
id: this.id,
});
this.log.debug('init complete');
}
/** Connect and close */
connect(addr, port) {
this.sendRequestInterval = setInterval(() => {
if (this.attempts > 0) {
this.attempts -= 1;
this.sendRequest(addr, port);
} else {
this.log.error(`failed to connect with ${addr}:${port}`);
clearInterval(this.sendRequestInterval);
this.restoreSocket();
this.emit('timeout');
}
}, this.timeout);
}
close() {
if (this.sendRequestInterval) {
clearInterval(this.sendRequestInterval);
}
this.restoreSocket();
}
/** Outgoing messages */
sendRequest(addr, port) {
const message = this.composeRequest(this.id);
this.socket.send(message, 0, message.length, port, addr);
this.log.debug(`sent request ${this.id} to ${addr}:${port}`);
}
sendAck(addr, port) {
const message = this.composeAck(this.remoteId);
this.socket.send(message, 0, message.length, port, addr);
this.log.debug(`sent ack ${this.remoteId} to ${addr}:${port}`);
}
/** Incoming message */
onMessage() {
return (bytes, rinfo) => {
this.log.debug(`receiving message from ${JSON.stringify(rinfo)}`);
const type = bytes.readUInt16BE(0);
switch (type) {
case UdpHolePuncher.PACKET.REQUEST:
this.onRequest(bytes.slice(2), rinfo);
break;
case UdpHolePuncher.PACKET.ACK:
this.onAck(bytes.slice(2), rinfo);
break;
default:
this.onRegularMessage(bytes, rinfo);
}
};
}
onRequest(bytes, rinfo) {
const id = bytes.toString();
this.log.debug(`receiving remote token ${id} from ${rinfo.address}:${rinfo.port}`);
this.remoteId = id;
this.receivingMessages = true;
this.sendAck(rinfo.address, rinfo.port);
this.emit('reachable');
this.verifyConnection();
}
onAck(bytes, rinfo) {
const ackId = bytes.toString();
this.log.debug(`receiving ack with token ${ackId} from ${rinfo.address}:${rinfo.port}`);
if (ackId !== this.id) {
this.log.debug('ack contains incorrect id, dropping on the floor');
return;
}
this.messageDeliveryConfirmed = true;
clearInterval(this.sendRequestInterval);
this.verifyConnection();
}
onRegularMessage(bytes, rinfo) {
this.log.debug('receiving regular message while establishing a connection');
// forward to original message listeners
this.messageListeners.forEach((callback) => {
callback(bytes, rinfo);
});
}
verifyConnection() {
if (this.receivingMessages && this.messageDeliveryConfirmed) {
this.log.debug('bi-directional connection established');
this.restoreSocket();
this.emit('connected');
}
}
/** Message composition */
composeRequest(id) {
this.log.debug(`composing request message with id ${id}`);
// type
const typeBytes = new Buffer(2);
typeBytes.writeUInt16BE(UdpHolePuncher.PACKET.REQUEST);
// value
const valueBytes = new Buffer(id);
// combination
const result = Buffer.concat([typeBytes, valueBytes]);
// done
return result;
}
composeAck(id) {
this.log.debug(`composing ack message with id ${id}`);
// type
const typeBytes = new Buffer(2);
typeBytes.writeUInt16BE(UdpHolePuncher.PACKET.ACK);
// value
const valueBytes = new Buffer(id);
// combination
const result = Buffer.concat([typeBytes, valueBytes]);
// done
return result;
}
/** Socket errors */
// Error handler
onFailure() {
return (error) => {
const errorMsg = `socket error: ${error}`;
this.log.error(errorMsg);
this.emit('error', error);
throw new Error(errorMsg);
};
}
/** Socket config */
initSocket() {
// store original message and error listeners, if any
this.messageListeners = this.socket.listeners('message');
this.errorListeners = this.socket.listeners('error');
// temp remove these listeners ...
this.messageListeners.forEach((callback) => {
this.socket.removeListener('message', callback);
});
this.errorListeners.forEach((callback) => {
this.socket.removeListener('error', callback);
});
// ... and put my handlers in place
this.socket.on('message', this.onMessage());
this.socket.on('error', this.onFailure());
}
restoreSocket() {
// remove my listeners
this.socket.listeners('message').forEach((callback) => {
this.socket.removeListener('message', callback);
});
this.socket.listeners('error').forEach((callback) => {
this.socket.removeListener('error', callback);
});
// restore the original listeners
this.messageListeners.forEach((callback) => {
this.socket.on('message', callback);
});
this.errorListeners.forEach((callback) => {
this.socket.on('error', callback);
});
// and remove refs to these original listeners
this.messageListeners = [];
this.errorListeners = [];
}
}
UdpHolePuncher.DEFAULTS = {
maxRequestAttempts: 10,
requestTimeout: 500,
};
UdpHolePuncher.PACKET = {
REQUEST: 0x9000,
ACK: 0x9001,
};
module.exports = UdpHolePuncher;
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["require","exports","../../../../core/tsSupport/extendsHelper","../../../input/InputHandler"],function(o,n,e,t){Object.defineProperty(n,"__esModule",{value:!0});var i;!function(o){o[o.IN=0]="IN",o[o.OUT=1]="OUT"}(i||(i={}));var r=function(o){function n(n,e,t){var r=o.call(this,"esri.views.2d.input.handlers.KeyZoom",!0)||this;return r.view=n,r.keys=e,r._keysToZoomAction={},r.registerIncoming("key-down",t,function(o){return r._handleKeyDown(o)}),e.zoomIn.forEach(function(o){return r._keysToZoomAction[o]=i.IN}),e.zoomOut.forEach(function(o){return r._keysToZoomAction[o]=i.OUT}),r}return e(n,o),n.prototype._handleKeyDown=function(o){this._handleKey(o)},n.prototype._handleKey=function(o){var n=o.modifiers;if(!(n.size>0)||n.has("Shift")){var e=this._keysToZoomAction[o.data.key];e===i.IN?(this.view.navigation.zoomIn(),o.stopPropagation()):e===i.OUT&&(this.view.navigation.zoomOut(),o.stopPropagation())}},n}(t.InputHandler);n.KeyZoom=r}); |
function XString(){
if(arguments.length==0){
this._string=new String();
}else{
if('string'==typeof(arguments[0]))
{
this._string=arguments[0];
}else
{
this._string=arguments[0].toString();
}
}
}
XString.prototype.asXString = function() {
if(arguments.length==0){
this._string=new String();
}else{
if('string'==typeof(arguments[0]))
{
this._string=arguments[0];
}else
{
this._string=arguments[0].toString();
}
}
};
XString.prototype.toString=function(){
return this._string;
}
XString.prototype.bind=function(){
var reg=/\{\{(\w+.)*\w+\}\}/g;
var path=require('libs/utils/path').path;
if(arguments.length==1){//either this is a single binding or map binding
if('string'==typeof(arguments[0])){
this._string=this._string.replace(reg,arguments[0]);
}else{
var dataMap=arguments[0];
//rebuild the datamap
var dataMap2={};
var matches=this._string.match(reg);
if(matches==null)
{
return this;
}
for(var i=0;i<matches.length;i++)
{
var match=matches[i];
var prop=match.substring(2,match.length-2);
var value=path(dataMap,prop);
if(value!=null)
{
dataMap2[prop]=value;
}
}
for(var prop in dataMap2){
var reg=new RegExp("\{\{"+prop+"\}\}","g");
this._string=this._string.replace(reg,dataMap2[prop]);
}
}
}else{//multiple argument bind
for(var i=0;i<arguments.length;i++){
var reg=new RegExp("\{\{["+i+"]\}\}","g");
this._string=this._string.replace(reg,arguments[i]);
}
}
return this;
}
var isNull=function(obj){
if(typeof(obj)=='undefined')
{
return true;
}
if(obj==null)
{
return true;
}
return false;
}
exports.xstring=function(){
var instance=new XString();
instance.asXString.apply(instance,arguments);
return instance;
}
exports.sqlFormat=function(value){
if('boolean' == typeof value)
{
if(value)
{
return 1;
}else
{
return 0;
}
}
else if(isNull(value))
{
return "null";
}
else if("number" == typeof value){
return value;
}else
{
return "'"+value.replace(/\'/g,"''")+"'"
}
}
exports.isNull=isNull;
|
define([
"./core",
"./var/pnum",
"./core/access",
"./css/var/rmargin",
"./css/var/rnumnonpx",
"./css/var/cssExpand",
"./css/var/isHidden",
"./css/var/getStyles",
"./css/curCSS",
"./css/defaultDisplay",
"./css/addGetHookIf",
"./css/support",
"./data/var/data_priv",
"./core/init",
"./css/swap",
"./core/ready",
"./selector" // contains
], function( chadQuery, pnum, access, rmargin, rnumnonpx, cssExpand, isHidden,
getStyles, curCSS, defaultDisplay, addGetHookIf, support, data_priv ) {
var
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += chadQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= chadQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= chadQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += chadQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += chadQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = chadQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : chadQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
chadQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = chadQuery.camelCase( name ),
style = elem.style;
name = chadQuery.cssProps[ origName ] || ( chadQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = chadQuery.cssHooks[ name ] || chadQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( chadQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !chadQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = chadQuery.camelCase( name );
// Make sure that we're working with the right name
name = chadQuery.cssProps[ origName ] || ( chadQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = chadQuery.cssHooks[ name ] || chadQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || chadQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
chadQuery.each([ "height", "width" ], function( i, name ) {
chadQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( chadQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
chadQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
chadQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
chadQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return chadQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
chadQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
chadQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
chadQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
chadQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( chadQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = chadQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
chadQuery.style( elem, name, value ) :
chadQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
chadQuery( this ).show();
} else {
chadQuery( this ).hide();
}
});
}
});
return chadQuery;
});
|
import { mount } from 'enzyme';
import React from 'react';
import ConfirmMessage from '../src/components/ConfirmMessage';
import Button from '../src/components/Button';
describe('ConfirmMessage', () => {
let wrapper;
const onYesClick = jest.fn();
const onNoClick = jest.fn();
describe('prop "popup.pop" is true', () => {
const popup = { msg: 'hello world' };
beforeEach(() => {
wrapper = mount(<ConfirmMessage
popup={popup}
onYesClick={onYesClick}
onNoClick={onNoClick}
/>,
);
});
it('should be defined', () => {
expect(wrapper).toBeDefined();
});
it('should render', () => {
expect(wrapper.find('div').length).toBeGreaterThan(0);
});
it('should display the text from prop popup.msg', () => {
const childText = wrapper.find('p').first().text();
expect(childText).toBe(popup.msg);
});
it('should have two Button-components', () => {
expect(wrapper.find(Button).length).toBe(2);
});
it("should receive pop object as prop 'popup'", () => {
const prop = wrapper.props().popup;
expect(prop).toBeDefined();
});
it('onNoClick prop should be defined', () => {
const prop = wrapper.props().onNoClick;
expect(prop).toBeDefined();
});
it('onYesClick prop should be defined', () => {
const prop = wrapper.props().onYesClick;
expect(prop).toBeDefined();
});
});
});
|
import nock from 'nock';
import expect from 'expect';
import mockStore from '../../helpers/mockStore';
import env from '../../../../frontend/src/lib/env';
import * as constants from '../../../../frontend/src/constants/expenses';
import approveExpense from '../../../../frontend/src/actions/expenses/approve';
import rejectExpense from '../../../../frontend/src/actions/expenses/reject';
describe('expense approval actions', () => {
afterEach(() => {
nock.cleanAll();
});
describe('approve a expense', () => {
it('creates APPROVE_EXPENSE_SUCCESS if it approves successfully', (done) => {
const groupid = 1;
const expenseid = 2;
const response = { success: true };
nock(env.API_ROOT)
.post(`/groups/${groupid}/expenses/${expenseid}/approve`, {
approved: true
})
.reply(200, response);
const store = mockStore({});
store.dispatch(approveExpense(groupid, expenseid))
.then(() => {
const [request, success] = store.getActions();
expect(request).toEqual({ type: constants.APPROVE_EXPENSE_REQUEST, groupid, expenseid });
expect(success).toEqual({ type: constants.APPROVE_EXPENSE_SUCCESS, groupid, expenseid, response });
done();
})
.catch(done)
});
it('creates APPROVE_EXPENSE_FAILURE if it fails', (done) => {
const groupid = 1;
const expenseid = 2;
nock(env.API_ROOT)
.post(`/groups/${groupid}/expenses/${expenseid}/approve`, {
approved: true
})
.replyWithError('Something went wrong!');
const store = mockStore({});
store.dispatch(approveExpense(groupid, expenseid))
.catch(() => {
const [request, failure] = store.getActions();
expect(request).toEqual({ type: constants.APPROVE_EXPENSE_REQUEST, groupid, expenseid });
expect(failure.type).toEqual(constants.APPROVE_EXPENSE_FAILURE);
expect(failure.error.message).toContain('request to http://localhost:3030/api/groups/1/expenses/2/approve failed');
done();
})
});
});
describe('reject a expense', () => {
it('creates REJECT_EXPENSE_SUCCESS if it rejects successfully', (done) => {
const groupid = 1;
const expenseid = 2;
const response = { success: true };
nock(env.API_ROOT)
.post(`/groups/${groupid}/expenses/${expenseid}/approve`, {
approved: false
})
.reply(200, response);
const store = mockStore({});
store.dispatch(rejectExpense(groupid, expenseid))
.then(() => {
const [request, success] = store.getActions();
expect(request).toEqual({ type: constants.REJECT_EXPENSE_REQUEST, groupid, expenseid });
expect(success).toEqual({ type: constants.REJECT_EXPENSE_SUCCESS, groupid, expenseid, response });
done();
})
.catch(done)
});
it('creates REJECT_EXPENSE_FAILURE if it fails', (done) => {
const groupid = 1;
const expenseid = 2;
nock(env.API_ROOT)
.post(`/groups/${groupid}/expenses/${expenseid}/approve`, {
approved: false
})
.replyWithError('Something went wrong!');
const store = mockStore({});
store.dispatch(rejectExpense(groupid, expenseid))
.catch(() => {
const [request, failure] = store.getActions();
expect(request).toEqual({ type: constants.REJECT_EXPENSE_REQUEST, groupid, expenseid });
expect(failure.type).toEqual(constants.REJECT_EXPENSE_FAILURE);
expect(failure.error.message).toContain('request to http://localhost:3030/api/groups/1/expenses/2/approve failed');
done();
})
});
});
});
|
app.factory('adsData', function adsData($http) {
function getAllAds(success, error) {
var accesToken = "mHATtNY_t4Zf9fsDbElhM-6kw3i1V8l95Ms6-gFjTq5uoF1YUgYkrFXG3VUtYauNAKNCjaRJXwLmukZ3oVJJfqJnM_HVwXJjAGlTev-U7RptA1mUKoEvXQWbG_9kq_MRS0Xcpc6R08krzldwQdOXa9mMVUnrVTO2RCm4_380ws9poagJ7YCCNiG7tPD0_4Q3g-UVQC3KOkrS8_xcWGxBxArj7FV0xcy2Hbvf5JgqvkRO9w4b_yFCHp0fdpY0rq2BFlhhzZpcsKvtslThkMipP4Aq_37whE3PkRztDhyWeZbIkHkUfCeQ39mYvKF4SSZNocSYhxKPZThYSmfpPcRbMoWilC3rsSR1S0ZcUoJ-G-1EG4AOkxEcaTDm2PyKHWRdRcF5au1imVT9tQoX70hr-i0BfOVpDqc3omqMuW7wmcHGZYL0EKFbc9BZC0AtLrq0zLEs_lGnXS_6qMoQT4opiburm74DEvnnZ45uRqVgHAs3psEOgA9ouZghzRNsSzcp";
$http({
method: 'GET',
url: 'http://softuni-social-network.azurewebsites.net/api/users/John/wall?PageSizes=5',
headers: { "Authorization": "Bearer " + accesToken }
})
.success(function (data, status, headers, config) {
success(data, status, headers, config);
})
.error(function (data, status, headers, config) {
error(data, status, headers(), config);
});
}
return {
getAds: getAllAds,
}
}) |
'use strict';
/* Controllers */
angular.module('app.controllers', []).
controller('appController', [ '$scope', '$state', 'Emails', function($scope, $state, Emails) {
$scope.emails = Emails.emails;
$scope.slides = {};
$scope.slides.done = false;
// pass-through methods from Emails Service
$scope.randomEmail = Emails.random;
$scope.closeAll = Emails.closeAll;
$scope.onNameSubmit = function(name) {
Emails.interpolateName(name);
$state.go('letter')
}
$scope.tags = ['Science',
'Religion', 'Altruism','Nihilism', 'Family',
'Drugs', 'There is No Answer', 'Recommended','Work', 'Other', 'All'
];
$scope.selectedTag = 'Recommended';
$scope.selectTag = function(tag){
$scope.selectedTag = tag;
}
$scope.isSelected = function(tag){
return( $scope.selectedTag.toLowerCase() == tag.toLowerCase());
}
$scope.emailsByTag = function(){
if ($scope.selectedTag === 'All') { return $scope.emails }
var taggedEmails = [];
$scope.emails.forEach(function(email){
if (email.tags.indexOf($scope.selectedTag) > -1) {
taggedEmails.push(email)
}
});
return taggedEmails
}
}])
.controller('slidesController', [ '$scope', 'Emails', function($scope, Emails) {
$scope.name = null;
$scope.currentSlide = 1; // initialize current slide to first
$scope.incrementSlide = function() {
$scope.currentSlide++;
if ($scope.currentSlide === 4) {
$scope.slides.done = true;
}
}
$scope.showSlide = function(slideNumber) {
return slideNumber == $scope.currentSlide;
}
}])
|
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// f7 -> 118
// f8 -> 119
// f9 -> 120
var prevBtn = document.querySelector('.play-controls__previous')
var playBtn = document.querySelector('.play-controls__play')
var pauseBtn = document.querySelector('.play-controls__pause')
var nextBtn = document.querySelector('.play-controls__next')
if (request.mediaKeyPressed == 118) {
prevBtn.click()
}
if (request.mediaKeyPressed == 119) {
var style = window.getComputedStyle(playBtn),
display = style.getPropertyValue('display')
if (display === 'none') {
pauseBtn.click()
return
}
playBtn.click()
}
if (request.mediaKeyPressed == 120) {
nextBtn.click()
}
})
|
"use strict";
// "use strict";
// import {
// controller,
// Controller,
// get,
// inject,
// IRequest,
// IResponse, middleware,
// validation,
// validator
// } from '../../../../index';
// import {Manager} from "../manager/manager";
// import {UserMiddleware} from "../middleware/userMiddleware";
//
// @controller()
// export class ContextController extends Controller {
//
// @inject() manager: Manager;
//
// @get("/test/context/")
// @validation("userName", validator.string().required())
// @middleware(UserMiddleware)
// async test(req: IRequest, res: IResponse) {
//
// let userName = await this.manager.getContextName()
//
// res.json({userName})
// }
//
//
// }
//
//
//
//# sourceMappingURL=~contextController.js.map |
var isArrayLike = require('./isArrayLike')
function flatten (input, ref) {
var result = Array.isArray(ref) ? ref : []
for (var i = 0, len = input.length; i < len; i++) {
var item = input[i]
if (typeof item === 'object' && isArrayLike(item)) {
flatten(item, result)
} else {
result[result.length] = item
}
}
return result
}
module.exports = flatten
|
version https://git-lfs.github.com/spec/v1
oid sha256:9cb6d8f717806368074367439ebad2573d3972ee5601bc1edb3ea2328a216f01
size 2004
|
let d3 = require('d3');
import Utils from '../core/Utils';
import Header from './Header';
import TimeIndicator from './TimeIndicator';
import Items from './Items';
import KeysPreview from './KeysPreview';
import Properties from './Properties';
import Keys from './Keys';
import Errors from './Errors';
import Selection from './Selection';
export default class Timeline {
constructor(editor, options) {
this.editor = editor;
this.tweenTime = this.editor.tweenTime;
this.timer = this.tweenTime.timer;
this.selectionManager = this.editor.selectionManager;
this._isDirty = true;
this.timer = this.tweenTime.timer;
this.currentTime = this.timer.time; // used in timeindicator.
this.onUpdate = this.onUpdate.bind(this);
// Make the domain cover 20% of the totalDuation by default.
this.initialDomain = [];
this.initialDomain[0] = options.domainStart || 0;
this.initialDomain[1] = options.domainEnd || this.timer.totalDuration * 0.2;
// Adapt time to be greater or equal to domainStart.
if (this.initialDomain[0] > this.timer.getCurrentTime()) {
this.timer.time[0] = this.initialDomain[0];
}
var margin = {top: 6, right: 20, bottom: 0, left: 265};
this.margin = margin;
var width = window.innerWidth - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom - 40;
this.lineHeight = 20;
this.label_position_x = -margin.left + 20;
this.x = d3.time.scale()
.domain(this.initialDomain)
.range([0, width]);
this.xAxis = d3.svg.axis()
.scale(this.x)
.orient("top")
.tickSize(-height, 0)
.tickFormat(Utils.formatMinutes);
this.svg = d3.select('.timeline__main').append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", 600);
this.svgContainer = this.svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
this.svgContainerTime = this.svg.append("g")
.attr("transform", "translate(" + margin.left + ",0)");
this.linesContainer = this.svg.append("g")
.attr("transform", "translate(" + margin.left + "," + (margin.top) + ")");
this.header = new Header(this.timer, this.initialDomain, this.tweenTime, width, margin);
this.timeIndicator = new TimeIndicator(this, this.svgContainerTime);
this.selection = new Selection(this, this.svg, margin);
this.items = new Items(this, this.linesContainer);
this.items.onUpdate.add(this.onUpdate);
this.keysPreview = new KeysPreview(this, this.linesContainer);
this.properties = new Properties(this);
this.properties.onKeyAdded.add((newKey, keyContainer) => {
this._isDirty = true;
// render the timeline directly so that we can directly select
// the new key with it's domElement.
this.render(0, false);
this.keys.selectNewKey(newKey, keyContainer);
});
this.errors = new Errors(this);
this.keys = new Keys(this);
this.keys.onKeyUpdated.add(() => {
this.onUpdate();
});
this.xAxisGrid = d3.svg.axis()
.scale(this.x)
.ticks(100)
.tickSize(-this.items.dy, 0)
.tickFormat("")
.orient("top");
this.xGrid = this.svgContainer.append('g')
.attr('class', 'x axis grid')
.attr("transform", "translate(0," + margin.top + ")")
.call(this.xAxisGrid);
this.xAxisElement = this.svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + margin.top + ")")
.call(this.xAxis);
this.header.onBrush.add((extent) => {
this.x.domain(extent);
this.xGrid.call(this.xAxisGrid);
this.xAxisElement.call(this.xAxis);
this._isDirty = true;
});
// First render
window.requestAnimationFrame(() => {this.render();});
window.onresize = () => {
var INNER_WIDTH = window.innerWidth;
var width = INNER_WIDTH - margin.left - margin.right;
this.svg.attr("width", width + margin.left + margin.right);
this.svg.selectAll('.timeline__right-mask')
.attr('width', INNER_WIDTH);
this.x.range([0, width]);
this._isDirty = true;
this.header.resize(INNER_WIDTH);
this.render();
};
}
onUpdate() {
this.editor.render(false, false, true);
}
render(time, time_changed) {
if (time_changed) {
var domainLength;
// Update current domain when playing to keep time indicator in view.
var margin_ms = 16;
if (this.timer.getCurrentTime() > this.initialDomain[1]) {
domainLength = this.initialDomain[1] - this.initialDomain[0];
this.initialDomain[0] += domainLength - margin_ms;
this.initialDomain[1] += domainLength - margin_ms;
this.header.setDomain(this.initialDomain);
}
if (this.timer.getCurrentTime() < this.initialDomain[0]) {
domainLength = this.initialDomain[1] - this.initialDomain[0];
this.initialDomain[0] = this.timer.getCurrentTime();
this.initialDomain[1] = this.initialDomain[0] + domainLength;
this.header.setDomain(this.initialDomain);
}
}
if (this._isDirty || time_changed) {
// Render header and time indicator everytime the time changed.
this.header.render();
this.timeIndicator.render();
}
if (this._isDirty) {
// No need to call this on each frames, but only on brush, key drag, ...
var bar = this.items.render();
this.keysPreview.render(bar);
var properties = this.properties.render(bar);
this.errors.render(properties);
this.keys.render(properties);
this._isDirty = false;
// Adapt the timeline height.
var height = Math.max(this.items.dy + 30, 230);
this.xAxis.tickSize(-height, 0);
this.xAxisGrid.tickSize(-height, 0);
this.xGrid.call(this.xAxisGrid);
this.xAxisElement.call(this.xAxis);
this.svg.attr("height", height);
this.timeIndicator.updateHeight(height);
}
}
}
|
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['Juggler', 'marionette', 'backbone', 'underscore'], function(Juggler, Marionette, Backbone, _) {
return (root.App = factory(root, Juggler, Marionette, Backbone, _));
});
} else if (typeof exports !== 'undefined') {
var Marionette = require('marionette');
var Backbone = require('backbone');
var _ = require('underscore');
module.exports = factory(root, Juggler, Marionette, Backbone, _);
} else {
root.App = factory(root, root.Juggler, root.Marionette, root.Backbone, root._);
}
}(this, function(root, Juggler, Marionette, Backbone, _) {
'use strict';
var previousApp = root.App;
var App = new Marionette.Application();
App.VERSION = '0.0.1';
App.noConflict = function() {
root.App = previousApp;
return this;
};
/*
* switch sub module
*/
App.startSubApp = function(appName, args) {
var currentApp = App.module(appName);
if (App.currentApp) {
App.currentApp.stop();
}
App.currentApp = currentApp;
currentApp.start(args);
};
// @include ./enities.js
// @include ./header.js
// @include ./home.js
// @include ./layout.js
// @include ./form.js
// @include ./table.js
// @include ./nav.js
// @include ./button.js
// @include ./dialog.js
// @include ./demo.js
App.addInitializer(function(){
});
return App;
}));
|
import {
FETCH_BOOKS,
FETCH_GOOGLE_API_BOOK_INFO,
ADD_BOOK,
ADD_TO_WISHLIST,
MARK_READ,
MARK_BEING_READ
} from '../actions/types';
/*
A reducer is a function that takes the current state and an action, and then returns a
new state. This reducer is responsible for appState.quotes data.
See `initialstate.js` for a clear view of what it looks like!
*/
export default function (state = null, action) {
switch (action.type) {
case FETCH_BOOKS:
return action.payload;
case FETCH_GOOGLE_API_BOOK_INFO:
return action.payload;
case ADD_BOOK: {
const newBookState = {};
newBookState[action.payload[1]] = action.payload[0];
return Object.assign({}, state, newBookState);
}
case ADD_TO_WISHLIST:
return state;
case MARK_READ:
return action.payload;
case MARK_BEING_READ:
return action.payload;
}
return state;
}
|
////////////////////////////////////
/**
* Intercooler.js - there is no need to be upset.
*/
var Intercooler = Intercooler || (function () {
'use strict'; // inside function for better merging
//--------------------------------------------------
// Vars
//--------------------------------------------------
var _MACROS = ['ic-get-from', 'ic-post-to', 'ic-put-to', 'ic-patch-to', 'ic-delete-from',
'ic-style-src', 'ic-attr-src', 'ic-prepend-from', 'ic-append-from'];
var _scrollHandler = null;
var _UUID = 1;
var _readyHandlers = [];
//============================================================
// Base Swap Definitions
//============================================================
function remove(elt) {
elt.remove();
}
function showIndicator(elt) {
if (elt.closest('.ic-use-transition').length > 0) {
elt.data('ic-use-transition', true);
elt.removeClass('ic-use-transition');
} else {
elt.show();
}
}
function hideIndicator(elt) {
if (elt.data('ic-use-transition')) {
elt.data('ic-use-transition', null);
elt.addClass('ic-use-transition');
} else {
elt.hide();
}
}
function prepend(parent, responseContent) {
try {
parent.prepend(responseContent);
} catch (e) {
log(elt, formatError(e), "ERROR");
}
if (parent.attr('ic-limit-children')) {
var limit = parseInt(parent.attr('ic-limit-children'));
if (parent.children().length > limit) {
parent.children().slice(limit, parent.children().length).remove();
}
}
}
function append(parent, responseContent) {
try {
parent.append(responseContent);
} catch (e) {
log(elt, formatError(e), "ERROR");
}
if (parent.attr('ic-limit-children')) {
var limit = parseInt(parent.attr('ic-limit-children'));
if (parent.children().length > limit) {
parent.children().slice(0, parent.children().length - limit).remove();
}
}
}
//============================================================
// Utility Methods
//============================================================
function log(elt, msg, level) {
if (elt == null) {
elt = $('body');
}
elt.trigger("log.ic", [msg, level, elt]);
if (level == "ERROR") {
if (window.console) {
window.console.log("Intercooler Error : " + msg);
}
var errorUrl = closestAttrValue($('body'), 'ic-post-errors-to');
if (errorUrl) {
$.post(errorUrl, {'error': msg})
}
}
}
function uuid() {
return _UUID++;
}
function icSelectorFor(elt) {
return "[ic-id='" + getIntercoolerId(elt) + "']";
}
function parseInterval(str) {
log(null, "POLL: Parsing interval string " + str, 'DEBUG');
if (str == "null" || str == "false" || str == "") {
return null;
} else if (str.lastIndexOf("ms") == str.length - 2) {
return parseFloat(str.substr(0, str.length - 2));
} else if (str.lastIndexOf("s") == str.length - 1) {
return parseFloat(str.substr(0, str.length - 1)) * 1000;
} else {
return 1000;
}
}
function initScrollHandler() {
if (_scrollHandler == null) {
_scrollHandler = function () {
$("[ic-trigger-on='scrolled-into-view']").each(function () {
if (isScrolledIntoView($(this)) && $(this).data('ic-scrolled-into-view-loaded') != true) {
$(this).data('ic-scrolled-into-view-loaded', true);
fireICRequest($(this));
}
})
};
$(window).scroll(_scrollHandler);
}
}
function currentUrl() {
return window.location.pathname + window.location.search + window.location.hash;
}
// taken from turbolinks.js
function createDocument(html) {
var doc = null;
if (/<(html|body)/i.test(html)) {
doc = document.documentElement.cloneNode();
doc.innerHTML = html;
} else {
doc = document.documentElement.cloneNode(true);
doc.querySelector('body').innerHTML = html;
}
return $(doc);
}
//============================================================
// Request/Parameter/Include Processing
//============================================================
function getTarget(elt) {
var closest = $(elt).closest('[ic-target]');
var targetValue = closest.attr('ic-target');
if (targetValue == 'this') {
return closest;
} else if (targetValue && targetValue.indexOf('this.') != 0) {
if (targetValue.indexOf('closest ') == 0) {
return elt.closest(targetValue.substr(8));
} else {
return $(targetValue);
}
} else {
return elt;
}
}
function processHeaders(elt, xhr) {
elt.trigger("beforeHeaders.ic", [elt, xhr]);
log(elt, "response headers: " + xhr.getAllResponseHeaders(), "DEBUG");
var target = null;
if (xhr.getResponseHeader("X-IC-Refresh")) {
var pathsToRefresh = xhr.getResponseHeader("X-IC-Refresh").split(",");
log(elt, "X-IC-Refresh: refreshing " + pathsToRefresh, "DEBUG");
$.each(pathsToRefresh, function (i, str) {
refreshDependencies(str.replace(/ /g, ""), elt);
});
}
if (xhr.getResponseHeader("X-IC-Script")) {
log(elt, "X-IC-Script: evaling " + xhr.getResponseHeader("X-IC-Script"), "DEBUG");
eval(xhr.getResponseHeader("X-IC-Script"));
}
if (xhr.getResponseHeader("X-IC-Redirect")) {
log(elt, "X-IC-Redirect: redirecting to " + xhr.getResponseHeader("X-IC-Redirect"), "DEBUG");
window.location = xhr.getResponseHeader("X-IC-Redirect");
}
if (xhr.getResponseHeader("X-IC-CancelPolling") == "true") {
cancelPolling($(elt).closest('[ic-poll]'));
}
if (xhr.getResponseHeader("X-IC-ResumePolling") == "true") {
var pollingElt = $(elt).closest('[ic-poll]');
pollingElt.attr('ic-pause-polling', null);
startPolling(pollingElt);
}
if (xhr.getResponseHeader("X-IC-Open")) {
log(elt, "X-IC-Open: opening " + xhr.getResponseHeader("X-IC-Open"), "DEBUG");
window.open(xhr.getResponseHeader("X-IC-Open"));
}
var triggerValue = xhr.getResponseHeader("X-IC-Trigger");
if (triggerValue) {
log(elt, "X-IC-Trigger: found trigger " + triggerValue, "DEBUG");
target = getTarget(elt);
// Deprecated API
if (xhr.getResponseHeader("X-IC-Trigger-Data")) {
var triggerArgs = $.parseJSON(xhr.getResponseHeader("X-IC-Trigger-Data"));
target.trigger(triggerValue, triggerArgs);
} else {
if(triggerValue.indexOf("{") >= 0) {
$.each($.parseJSON(triggerValue), function(event, args) {
target.trigger(event, args);
});
} else {
target.trigger(triggerValue, []);
}
}
}
if (xhr.getResponseHeader("X-IC-Remove")) {
if (elt) {
target = getTarget(elt);
log(elt, "X-IC-Remove header found.", "DEBUG");
remove(target);
}
}
elt.trigger("afterHeaders.ic", [elt, xhr]);
return true;
}
function beforeRequest(elt) {
elt.addClass('disabled');
elt.data('ic-request-in-flight', true);
}
function requestCleanup(indicator, elt) {
if (indicator.length > 0) {
hideIndicator(indicator);
}
elt.removeClass('disabled');
elt.data('ic-request-in-flight', false);
if (elt.data('ic-next-request')) {
elt.data('ic-next-request')();
elt.data('ic-next-request', null);
}
}
function replaceOrAddMethod(data, actualMethod) {
var regex = /(&|^)_method=[^&]*/;
var content = "&_method=" + actualMethod;
if (regex.test(data)) {
return data.replace(regex, content)
} else {
return data + "&" + content;
}
}
function globalEval(script) {
return window[ "eval" ].call(window, script);
}
function closestAttrValue(elt, attr) {
var closestElt = $(elt).closest('[' + attr + ']');
if (closestElt.length > 0) {
return closestElt.attr(attr);
} else {
return null;
}
}
function formatError(e) {
var msg = e.toString() + "\n";
try {
msg += e.stack;
} catch (e) {
// ignore
}
return msg;
}
function handleRemoteRequest(elt, type, url, data, success) {
beforeRequest(elt);
data = replaceOrAddMethod(data, type);
// Spinner support
var indicator = findIndicator(elt);
if (indicator.length > 0) {
showIndicator(indicator);
}
var requestId = uuid();
var requestStart = new Date();
var actualRequestType = type == 'GET' ? 'GET' : 'POST';
$.ajax({
type: actualRequestType,
url: url,
data: data,
dataType: 'text',
headers: {
"Accept": "text/html-partial, */*; q=0.9",
"X-IC-Request": true,
"X-HTTP-Method-Override": type
},
beforeSend: function (xhr, settings) {
elt.trigger("beforeSend.ic", [elt, data, settings, xhr, requestId]);
log(elt, "before AJAX request " + requestId + ": " + type + " to " + url, "DEBUG");
var onBeforeSend = closestAttrValue(elt, 'ic-on-beforeSend');
if (onBeforeSend) {
globalEval('(function (data, settings, xhr) {' + onBeforeSend + '})')(data, settings, xhr);
}
},
success: function (data, textStatus, xhr) {
elt.trigger("success.ic", [elt, data, textStatus, xhr, requestId]);
log(elt, "AJAX request " + requestId + " was successful.", "DEBUG");
var onSuccess = closestAttrValue(elt, 'ic-on-success');
if (onSuccess) {
if (globalEval('(function (data, textStatus, xhr) {' + onSuccess + '})')(data, textStatus, xhr) == false) {
return;
}
}
var beforeHeaders = new Date();
try {
if (processHeaders(elt, xhr)) {
log(elt, "Processed headers for request " + requestId + " in " + (new Date() - beforeHeaders) + "ms", "DEBUG");
var beforeSuccess = new Date();
if (xhr.getResponseHeader("X-IC-PushURL") || closestAttrValue(elt, 'ic-push-url') == "true") {
try {
requestCleanup(indicator, elt); // clean up before snap-shotting HTML
var newUrl = xhr.getResponseHeader("X-IC-PushURL") || closestAttrValue(elt, 'ic-src');
_history.snapshotForHistory(newUrl);
} catch(e) {
log(elt, "Error during history snapshot for " + requestId + ": " + formatError(e), "ERROR");
}
}
success(data, textStatus, elt, xhr);
log(elt, "Process content for request " + requestId + " in " + (new Date() - beforeSuccess) + "ms", "DEBUG");
}
elt.trigger("after.success.ic", [elt, data, textStatus, xhr, requestId]);
} catch (e) {
log(elt, "Error processing successful request " + requestId + " : " + formatError(e), "ERROR");
}
},
error: function (xhr, status, str) {
elt.trigger("error.ic", [elt, status, str, xhr]);
var onError = closestAttrValue(elt, 'ic-on-error');
if (onError) {
globalEval('(function (status, str, xhr) {' + onError + '})')(status, str, xhr);
}
log(elt, "AJAX request " + requestId + " experienced an error: " + str, "ERROR");
},
complete: function (xhr, status) {
log(elt, "AJAX request " + requestId + " completed in " + (new Date() - requestStart) + "ms", "DEBUG");
requestCleanup(indicator, elt);
try {
if ($.contains(document, elt[0])) {
$(elt).trigger("complete.ic", [elt, data, status, xhr, requestId]);
} else {
$('body').trigger("complete.ic", [elt, data, status, xhr, requestId]);
}
} catch (e) {
log(elt, "Error during complete.ic event for " + requestId + " : " + formatError(e), "ERROR");
}
var onComplete = closestAttrValue(elt, 'ic-on-complete');
if (onComplete) {
globalEval('(function (xhr, status) {' + onComplete + '})')(xhr, status);
}
}
})
}
function findIndicator(elt) {
var indicator = null;
if ($(elt).attr('ic-indicator')) {
indicator = $($(elt).attr('ic-indicator')).first();
} else {
indicator = $(elt).find(".ic-indicator").first();
if (indicator.length == 0) {
var parent = closestAttrValue(elt, 'ic-indicator');
if (parent) {
indicator = $(parent).first();
} else {
if($(elt).next().is('.ic-indicator')) {
indicator = $(elt).next();
}
}
}
}
return indicator;
}
function processIncludes(str) {
var returnString = "";
if ($.trim(str).indexOf("{") == 0) {
var obj = $.parseJSON(str);
$.each(obj, function (key, value) {
returnString += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(value);
});
} else {
$(str).each(function () {
returnString += "&" + $(this).serialize();
});
}
return returnString;
}
function getParametersForElement(verb, elt, triggerOrigin) {
var target = getTarget(elt);
var str = "ic-request=true";
// if the element is in a form, include the entire form
if (verb != "GET" && elt.closest('form').length > 0) {
str += "&" + elt.closest('form').serialize();
} else { // otherwise include the element
str += "&" + elt.serialize();
}
var promptText = closestAttrValue(elt, 'ic-prompt');
if(promptText) {
var promptVal = prompt(promptText);
str += "&ic-prompt-value=" + encodeURIComponent(promptVal);
}
if (elt.attr('id')) {
str += "&ic-element-id=" + elt.attr('id');
}
if (elt.attr('name')) {
str += "&ic-element-name=" + elt.attr('name');
}
if (target.attr('ic-id')) {
str += "&ic-id=" + target.attr('ic-id');
}
if (target.attr('id')) {
str += "&ic-target-id=" + target.attr('id');
}
if (triggerOrigin && triggerOrigin.attr('id')) {
str += "&ic-trigger-id=" + triggerOrigin.attr('id');
}
if (triggerOrigin && triggerOrigin.attr('name')) {
str += "&ic-trigger-name=" + triggerOrigin.attr('name');
}
if (target.data('ic-last-refresh')) {
str += "&ic-last-refresh=" + target.data('ic-last-refresh');
}
var includeAttr = closestAttrValue(elt, 'ic-include');
if (includeAttr) {
str += processIncludes(includeAttr);
}
$('[ic-global-include]').each(function() {
str += processIncludes($(this).attr('ic-global-include'));
});
str += "&ic-current-url=" + encodeURIComponent(currentUrl());
log(elt, "request parameters " + str, "DEBUG");
return str;
}
function maybeSetIntercoolerInfo(elt) {
var target = getTarget(elt);
getIntercoolerId(target);
maybeSetIntercoolerMetadata(target);
if (elt.data('elementAdded.ic') != true) {
elt.data('elementAdded.ic', true);
elt.trigger("elementAdded.ic");
}
}
function updateIntercoolerMetaData(elt) {
elt.data('ic-last-refresh', new Date().getTime());
}
function maybeSetIntercoolerMetadata(elt) {
elt.data('ic-last-refresh', new Date().getTime());
}
function getIntercoolerId(elt) {
if (!elt.attr('ic-id')) {
elt.attr('ic-id', uuid());
}
return elt.attr('ic-id');
}
//============================================================
// Tree Processing
//============================================================
function processNodes(elt) {
if(elt.length > 1) {
elt.each(function(){
processNodes($(this));
})
} else {
processMacros(elt);
processSources(elt);
processPolling(elt);
processTriggerOn(elt);
processRemoveAfter(elt);
processAddClasses(elt);
processRemoveClasses(elt);
}
}
function fireReadyStuff(elt) {
elt.trigger('nodesProcessed.ic');
$.each(_readyHandlers, function (i, handler) {
try {
handler(elt);
} catch (e) {
log(elt, formatError(e), "ERROR");
}
});
}
function processMacros(elt) {
$.each(_MACROS, function (i, macro) {
if ($(elt).closest('.ic-ignore').length == 0) {
if ($(elt).is('[' + macro + ']')) {
processMacro(macro, $(elt));
}
$(elt).find('[' + macro + ']').each(function () {
if ($(this).closest('.ic-ignore').length == 0) {
processMacro(macro, $(this));
}
});
}
});
}
function processSources(elt) {
if ($(elt).closest('.ic-ignore').length == 0) {
if ($(elt).is("[ic-src]")) {
maybeSetIntercoolerInfo($(elt));
}
$(elt).find("[ic-src]").each(function () {
if ($(this).closest('.ic-ignore').length == 0) {
maybeSetIntercoolerInfo($(this));
}
});
}
}
function processPolling(elt) {
if ($(elt).closest('.ic-ignore').length == 0) {
if ($(elt).is('[ic-poll]')) {
maybeSetIntercoolerInfo($(elt));
startPolling(elt);
}
$(elt).find('[ic-poll]').each(function () {
if ($(this).closest('.ic-ignore').length == 0) {
maybeSetIntercoolerInfo($(this));
startPolling($(this));
}
});
}
}
function processTriggerOn(elt) {
if ($(elt).closest('.ic-ignore').length == 0) {
handleTriggerOn(elt);
$(elt).find('[ic-trigger-on]').each(function () {
if ($(this).closest('.ic-ignore').length == 0) {
handleTriggerOn($(this));
}
});
}
}
function processRemoveAfter(elt) {
if ($(elt).closest('.ic-ignore').length == 0) {
handleRemoveAfter(elt);
$(elt).find('[ic-remove-after]').each(function () {
if ($(this).closest('.ic-ignore').length == 0) {
handleRemoveAfter($(this));
}
});
}
}
function processAddClasses(elt) {
if ($(elt).closest('.ic-ignore').length == 0) {
handleAddClasses(elt);
$(elt).find('[ic-add-class]').each(function () {
if ($(this).closest('.ic-ignore').length == 0) {
handleAddClasses($(this));
}
});
}
}
function processRemoveClasses(elt) {
if ($(elt).closest('.ic-ignore').length == 0) {
handleRemoveClasses(elt);
$(elt).find('[ic-remove-class]').each(function () {
if ($(this).closest('.ic-ignore').length == 0) {
handleRemoveClasses($(this));
}
});
}
}
//============================================================
// Polling support
//============================================================
function startPolling(elt) {
if (elt.data('ic-poll-interval-id') == null && $(elt).attr('ic-pause-polling') != 'true') {
var interval = parseInterval(elt.attr('ic-poll'));
if (interval != null) {
var selector = icSelectorFor(elt);
var repeats = parseInt(elt.attr('ic-poll-repeats')) || -1;
var currentIteration = 0;
log(elt, "POLL: Starting poll for element " + selector, "DEBUG");
var timerId = setInterval(function () {
var target = $(selector);
elt.trigger("onPoll.ic", target);
if ((target.length == 0) || (currentIteration == repeats) || elt.data('ic-poll-interval-id') != timerId) {
log(elt, "POLL: Clearing poll for element " + selector, "DEBUG");
clearTimeout(timerId);
} else {
fireICRequest(target);
}
currentIteration++;
}, interval);
elt.data('ic-poll-interval-id', timerId);
}
}
}
function cancelPolling(elt) {
if (elt.data('ic-poll-interval-id') != null) {
clearTimeout(elt.data('ic-poll-interval-id'));
elt.data('ic-poll-interval-id', null);
}
}
//============================================================----
// Dependency support
//============================================================----
function refreshDependencies(dest, src) {
log(src, "refreshing dependencies for path " + dest, "DEBUG");
$('[ic-src]').each(function () {
var fired = false;
if (verbFor($(this)) == "GET" && $(this).attr('ic-deps') != 'ignore' && typeof($(this).attr('ic-poll')) == 'undefined') {
if (isDependent(dest, $(this).attr('ic-src'))) {
if (src == null || $(src)[0] != $(this)[0]) {
fireICRequest($(this));
fired = true;
}
} else if (isDependent(dest, $(this).attr('ic-deps')) || $(this).attr('ic-deps') == "*") {
if (src == null || $(src)[0] != $(this)[0]) {
fireICRequest($(this));
fired = true;
}
}
}
if (fired) {
log($(this), "depends on path " + dest + ", refreshing...", "DEBUG")
}
});
}
function isDependent(src, dest) {
return (src && dest) && (dest.indexOf(src) == 0 || src.indexOf(dest) == 0);
}
//============================================================----
// Trigger-On support
//============================================================----
function verbFor(elt) {
if (elt.attr('ic-verb')) {
return elt.attr('ic-verb').toUpperCase();
}
return "GET";
}
function eventFor(attr, elt) {
if (attr == "default") {
if ($(elt).is('button')) {
return 'click';
} else if ($(elt).is('form')) {
return 'submit';
} else if ($(elt).is(':input')) {
return 'change';
} else {
return 'click';
}
} else {
return attr;
}
}
function preventDefault(elt) {
return elt.is('form') || (elt.is(':submit') && elt.closest('form').length == 1);
}
function handleRemoveAfter(elt) {
if ($(elt).attr('ic-remove-after')) {
var interval = parseInterval($(elt).attr('ic-remove-after'));
setTimeout(function () {
remove(elt);
}, interval);
}
}
function parseAndApplyClass(classInfo, elt, operation) {
var cssClass = "";
var delay = 50;
if (classInfo.indexOf(":") > 0) {
var split = classInfo.split(':');
cssClass = split[0];
delay = parseInterval(split[1]);
} else {
cssClass = classInfo;
}
setTimeout(function () {
elt[operation](cssClass)
}, delay);
}
function handleAddClasses(elt) {
if ($(elt).attr('ic-add-class')) {
var values = $(elt).attr('ic-add-class').split(",");
var arrayLength = values.length;
for (var i = 0; i < arrayLength; i++) {
parseAndApplyClass($.trim(values[i]), elt, 'addClass');
}
}
}
function handleRemoveClasses(elt) {
if ($(elt).attr('ic-remove-class')) {
var values = $(elt).attr('ic-remove-class').split(",");
var arrayLength = values.length;
for (var i = 0; i < arrayLength; i++) {
parseAndApplyClass($.trim(values[i]), elt, 'removeClass');
}
}
}
function handleTriggerOn(elt) {
if ($(elt).attr('ic-trigger-on')) {
if ($(elt).attr('ic-trigger-on') == 'load') {
fireICRequest(elt);
} else if ($(elt).attr('ic-trigger-on') == 'scrolled-into-view') {
initScrollHandler();
setTimeout(function () {
$(window).trigger('scroll');
}, 100); // Trigger a scroll in case element is already viewable
} else {
var triggerOn = $(elt).attr('ic-trigger-on').split(" ");
$(elt).on(eventFor(triggerOn[0], $(elt)), function (e) {
var onBeforeTrigger = closestAttrValue(elt, 'ic-on-beforeTrigger');
if (onBeforeTrigger) {
if (globalEval('(function (evt, elt) {' + onBeforeTrigger + '})')(e, $(elt)) == false) {
log($(elt), "ic-trigger cancelled by ic-on-beforeTrigger", "DEBUG");
return false;
}
}
if (triggerOn[1] == 'changed') {
var currentVal = $(elt).val();
var previousVal = $(elt).data('ic-previous-val');
$(elt).data('ic-previous-val', currentVal);
if (currentVal != previousVal) {
fireICRequest($(elt));
}
} else {
fireICRequest($(elt));
}
if (preventDefault(elt)) {
e.preventDefault();
return false;
}
return true;
});
}
}
}
//============================================================----
// Macro support
//============================================================----
function processMacro(macro, elt) {
// action attributes
if (macro == 'ic-post-to') {
setIfAbsent(elt, 'ic-src', elt.attr('ic-post-to'));
setIfAbsent(elt, 'ic-verb', 'POST');
setIfAbsent(elt, 'ic-trigger-on', 'default');
setIfAbsent(elt, 'ic-deps', 'ignore');
}
if (macro == 'ic-put-to') {
setIfAbsent(elt, 'ic-src', elt.attr('ic-put-to'));
setIfAbsent(elt, 'ic-verb', 'PUT');
setIfAbsent(elt, 'ic-trigger-on', 'default');
setIfAbsent(elt, 'ic-deps', 'ignore');
}
if (macro == 'ic-patch-to') {
setIfAbsent(elt, 'ic-src', elt.attr('ic-patch-to'));
setIfAbsent(elt, 'ic-verb', 'PATCH');
setIfAbsent(elt, 'ic-trigger-on', 'default');
setIfAbsent(elt, 'ic-deps', 'ignore');
}
if (macro == 'ic-get-from') {
setIfAbsent(elt, 'ic-src', elt.attr('ic-get-from'));
setIfAbsent(elt, 'ic-trigger-on', 'default');
setIfAbsent(elt, 'ic-deps', 'ignore');
}
if (macro == 'ic-delete-from') {
setIfAbsent(elt, 'ic-src', elt.attr('ic-delete-from'));
setIfAbsent(elt, 'ic-verb', 'DELETE');
setIfAbsent(elt, 'ic-trigger-on', 'default');
setIfAbsent(elt, 'ic-deps', 'ignore');
}
// non-action attributes
var value = null;
var url = null;
if (macro == 'ic-style-src') {
value = elt.attr('ic-style-src').split(":");
var styleAttribute = value[0];
url = value[1];
setIfAbsent(elt, 'ic-src', url);
setIfAbsent(elt, 'ic-target', 'this.style.' + styleAttribute);
}
if (macro == 'ic-attr-src') {
value = elt.attr('ic-attr-src').split(":");
var attribute = value[0];
url = value[1];
setIfAbsent(elt, 'ic-src', url);
setIfAbsent(elt, 'ic-target', 'this.' + attribute);
}
if (macro == 'ic-prepend-from') {
setIfAbsent(elt, 'ic-src', elt.attr('ic-prepend-from'));
}
if (macro == 'ic-append-from') {
setIfAbsent(elt, 'ic-src', elt.attr('ic-append-from'));
}
}
function setIfAbsent(elt, attr, value) {
if (elt.attr(attr) == null) {
elt.attr(attr, value);
}
}
//============================================================----
// Utilities
//============================================================----
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
&& (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
function maybeScrollToTarget(elt, target) {
if (closestAttrValue(elt, 'ic-scroll-to-target') != "false" &&
(closestAttrValue(elt, 'ic-scroll-to-target') == 'true' ||
closestAttrValue(target, 'ic-scroll-to-target') == 'true')) {
var offset = -50; // -50 px default offset padding
if (closestAttrValue(elt, 'ic-scroll-offset')) {
offset = parseInt(closestAttrValue(elt, 'ic-scroll-offset'));
} else if (closestAttrValue(target, 'ic-scroll-offset')) {
offset = parseInt(closestAttrValue(target, 'ic-scroll-offset'));
}
var currentPosition = target.offset().top;
var portalTop = $(window).scrollTop();
var portalEnd = portalTop + window.innerHeight;
//if the current top of this element is not visible, scroll it to the top position
if (currentPosition < portalTop || currentPosition > portalEnd) {
offset += currentPosition;
$('html,body').animate({scrollTop: offset}, 400);
}
}
}
function getTransitionDuration(elt, target) {
var transitionDuration = closestAttrValue(elt, 'ic-transition-duration');
if (transitionDuration) {
return parseInterval(transitionDuration);
}
transitionDuration = closestAttrValue(target, 'ic-transition-duration');
if (transitionDuration) {
return parseInterval(transitionDuration);
}
var duration = 0;
var durationStr = $(target).css('transition-duration');
if(durationStr) {
duration += parseInterval(durationStr);
}
var delayStr = $(target).css('transition-delay');
if(delayStr) {
duration += parseInterval(delayStr);
}
return duration;
}
function processICResponse(responseContent, elt, forHistory) {
if (responseContent && responseContent != "" && responseContent != " ") {
log(elt, "response content: \n" + responseContent, "DEBUG");
var target = getTarget(elt);
var contentToSwap = maybeFilter(responseContent, closestAttrValue(elt, 'ic-select-from-response'));
var doSwap = function () {
if (closestAttrValue(elt, 'ic-replace-target') == "true") {
try {
target.replaceWith(contentToSwap);
} catch (e) {
log(elt, formatError(e), "ERROR");
}
processNodes(contentToSwap);
fireReadyStuff($(target));
} else {
if (elt.is('[ic-prepend-from]')) {
prepend(target, contentToSwap);
processNodes(contentToSwap);
fireReadyStuff($(target));
} else if (elt.is('[ic-append-from]')) {
append(target, contentToSwap);
processNodes(contentToSwap);
fireReadyStuff($(target));
} else {
try {
target.empty().append(contentToSwap);
} catch (e) {
log(elt, formatError(e), "ERROR");
}
$(target).children().each(function () {
processNodes($(this));
});
fireReadyStuff($(target));
}
updateIntercoolerMetaData(target);
if(forHistory != true) {
maybeScrollToTarget(elt, target);
}
}
};
if(target.length == 0) {
//TODO cgross - refactor getTarget to return printable string here
log(elt, "Invalid target for element: " + $(elt).closest('[ic-target]').attr('ic-target'), "ERROR");
return;
}
var delay = getTransitionDuration(elt, target);
target.addClass('ic-transitioning');
setTimeout(function () {
try {
doSwap();
} catch(e) {
log(elt, "Error during content swaop : " + formatError(e), "ERROR");
}
setTimeout(function () {
try {
target.removeClass('ic-transitioning');
_history.updateHistory();
target.trigger("complete_transition.ic", [target]);
} catch(e) {
log(elt, "Error during transition complete : " + formatError(e), "ERROR");
}
}, 20);
}, delay);
} else {
log(elt, "Empty response, nothing to do here.", "DEBUG");
}
}
function maybeFilter(newContent, filter) {
var content = $.parseHTML(newContent, null, true);
var asQuery = $(content);
if (filter) {
return asQuery.filter(filter).add(asQuery.find(filter)).contents();
} else {
return asQuery;
}
}
function getStyleTarget(elt) {
var val = closestAttrValue(elt, 'ic-target');
if (val && val.indexOf("this.style.") == 0) {
return val.substr(11)
} else {
return null;
}
}
function getAttrTarget(elt) {
var val = closestAttrValue(elt, 'ic-target');
if (val && val.indexOf("this.") == 0) {
return val.substr(5)
} else {
return null;
}
}
function fireICRequest(elt, alternateHandler) {
var triggerOrigin = elt;
if (!elt.is('[ic-src]')) {
elt = elt.closest('[ic-src]');
}
var confirmText = closestAttrValue(elt, 'ic-confirm');
if (confirmText) {
if (!confirm(confirmText)) {
return;
}
}
if (elt.length > 0) {
var icEventId = uuid();
elt.data('ic-event-id', icEventId);
var invokeRequest = function () {
// if an existing request is in flight for this element, push this request as the next to be executed
if (elt.data('ic-request-in-flight') == true) {
elt.data('ic-next-request', invokeRequest);
return;
}
if (elt.data('ic-event-id') == icEventId) {
var styleTarget = getStyleTarget(elt);
var attrTarget = styleTarget ? null : getAttrTarget(elt);
var verb = verbFor(elt);
var success = alternateHandler || function (data) {
if (styleTarget) {
elt.css(styleTarget, data);
} else if (attrTarget) {
elt.attr(attrTarget, data);
} else {
processICResponse(data, elt);
if (verb != 'GET') {
refreshDependencies(elt.attr('ic-src'), elt);
}
}
};
handleRemoteRequest(elt, verb, elt.attr('ic-src'), getParametersForElement(verb, elt, triggerOrigin), success);
}
};
var triggerDelay = closestAttrValue(elt, 'ic-trigger-delay');
if (triggerDelay) {
setTimeout(invokeRequest, parseInterval(triggerDelay));
} else {
invokeRequest();
}
}
}
//============================================================
// History Support
//============================================================
function newIntercoolerHistory(storage, history, slotLimit, historyVersion) {
/* Constants */
var HISTORY_SUPPORT_SLOT = 'ic-history-support';
var HISTORY_SLOT_PREFIX = "ic-hist-elt-";
/* Instance Vars */
var historySupportData = JSON.parse(storage.getItem(HISTORY_SUPPORT_SLOT));
var _snapshot = null;
// Reset history if the history config has changed
if (historyConfigHasChanged(historySupportData)) {
log(getTargetForHistory($('body')), "Intercooler History configuration changed, clearing history", "INFO");
clearHistory();
}
if(historySupportData == null) {
historySupportData = {
slotLimit : slotLimit,
historyVersion: historyVersion,
lruList: []
};
}
/* Instance Methods */
function historyConfigHasChanged(historySupportData) {
return historySupportData == null ||
historySupportData.slotLimit != slotLimit ||
historySupportData.historyVersion != historyVersion ||
historySupportData.lruList == null
}
function clearHistory () {
var keys = [];
for (var i = 0; i < storage.length; i++) {
if (storage.key(i).indexOf(HISTORY_SLOT_PREFIX) == 0) {
keys.push(storage.key(i));
}
}
for (var j = 0; j < keys.length; j++) {
storage.removeItem(keys[j]);
}
storage.removeItem(HISTORY_SUPPORT_SLOT);
historySupportData = {
slotLimit : slotLimit,
historyVersion: historyVersion,
lruList: []
};
}
function updateLRUList(url) {
var lruList = historySupportData.lruList;
var currentIndex = lruList.indexOf(url);
var t = getTargetForHistory($('body'));
// found in current list, shift it to the end
if(currentIndex >= 0) {
log(t, "URL found in LRU list, moving to end", "INFO");
lruList.splice(currentIndex, 1);
lruList.push(url);
} else {
// not found, add and shift if necessary
log(t, "URL not found in LRU list, adding", "INFO");
lruList.push(url);
if(lruList.length > historySupportData.slotLimit) {
var urlToDelete = lruList.shift();
log(t, "History overflow, removing local history for " + urlToDelete, "INFO");
storage.removeItem(HISTORY_SLOT_PREFIX + urlToDelete);
}
}
// save history metadata
storage.setItem(HISTORY_SUPPORT_SLOT, JSON.stringify(historySupportData));
return lruList;
}
function saveHistoryData(restorationData) {
var content = JSON.stringify(restorationData);
try {
storage.setItem(restorationData.id, content);
} catch (e) {
//quota error, nuke local cache
try {
clearHistory();
storage.setItem(restorationData.id, content);
} catch (e) {
log(getTargetForHistory($('body')), "Unable to save intercooler history with entire history cleared, is something else eating " +
"local storage? History Limit:" + slotLimit, "ERROR");
}
}
}
function makeHistoryEntry(html, yOffset, url) {
var restorationData = {
"url": url,
"id": HISTORY_SLOT_PREFIX + url,
"content": html,
"yOffset": yOffset,
"timestamp": new Date().getTime()
};
updateLRUList(url);
// save to the history slot
saveHistoryData(restorationData);
return restorationData;
}
function addPopStateHandler(windowToAdd) {
if (windowToAdd.onpopstate == null || windowToAdd.onpopstate['ic-on-pop-state-handler'] != true) {
var currentOnPopState = windowToAdd.onpopstate;
windowToAdd.onpopstate = function (event) {
getTargetForHistory($('body')).trigger('handle.onpopstate.ic');
if (!handleHistoryNavigation(event)) {
if (currentOnPopState) {
currentOnPopState(event);
}
}
getTargetForHistory($('body')).trigger('pageLoad.ic');
};
windowToAdd.onpopstate['ic-on-pop-state-handler'] = true;
}
}
function updateHistory() {
if(_snapshot) {
pushUrl(_snapshot.newUrl, currentUrl(), _snapshot.oldHtml, _snapshot.yOffset);
_snapshot = null;
}
}
function pushUrl(newUrl, originalUrl, originalHtml, yOffset) {
var historyEntry = makeHistoryEntry(originalHtml, yOffset, originalUrl);
history.replaceState({"ic-id": historyEntry.id}, "", "");
var t = getTargetForHistory($('body'));
var restorationData = makeHistoryEntry(t.html(), window.pageYOffset, newUrl);
history.pushState({'ic-id': restorationData.id}, "", newUrl);
t.trigger("pushUrl.ic", [t, restorationData]);
}
function handleHistoryNavigation(event) {
var data = event.state;
if (data && data['ic-id']) {
var historyData = JSON.parse(storage.getItem(data['ic-id']));
if (historyData) {
processICResponse(historyData["content"], getTargetForHistory($('body')), true);
if(historyData["yOffset"]) {
window.scrollTo(0, historyData["yOffset"])
}
return true;
} else {
$.get(currentUrl(), {'ic-restore-history' : true}, function(data, status){
var newDoc = createDocument(data);
var replacementHtml = getTargetForHistory(newDoc).html();
processICResponse(replacementHtml, getTargetForHistory($('body')), true);
});
}
}
return false;
}
function getTargetForHistory(elt) {
var explicitHistoryTarget = elt.find('[ic-history-elt]');
if (explicitHistoryTarget.length > 0) {
return explicitHistoryTarget;
} else {
return elt;
}
}
function snapshotForHistory(newUrl) {
var t = getTargetForHistory($('body'));
t.trigger("beforeHistorySnapshot.ic", [t]);
_snapshot = {
newUrl: newUrl,
oldHtml: t.html(),
yOffset : window.pageYOffset
}
}
function dumpLocalStorage() {
var str = "";
var keys = [];
for (var x in storage) {
keys.push(x);
}
keys.sort();
var total = 0;
for (var i in keys) {
var size = (storage[keys[i]].length * 2);
total += size;
str += keys[i] + "=" + (size / 1024 / 1024).toFixed(2) + " MB\n";
}
return str + "\nTOTAL LOCAL STORAGE: " + (total / 1024 / 1024).toFixed(2) + " MB";
}
function supportData() {
return historySupportData;
}
/* API */
return {
clearHistory : clearHistory,
updateHistory : updateHistory,
addPopStateHandler: addPopStateHandler,
snapshotForHistory: snapshotForHistory,
_internal : {
addPopStateHandler: addPopStateHandler,
supportData: supportData,
dumpLocalStorage: dumpLocalStorage,
updateLRUList: updateLRUList
}
}
}
function getSlotLimit() {
return 20;
}
function refresh(val) {
if (typeof val == 'string' || val instanceof String) {
refreshDependencies(val);
} else {
fireICRequest(val);
}
return Intercooler;
}
var _history = newIntercoolerHistory(localStorage, window.history, getSlotLimit(), .1);
//============================================================
// Local references transport
//============================================================
$.ajaxTransport("text", function (options, origOptions) {
if (origOptions.url[0] == "#") {
var ltAttr = "ic-local-";
var src = $(origOptions.url);
var rsphdr = [];
var status = 200;
var statusText = "OK";
src.each(function (i, el) {
$.each(el.attributes, function (j, attr) {
if (attr.name.substr(0, ltAttr.length) == ltAttr) {
var lhName = attr.name.substring(ltAttr.length);
if (lhName == "status") {
var statusLine = attr.value.match(/(\d+)\s?(.*)/);
if (statusLine != null) {
status = statusLine[1];
statusText = statusLine[2];
} else {
status = "500";
statusText = "Attribute Error";
}
} else {
rsphdr.push(lhName + ": " + attr.value);
}
}
});
});
var rsp = src.length > 0 ? src.html() : "";
return {
send: function (reqhdr, completeCallback) {
completeCallback(status, statusText, {html: rsp}, rsphdr.join("\n"));
},
abort: function () {
}
}
} else {
return null;
}
}
);
//============================================================
// Bootstrap
//============================================================
function init() {
var elt = $('body');
processNodes(elt);
fireReadyStuff(elt);
_history.addPopStateHandler(window);
if (location.search && location.search.indexOf("ic-launch-debugger=true") >= 0) {
Intercooler.debug();
}
}
$(function () {
init();
});
/* ===================================================
* API
* =================================================== */
return {
refresh: refresh,
history: _history,
triggerRequest: fireICRequest,
processNodes: processNodes,
closestAttrValue: closestAttrValue,
verbFor: verbFor,
isDependent: isDependent,
getTarget: getTarget,
ready : function(readyHandler) {
_readyHandlers.push(readyHandler);
},
debug: function () {
var debuggerUrl = closestAttrValue('body', 'ic-debugger-url') ||
"https://intercoolerreleases-leaddynocom.netdna-ssl.com/intercooler-debugger.js";
$.getScript(debuggerUrl)
.fail(function (jqxhr, settings, exception) {
log($('body'), formatError(exception), "ERROR");
});
},
_internal : {
init:init
},
/* ===================================================
* Deprecated API
* =================================================== */
defaultTransition: function () {
log($('body'), "This method is no longer supported. Transitions are now done via CSS", "ERROR");
},
defineTransition: function () {
log($('body'), "This method is no longer supported. Transitions are now done via CSS", "ERROR");
},
addURLHandler: function () {
log($('body'), "This method is no longer supported. Please use the jQuery mockjax plugin instead: https://github.com/jakerella/jquery-mockjax", "ERROR");
},
setRemote: function () {
log($('body'), "This method is no longer supported. Please use the jQuery mockjax plugin instead: https://github.com/jakerella/jquery-mockjax", "ERROR");
}
}
})();
|
const fs = require('fs');
const path = require('path');
const url = require('url');
const ServiceSettings = require('../service-settings');
class Service extends ServiceSettings {
constructor(pusshSettings) {
super(pusshSettings, 'local_transfer');
this.name = 'Local Filesystem';
this.description = 'Move screenshots to a directory other then the desktop';
this.settings = [
{
name: 'Location',
key: 'location',
type: 'text',
password: false,
default: '',
helpText: 'Move new screenshots to this directory'
}
];
this.loadSettings();
}
upload(file, callback) {
if (!this.getSetting('location')) return callback(new Error('No location configured'));
const newFile = path.join(this.getSetting('location'), path.basename(file));
fs.writeFileSync(newFile, fs.readFileSync(file));
callback(null, url.resolve('file://', newFile));
}
}
module.exports = Service;
|
var moment = require('moment');
var Q = require('q');
var Metric = require('../lib/metric');
var G = require('../global');
var topic_count = 50000;
var rcd_per_hour = 60;
var metric;
var topics = [];
function init (){
for (var i=0; i<topic_count; i++){
topics.push("system_" + (i+1).toString());
}
}
init();
function doWrite (){
var data = {};
metric.keys.forEach(function (key){
data[key.name] = Math.floor(Math.random()*1000000);
});
topics.forEach(function (topic){
G.getApp().append(topic, data, metric.name, Date.now());
});
console.log("[%s] Write %s topics(%s), %s records.",
moment().format("YYYY-MM-DD HH:mm:ss"),
topics.length,
metric.name,
topics.length * Object.keys(data).length);
}
function run (){
Q.fcall(function (){
return Q.Promise(function (resolve, reject){
Metric.find({"name":"metric_bench_1"}, function (err, results){
if (err)
reject(err);
else if(!results.length){
reject("metric_bench_1 not exist.");
}
else{
metric = results[0];
resolve();
}
})
})
}).then(function (){
doWrite();
setInterval(doWrite, 60*60*1000/rcd_per_hour);
}).catch(function (err){
console.error(err);
process.exit(1);
});
}
run(); |
/*!
* jQuery UI Button @VERSION
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/button/
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./jquery.ui.core",
"./jquery.ui.widget"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
var lastActive, startXPos, startYPos, clickDragged,
baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
formResetHandler = function() {
var form = $( this );
setTimeout(function() {
form.find( ":ui-button" ).button( "refresh" );
}, 1 );
},
radioGroup = function( radio ) {
var name = radio.name,
form = radio.form,
radios = $( [] );
if ( name ) {
name = name.replace( /'/g, "\\'" );
if ( form ) {
radios = $( form ).find( "[name='" + name + "']" );
} else {
radios = $( "[name='" + name + "']", radio.ownerDocument )
.filter(function() {
return !this.form;
});
}
}
return radios;
};
$.widget( "ui.button", {
version: "@VERSION",
defaultElement: "<button>",
options: {
disabled: null,
text: true,
label: null,
icons: {
primary: null,
secondary: null
}
},
_create: function() {
this.element.closest( "form" )
.unbind( "reset" + this.eventNamespace )
.bind( "reset" + this.eventNamespace, formResetHandler );
if ( typeof this.options.disabled !== "boolean" ) {
this.options.disabled = !!this.element.prop( "disabled" );
} else {
this.element.prop( "disabled", this.options.disabled );
}
this._determineButtonType();
this.hasTitle = !!this.buttonElement.attr( "title" );
var that = this,
options = this.options,
toggleButton = this.type === "checkbox" || this.type === "radio",
activeClass = !toggleButton ? "ui-state-active" : "";
if ( options.label === null ) {
options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
}
this._hoverable( this.buttonElement );
this.buttonElement
.addClass( baseClasses )
.attr( "role", "button" )
.bind( "mouseenter" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
if ( this === lastActive ) {
$( this ).addClass( "ui-state-active" );
}
})
.bind( "mouseleave" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
$( this ).removeClass( activeClass );
})
.bind( "click" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
event.preventDefault();
event.stopImmediatePropagation();
}
});
// Can't use _focusable() because the element that receives focus
// and the element that gets the ui-state-focus class are different
this._on({
focus: function() {
this.buttonElement.addClass( "ui-state-focus" );
},
blur: function() {
this.buttonElement.removeClass( "ui-state-focus" );
}
});
if ( toggleButton ) {
this.element.bind( "change" + this.eventNamespace, function() {
if ( clickDragged ) {
return;
}
that.refresh();
});
// if mouse moves between mousedown and mouseup (drag) set clickDragged flag
// prevents issue where button state changes but checkbox/radio checked state
// does not in Firefox (see ticket #6970)
this.buttonElement
.bind( "mousedown" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
return;
}
clickDragged = false;
startXPos = event.pageX;
startYPos = event.pageY;
})
.bind( "mouseup" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
return;
}
if ( startXPos !== event.pageX || startYPos !== event.pageY ) {
clickDragged = true;
}
});
}
if ( this.type === "checkbox" ) {
this.buttonElement.bind( "click" + this.eventNamespace, function() {
if ( options.disabled || clickDragged ) {
return false;
}
});
} else if ( this.type === "radio" ) {
this.buttonElement.bind( "click" + this.eventNamespace, function() {
if ( options.disabled || clickDragged ) {
return false;
}
$( this ).addClass( "ui-state-active" );
that.buttonElement.attr( "aria-pressed", "true" );
var radio = that.element[ 0 ];
radioGroup( radio )
.not( radio )
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
});
} else {
this.buttonElement
.bind( "mousedown" + this.eventNamespace, function() {
if ( options.disabled ) {
return false;
}
$( this ).addClass( "ui-state-active" );
lastActive = this;
that.document.one( "mouseup", function() {
lastActive = null;
});
})
.bind( "mouseup" + this.eventNamespace, function() {
if ( options.disabled ) {
return false;
}
$( this ).removeClass( "ui-state-active" );
})
.bind( "keydown" + this.eventNamespace, function(event) {
if ( options.disabled ) {
return false;
}
if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
$( this ).addClass( "ui-state-active" );
}
})
// see #8559, we bind to blur here in case the button element loses
// focus between keydown and keyup, it would be left in an "active" state
.bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
$( this ).removeClass( "ui-state-active" );
});
if ( this.buttonElement.is("a") ) {
this.buttonElement.keyup(function(event) {
if ( event.keyCode === $.ui.keyCode.SPACE ) {
// TODO pass through original event correctly (just as 2nd argument doesn't work)
$( this ).click();
}
});
}
}
this._setOption( "disabled", options.disabled );
this._resetButton();
},
_determineButtonType: function() {
var ancestor, labelSelector, checked;
if ( this.element.is("[type=checkbox]") ) {
this.type = "checkbox";
} else if ( this.element.is("[type=radio]") ) {
this.type = "radio";
} else if ( this.element.is("input") ) {
this.type = "input";
} else {
this.type = "button";
}
if ( this.type === "checkbox" || this.type === "radio" ) {
// we don't search against the document in case the element
// is disconnected from the DOM
ancestor = this.element.parents().last();
labelSelector = "label[for='" + this.element.attr("id") + "']";
this.buttonElement = ancestor.find( labelSelector );
if ( !this.buttonElement.length ) {
ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
this.buttonElement = ancestor.filter( labelSelector );
if ( !this.buttonElement.length ) {
this.buttonElement = ancestor.find( labelSelector );
}
}
this.element.addClass( "ui-helper-hidden-accessible" );
checked = this.element.is( ":checked" );
if ( checked ) {
this.buttonElement.addClass( "ui-state-active" );
}
this.buttonElement.prop( "aria-pressed", checked );
} else {
this.buttonElement = this.element;
}
},
widget: function() {
return this.buttonElement;
},
_destroy: function() {
this.element
.removeClass( "ui-helper-hidden-accessible" );
this.buttonElement
.removeClass( baseClasses + " ui-state-active " + typeClasses )
.removeAttr( "role" )
.removeAttr( "aria-pressed" )
.html( this.buttonElement.find(".ui-button-text").html() );
if ( !this.hasTitle ) {
this.buttonElement.removeAttr( "title" );
}
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "disabled" ) {
this.widget().toggleClass( "ui-state-disabled", !!value );
this.element.prop( "disabled", !!value );
if ( value ) {
this.buttonElement.removeClass( "ui-state-focus" );
}
return;
}
this._resetButton();
},
refresh: function() {
//See #8237 & #8828
var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );
if ( isDisabled !== this.options.disabled ) {
this._setOption( "disabled", isDisabled );
}
if ( this.type === "radio" ) {
radioGroup( this.element[0] ).each(function() {
if ( $( this ).is( ":checked" ) ) {
$( this ).button( "widget" )
.addClass( "ui-state-active" )
.attr( "aria-pressed", "true" );
} else {
$( this ).button( "widget" )
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
}
});
} else if ( this.type === "checkbox" ) {
if ( this.element.is( ":checked" ) ) {
this.buttonElement
.addClass( "ui-state-active" )
.attr( "aria-pressed", "true" );
} else {
this.buttonElement
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
}
}
},
_resetButton: function() {
if ( this.type === "input" ) {
if ( this.options.label ) {
this.element.val( this.options.label );
}
return;
}
var buttonElement = this.buttonElement.removeClass( typeClasses ),
buttonText = $( "<span></span>", this.document[0] )
.addClass( "ui-button-text" )
.html( this.options.label )
.appendTo( buttonElement.empty() )
.text(),
icons = this.options.icons,
multipleIcons = icons.primary && icons.secondary,
buttonClasses = [];
if ( icons.primary || icons.secondary ) {
if ( this.options.text ) {
buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
}
if ( icons.primary ) {
buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
}
if ( icons.secondary ) {
buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
}
if ( !this.options.text ) {
buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );
if ( !this.hasTitle ) {
buttonElement.attr( "title", $.trim( buttonText ) );
}
}
} else {
buttonClasses.push( "ui-button-text-only" );
}
buttonElement.addClass( buttonClasses.join( " " ) );
}
});
$.widget( "ui.buttonset", {
version: "@VERSION",
options: {
items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
},
_create: function() {
this.element.addClass( "ui-buttonset" );
},
_init: function() {
this.refresh();
},
_setOption: function( key, value ) {
if ( key === "disabled" ) {
this.buttons.button( "option", key, value );
}
this._super( key, value );
},
refresh: function() {
var rtl = this.element.css( "direction" ) === "rtl";
this.buttons = this.element.find( this.options.items )
.filter( ":ui-button" )
.button( "refresh" )
.end()
.not( ":ui-button" )
.button()
.end()
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
.filter( ":first" )
.addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
.end()
.filter( ":last" )
.addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
.end()
.end();
},
_destroy: function() {
this.element.removeClass( "ui-buttonset" );
this.buttons
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-corner-left ui-corner-right" )
.end()
.button( "destroy" );
}
});
}));
|
var Backbone = require("backbone");
var _ = require("underscore");
var Models = require("./models");
//var UndoManager = require("backbone-undo");
function get_author(){
return window.preferences.author || "";
}
var BaseView = Backbone.View.extend({
display_load:function(message, callback){
var self = this;
if(message.trim()!=""){
var load = '<div id="loading_modal" class="text-center fade">' +
'<div id="kolibri_load_gif"></div>' +
'<h4 id="kolibri_load_text" class="text-center">' + message + '</h4>' +
'</div>';
$(load).appendTo('body');
}
if(callback){
var promise = new Promise(function(resolve, reject){
callback(resolve, reject);
});
promise.then(function(){
if(message.trim()!=""){
$("#loading_modal").remove();
}
}).catch(function(error){
if(message!=""){
$("#kolibri_load_text").text("Error with asynchronous call. Please refresh the page");
}
console.log("Error with asynchronous call", error);
});
}else{
$("#loading_modal").remove();
}
},
reload_ancestors:function(collection, include_collection){
include_collection = include_collection==null || include_collection;
var list_to_reload = (include_collection) ? collection.pluck("id") : [];
var self = this;
collection.forEach(function(entry){
$.merge(list_to_reload, entry.get("ancestors"));
});
if(window.current_channel.get("main_tree")){
list_to_reload.push(window.current_channel.get("main_tree").id)
}
this.retrieve_nodes($.unique(list_to_reload), true).then(function(fetched){
fetched.forEach(function(model){
var object = window.workspace_manager.get(model.get("id"));
if(object){
if(object.node) object.node.reload(model);
if(object.list) object.list.set_root_model(model);
}
if(model.id === window.current_channel.get("main_tree").id){
window.current_channel.set('main_tree', model.toJSON());
self.check_if_published(model);
window.workspace_manager.get_main_view().handle_checked();
}
if(model.id === window.current_user.get('clipboard_tree').id){
window.current_user.set('clipboard_tree', model.toJSON());
}
});
});
},
retrieve_nodes:function(ids, force_fetch){
force_fetch = (force_fetch)? true:false;
return window.channel_router.nodeCollection.get_all_fetch(ids, force_fetch);
},
fetch_model:function(model){
return new Promise(function(resolve, reject){
model.fetch({
success: resolve,
error: reject
});
});
},
check_if_published:function(root){
var is_published = root.get("published");
$("#hide-if-unpublished").css("display", (is_published) ? "inline-block" : "none");
if(root.get("metadata").has_changed_descendant){
$("#channel-publish-button").prop("disabled", false);
$("#channel-publish-button").text("PUBLISH");
$("#channel-publish-button").removeClass("disabled");
}else{
$("#channel-publish-button").prop("disabled", true);
$("#channel-publish-button").text("No changes detected");
$("#channel-publish-button").addClass("disabled");
}
},
cancel_actions:function(event){
event.preventDefault();
event.stopPropagation();
if(window.workspace_manager.get_main_view()){
window.workspace_manager.get_main_view().close_all_popups();
}
},
});
var BaseWorkspaceView = BaseView.extend({
lists: [],
bind_workspace_functions:function(){
_.bindAll(this, 'reload_ancestors','publish' , 'edit_permissions', 'handle_published', 'handle_move', 'handle_changed_settings',
'edit_selected', 'add_to_trash', 'add_to_clipboard', 'get_selected', 'cancel_actions', 'delete_items_permanently');
},
publish:function(){
if(!$("#channel-publish-button").hasClass("disabled")){
var Exporter = require("edit_channel/export/views");
var exporter = new Exporter.ExportModalView({
model: window.current_channel.get_root("main_tree"),
onpublish: this.handle_published
});
}
},
activate_channel: function(){
var dialog = require("edit_channel/utils/dialog");
var original_resource_count = window.current_channel.get('main_tree').metadata.resource_count;
var original_topic_count = window.current_channel.get('main_tree').metadata.total_count - original_resource_count;
var staged_resource_count = window.current_channel.get('staging_tree').metadata.resource_count;
var staged_topic_count = window.current_channel.get('staging_tree').metadata.total_count - staged_resource_count;
dialog.dialog("Deploy Channel?", "Deploying this topic tree will replace the live topic tree (" +
+ original_topic_count + " topics, " + original_resource_count + " resources) with this staged topic tree (" +
+ staged_topic_count + " topics, " + staged_resource_count + " resources). Are you sure you want to deploy this updated topic tree?", {
'View Summary': function(){
var treeViews = require('edit_channel/tree_edit/views');
new treeViews.DiffModalView();
},
'Keep Reviewing': function(){},
'Deploy': function(){
window.current_channel.activate_channel().then(function(){
window.location.href = '/channels/' + window.current_channel.id + '/edit';
}).catch(function(error){
dialog.alert("Channel not approved", error);
});
}
}, null);
},
handle_published:function(collection){
this.reload_ancestors(collection);
var staticModal = require('edit_channel/information/views');
new staticModal.PublishedModalView({channel_id: window.current_channel.id});
},
edit_permissions:function(){
var ShareViews = require("edit_channel/share/views");
var share_view = new ShareViews.ShareModalView({
model:window.current_channel,
current_user: window.current_user
});
},
edit_selected:function(allow_edit){
var UploaderViews = require("edit_channel/uploader/views");
var list = this.get_selected();
var edit_collection = new Models.ContentNodeCollection();
/* Create list of nodes to edit */
for(var i = 0; i < list.length; i++){
var model = list[i].model;
model.view = list[i];
edit_collection.add(model);
}
$("#main-content-area").append("<div id='dialog'></div>");
var content = null;
if(edit_collection.length ==1){
content = edit_collection.models[0];
}
var metadata_view = new UploaderViews.MetadataModalView({
collection: edit_collection,
el: $("#dialog"),
model: content,
new_content: false,
onsave: this.reload_ancestors,
allow_edit: allow_edit
});
},
add_to_trash:function(collection, message){
message = (message!=null)? message: "Archiving Content...";
var self = this;
var promise = new Promise(function(resolve, reject){
self.display_load(message, function(resolve_load, reject_load){
var reloadCollection = collection.clone();
var trash_node = window.current_channel.get_root("trash_tree");
collection.move(trash_node, trash_node.get("metadata").max_sort_order).then(function(){
self.reload_ancestors(reloadCollection, false);
trash_node.fetch({
success:function(fetched){
window.current_channel.set("trash_tree", fetched.attributes)
resolve(collection);
resolve_load(true);
}
})
});
});
});
return promise;
},
add_to_clipboard:function(collection, message){
message = (message!=null)? message: "Moving to Clipboard...";
return this.move_to_queue_list(collection, window.workspace_manager.get_queue_view().clipboard_queue, message);
},
move_to_queue_list:function(collection, list_view, message){
message = (message!=null)? message: "Moving Content...";
var self = this;
var promise = new Promise(function(resolve, reject){
self.display_load(message, function(resolve_load, reject_load){
var reloadCollection = collection.clone();
collection.move(list_view.model, list_view.model.get("metadata").max_sort_order).then(function(){
list_view.add_nodes(collection);
self.reload_ancestors(reloadCollection, false);
resolve(collection);
resolve_load(true);
});
});
});
return promise;
},
get_selected:function(exclude_descendants){
var selected_list = [];
// Use for loop to break if needed
for(var i = 0; i < this.lists.length; ++i){
selected_list = $.merge(selected_list, this.lists[i].get_selected());
if(exclude_descendants && selected_list.length > 0){
break;
}
}
return selected_list;
},
open_archive:function(){
var ArchiveView = require("edit_channel/archive/views");
window.current_channel.get_root("trash_tree").fetch({
success:function(fetched){
window.current_channel.set("trash_tree", fetched.attributes);
var archive = new ArchiveView.ArchiveModalView({
model : fetched
});
}
});
},
move_content:function(move_collection){
var MoveView = require("edit_channel/move/views");
var list = this.get_selected(true);
var move_collection = new Models.ContentNodeCollection(_.pluck(list, 'model'));
$("#main-content-area").append("<div id='dialog'></div>");
var move = new MoveView.MoveModalView({
collection: move_collection,
el: $("#dialog"),
onmove: this.handle_move,
model: window.current_channel.get_root("main_tree")
});
},
handle_move:function(target, moved, original_parents){
var reloadCollection = new Models.ContentNodeCollection();
reloadCollection.add(original_parents.models);
reloadCollection.add(moved.models);
// Remove where nodes originally were
moved.forEach(function(node){ window.workspace_manager.remove(node.id)});
// Add nodes to correct place
var content = window.workspace_manager.get(target.id);
if(content && content.list)
content.list.add_nodes(moved);
// Recalculate counts
this.reload_ancestors(original_parents, true);
},
delete_items_permanently:function(message, list, callback){
message = (message!=null)? message: "Deleting...";
var self = this;
this.display_load(message, function(resolve_load, reject_load){
var promise_list = [];
var reload = new Models.ContentNodeCollection();
for(var i = 0; i < list.length; i++){
var view = list[i];
if(view){
promise_list.push(new Promise(function(resolve, reject){
reload.add(view.model);
if(view.containing_list_view){
reload.add(view.containing_list_view.model);
}
view.model.destroy({
success:function(data){
window.workspace_manager.remove(data.id);
resolve(data);
},
error:function(obj, error){
reject(error);
}
});
}));
}
}
Promise.all(promise_list).then(function(){
self.lists.forEach(function(list){
list.handle_if_empty();
})
self.reload_ancestors(reload, true);
if(callback){
callback();
}
resolve_load("Success!");
}).catch(function(error){
reject_load(error);
});
});
},
open_channel_settings: function(){
var settings = require('edit_channel/channel_settings/views');
new settings.SettingsModalView({
model: window.current_channel,
onsave: this.handle_changed_settings
});
},
handle_changed_settings: function(data){
$("#channel_selection_dropdown").text(data.get('name'));
window.workspace_manager.get_main_view().model.set('title', data.get('name'));
window.preferences = data.get('preferences');
}
});
var BaseModalView = BaseView.extend({
callback:null,
render: function(closeFunction, renderData) {
this.$el.html(this.template(renderData));
$("body").append(this.el);
this.$(".modal").modal({show: true});
this.$(".modal").on("hide.bs.modal", closeFunction);
},
close: function() {
if(this.modal){
this.$(".modal").modal('hide');
}
this.remove();
},
closed_modal:function(){
$("body").addClass('modal-open'); //Make sure modal-open class persists
$('.modal-backdrop').slice(1).remove();
this.remove();
}
});
var BaseListView = BaseView.extend({
/* Properties to overwrite */
collection : null, //Collection to be used for data
template:null,
list_selector:null,
default_item:null,
selectedClass: "content-selected",
item_class_selector:null,
/* Functions to overwrite */
create_new_view: null,
views: [], //List of item views to help with garbage collection
bind_list_functions:function(){
_.bindAll(this, 'load_content', 'close', 'handle_if_empty', 'check_all', 'get_selected',
'set_root_model', 'update_views', 'cancel_actions');
},
set_root_model:function(model){
this.model.set(model.toJSON());
},
update_views:function(){
this.retrieve_nodes(this.model.get("children"), true).then(this.load_content);
},
load_content: function(collection, default_text){
collection = (collection)? collection : this.collection;
default_text = (default_text)? default_text : "No items found."
this.views = [];
var default_element = this.$(this.default_item);
default_element.text(default_text);
this.$(this.list_selector).html("").append(default_element);
var self = this;
collection.forEach(function(entry){
var item_view = self.create_new_view(entry);
self.$(self.list_selector).append(item_view.el);
});
this.handle_if_empty();
},
handle_if_empty:function(){
this.$(this.default_item).css("display", (this.views.length > 0) ? "none" : "block");
},
check_all :function(event){
var is_checked = (event) ? event.currentTarget.checked : true;
this.$el.find(":checkbox").prop("checked", is_checked);
this.recurse_check_all(this.views);
},
recurse_check_all:function(views){
var self = this;
views.forEach(function(view){
view.handle_checked();
if(view.subcontent_view){
self.recurse_check_all(view.subcontent_view.views);
}
})
},
get_selected: function(){
var selected_views = [];
this.views.forEach(function(view){
if(view.checked){
selected_views.push(view);
}else if(view.subcontent_view){
selected_views = _.union(selected_views, view.subcontent_view.get_selected());
}
})
return selected_views;
},
close: function(){
this.remove();
}
});
var BaseEditableListView = BaseListView.extend({
collection : null, //Collection to be used for data
template:null,
list_selector:null,
default_item:null,
selectedClass: "content-selected",
item_class_selector:null,
/* Functions to overwrite */
create_new_view: null,
views: [], //List of item views to help with garbage collection
bind_edit_functions:function(){
this.bind_list_functions();
_.bindAll(this, 'create_new_item', 'reset', 'save','delete');
},
create_new_item: function(newModelData, appendToList, message){
appendToList = (appendToList)? appendToList : false;
message = (message!=null)? message: "Creating...";
var self = this;
var promise = new Promise(function(resolve, reject){
self.display_load(message, function(resolve_load, reject_load){
self.collection.create(newModelData, {
success:function(newModel){
var new_view = self.create_new_view(newModel);
if(appendToList){
self.$(self.list_selector).append(new_view.el);
}
self.handle_if_empty();
resolve(new_view);
resolve_load(true);
},
error:function(obj, error){
console.log("ERROR:", error);
reject(error);
reject_load(error);
}
});
});
});
return promise;
},
reset: function(){
this.views.forEach(function(entry){
entry.model.unset();
});
},
save:function(message, beforeSave){
message = (message!=null)? message: "Saving...";
var self = this;
var promise = new Promise(function(resolve, reject){
self.display_load(message, function(load_resolve, load_reject){
if(beforeSave){
beforeSave();
}
self.collection.save().then(function(collection){
resolve(collection);
load_resolve(true);
}).catch(function(error){
load_reject(error);
});
});
})
return promise;
},
delete_items_permanently:function(message){
message = (message!=null)? message: "Deleting...";
var self = this;
this.display_load(message, function(resolve_load, reject_load){
var list = self.get_selected();
var promise_list = [];
for(var i = 0; i < list.length; i++){
var view = list[i];
if(view){
promise_list.push(new Promise(function(resolve, reject){
view.model.destroy({
success:function(data){
resolve(data);
},
error:function(obj, error){
reject(error);
}
});
self.collection.remove(view.model);
self.views.splice(view,1);
view.remove();
}));
}
}
Promise.all(promise_list).then(function(){
self.handle_if_empty();
resolve_load("Success!");
}).catch(function(error){
reject_load(error);
});
});
},
delete:function(view){
this.collection.remove(view.model);
this.views = _.reject(this.views, function(el) { return el.model.id === view.model.id; });
this.handle_if_empty();
// this.update_views();
},
delete_items_permanently:function(message){
message = (message!=null)? message: "Deleting...";
var self = this;
this.display_load(message, function(resolve_load, reject_load){
var list = self.get_selected();
var promise_list = [];
for(var i = 0; i < list.length; i++){
var view = list[i];
if(view){
promise_list.push(new Promise(function(resolve, reject){
view.model.destroy({
success:function(data){
resolve(data);
},
error:function(obj, error){
reject(error);
}
});
self.collection.remove(view.model);
self.views.splice(view,1);
view.remove();
}));
}
}
Promise.all(promise_list).then(function(){
self.handle_if_empty();
resolve_load("Success!");
}).catch(function(error){
reject_load(error);
});
});
},
remove_view:function(view){
this.views = _.reject(this.views, function(v){ return v.cid === view.cid; })
}
});
var BaseWorkspaceListView = BaseEditableListView.extend({
/* Properties to overwrite */
collection : null, //Collection to be used for data
item_view: null,
template:null,
list_selector:null,
default_item:null,
content_node_view:null,
/* Functions to overwrite */
create_new_view:null,
views: [], //List of item views to help with garbage collection
bind_workspace_functions: function(){
this.bind_edit_functions();
_.bindAll(this, 'copy_selected', 'delete_selected', 'add_topic','add_nodes', 'drop_in_container','handle_drop', 'refresh_droppable',
'import_content', 'add_files', 'add_to_clipboard', 'add_to_trash','make_droppable', 'copy_collection', 'add_exercise');
},
copy_selected:function(){
var list = this.get_selected();
var copyCollection = new Models.ContentNodeCollection();
for(var i = 0; i < list.length; i++){
copyCollection.add(list[i].model);
}
return this.copy_collection(copyCollection);
},
copy_collection:function(copyCollection){
var clipboard = window.workspace_manager.get_queue_view();
clipboard.open_queue();
return copyCollection.duplicate(clipboard.clipboard_queue.model);
},
delete_selected:function(){
var list = this.get_selected();
var deleteCollection = new Models.ContentNodeCollection();
for(var i = 0; i < list.length; i++){
var view = list[i];
if(view){
deleteCollection.add(view.model);
view.remove();
}
}
this.add_to_trash(deleteCollection, "Deleting Content...");
},
make_droppable:function(){
var DragHelper = require("edit_channel/utils/drag_drop");
DragHelper.addSortable(this, this.selectedClass, this.drop_in_container);
},
refresh_droppable:function(){
var self = this;
setTimeout(function(){
$( self.list_selector ).sortable( "enable" );
$( self.list_selector ).sortable( "refresh" );
}, 100);
},
drop_in_container:function(moved_item, selected_items, orders){
var self = this;
return new Promise(function(resolve, reject){
if(_.contains(orders, moved_item)){
self.handle_drop(selected_items).then(function(collection){
var ids = collection.pluck('id');
var pivot = orders.indexOf(moved_item);
var min = _.chain(orders.slice(0, pivot))
.reject(function(item) { return _.contains(ids, item.id); })
.map(function(item) { return item.get('sort_order'); })
.max().value();
var max = _.chain(orders.slice(pivot, orders.length))
.reject(function(item) { return _.contains(ids, item.id); })
.map(function(item) { return item.get('sort_order'); })
.min().value();
min = _.isFinite(min)? min : 0;
max = _.isFinite(max)? max : min + (selected_items.length * 2);
var reload_list = [];
var last_elem = $("#" + moved_item.id);
collection.forEach(function(node){
reload_list.push(node.get("id"));
if(node.get("parent") !== self.model.get("id")){
reload_list.push(node.get("parent"));
}
var to_delete = $("#" + node.id);
var item_view = self.create_new_view(node);
last_elem.after(item_view.el);
last_elem = item_view.$el;
to_delete.remove();
});
collection.move(self.model, max, min).then(function(savedCollection){
self.retrieve_nodes($.unique(reload_list), true).then(function(fetched){
self.container.handle_move(self.model, savedCollection, fetched);
resolve(true);
});
}).catch(function(error){
var dialog = require("edit_channel/utils/dialog");
dialog.alert("Error Moving Content", error.responseText, function(){
$(".content-list").sortable( "cancel" );
$(".content-list").sortable( "enable" );
$(".content-list").sortable( "refresh" );
// Revert back to original positions
self.retrieve_nodes($.unique(reload_list), true).then(function(fetched){
self.reload_ancestors(fetched);
self.render();
});
});
});
});
}
});
},
handle_drop:function(collection){
this.$(this.default_item).css("display", "none");
var promise = new Promise(function(resolve, reject){
resolve(collection);
});
return promise;
},
add_nodes:function(collection){
var self = this;
collection.forEach(function(entry){
var new_view = self.create_new_view(entry);
self.$(self.list_selector).append(new_view.el);
});
this.model.set('children', this.model.get('children').concat(collection.pluck('id')));
this.reload_ancestors(collection, false);
this.handle_if_empty();
},
add_topic: function(){
var UploaderViews = require("edit_channel/uploader/views");
var self = this;
this.collection.create_new_node({
"kind":"topic",
"title": (this.model.get('parent'))? this.model.get('title') + " Topic" : "Topic",
"author": get_author(),
}).then(function(new_topic){
var edit_collection = new Models.ContentNodeCollection([new_topic]);
$("#main-content-area").append("<div id='dialog'></div>");
var metadata_view = new UploaderViews.MetadataModalView({
el : $("#dialog"),
collection: edit_collection,
model: self.model,
new_content: true,
new_topic: true,
onsave: self.reload_ancestors,
onnew:self.add_nodes,
allow_edit: true
});
});
},
import_content:function(){
var Import = require("edit_channel/import/views");
var import_view = new Import.ImportModalView({
modal: true,
onimport: this.add_nodes,
model: this.model
});
},
add_files:function(){
var FileUploader = require("edit_channel/file_upload/views");
this.file_upload_view = new FileUploader.FileModalView({
parent_view: this,
model:this.model,
onsave: this.reload_ancestors,
onnew:this.add_nodes
});
},
add_to_clipboard:function(collection, message){
message = (message!=null)? message: "Moving to Clipboard...";
var self = this;
this.container.add_to_clipboard(collection, message).then(function(){
self.handle_if_empty();
});
},
add_to_trash:function(collection, message){
message = (message!=null)? message: "Deleting Content...";
var self = this;
this.container.add_to_trash(collection, message).then(function(){
self.handle_if_empty();
});
},
add_exercise:function(){
var UploaderViews = require("edit_channel/uploader/views");
var self = this;
this.collection.create_new_node({
"kind":"exercise",
"title": (this.model.get('parent'))? this.model.get('title') + " Exercise" : "Exercise", // Avoid having exercises prefilled with 'email clipboard'
"author": get_author(),
"copyright_holder": (window.preferences.copyright_holder === null) ? get_author() : window.preferences.copyright_holder,
"license_name": window.preferences.license,
"license_description": (window.preferences.license_description && window.preferences.license==="Special Permissions") ? window.preferences.license_description : ""
}).then(function(new_exercise){
var edit_collection = new Models.ContentNodeCollection([new_exercise]);
$("#main-content-area").append("<div id='dialog'></div>");
var metadata_view = new UploaderViews.MetadataModalView({
el : $("#dialog"),
collection: edit_collection,
model: self.model,
new_content: true,
new_exercise: true,
onsave: self.reload_ancestors,
onnew:self.add_nodes,
allow_edit: true
});
});
}
});
var BaseListItemView = BaseView.extend({
containing_list_view:null,
template:null,
id:null,
className:null,
model: null,
tagName: "li",
selectedClass: null,
checked : false,
bind_list_functions:function(){
_.bindAll(this, 'handle_checked', 'cancel_actions');
},
handle_checked:function(){
this.checked = this.$el.find(">input[type=checkbox]").is(":checked");
(this.checked)? this.$el.addClass(this.selectedClass) : this.$el.removeClass(this.selectedClass);
},
});
var BaseListEditableItemView = BaseListItemView.extend({
containing_list_view:null,
originalData: null,
bind_edit_functions:function(){
_.bindAll(this, 'set','unset','save','delete','reload');
this.bind_list_functions();
},
set:function(data){
if(this.model){
this.model.set(data);
}
},
unset:function(){
this.model.set(this.originalData);
},
save:function(data, message){
message = (message!=null)? message: "Saving...";
var self = this;
var promise = new Promise(function(resolve, reject){
self.originalData = data;
if(self.model.isNew()){
self.containing_list_view.create_new_item(data).then(function(newView){
resolve(newView.model);
}).catch(function(error){
console.log("ERROR (edit_channel: save):", error);
reject(error);
});
}else{
self.display_load(message, function(resolve_load, reject_load){
self.model.save(data,{
patch:true,
success:function(savedModel){
resolve(savedModel);
resolve_load(true);
},
error:function(obj, error){
console.log("ERROR:", error);
reject(error);
reject_load(error);
}
});
});
}
});
return promise;
},
delete:function(destroy_model, message, callback){
message = (message!=null)? message: "Deleting...";
var self = this;
if(destroy_model){
this.display_load(message, function(resolve_load, reject_load){
self.containing_list_view.delete(self);
var model_id = self.model.id;
self.model.destroy({
success:function(){
window.workspace_manager.remove(model_id);
if(self.containing_list_view){
var reload = new Models.ContentNodeCollection();
reload.add(self.containing_list_view.model);
self.reload_ancestors(reload);
}
if(callback){
callback();
}
resolve_load(true);
},
error:function(obj, error){
reject_load(error);
}
});
});
}
},
reload:function(model){
this.model.set(model.attributes);
this.render();
}
});
var BaseListNodeItemView = BaseListEditableItemView.extend({
containing_list_view:null,
originalData: null,
template:null,
id:null,
className:null,
model: null,
tagName: "li",
selectedClass: null,
expandedClass: null,
collapsedClass: null,
getToggler: null,
getSubdirectory: null,
load_subfiles:null,
bind_node_functions: function(){
_.bindAll(this, 'toggle','open_folder','close_folder');
this.bind_edit_functions();
},
toggle:function(event){
this.cancel_actions(event);
(this.getToggler().hasClass(this.collapsedClass)) ? this.open_folder() : this.close_folder();
if(this.container){
var containing_element = this.container.$el.find(this.list_selector);
containing_element.scrollLeft(containing_element.width());
}
},
open_folder:function(open_speed){
open_speed = (open_speed)? open_speed: 200;
this.getSubdirectory().slideDown(open_speed);
if(!this.subcontent_view){
this.load_subfiles();
}
this.getToggler().removeClass(this.collapsedClass).addClass(this.expandedClass);
},
close_folder:function(close_speed){
close_speed = (close_speed)? close_speed: 200;
this.getSubdirectory().slideUp(close_speed);
this.getToggler().removeClass(this.expandedClass).addClass(this.collapsedClass);
}
});
var BaseWorkspaceListNodeItemView = BaseListNodeItemView.extend({
containing_list_view:null,
originalData: null,
template:null,
id:null,
className:null,
model: null,
tagName: "li",
selectedClass: "content-selected",
bind_workspace_functions:function(){
this.bind_node_functions();
_.bindAll(this, 'copy_item', 'open_preview', 'open_edit', 'handle_drop',
'handle_checked', 'add_to_clipboard', 'add_to_trash', 'make_droppable',
'add_nodes', 'add_topic', 'open_move', 'handle_move');
},
make_droppable:function(){
// Temporarily disable dropping onto topics for now
// if(this.model.get("kind") === "topic"){
// var DragHelper = require("edit_channel/utils/drag_drop");
// DragHelper.addTopicDragDrop(this, this.open_folder, this.handle_drop);
// }
},
open_preview:function(){
var Previewer = require("edit_channel/preview/views");
$("#main-content-area").append("<div id='dialog'></div>");
var data={
el : $("#dialog"),
model: this.model,
}
new Previewer.PreviewModalView(data);
},
open_move:function(){
var MoveView = require("edit_channel/move/views");
var move_collection = new Models.ContentNodeCollection();
move_collection.add(this.model);
$("#main-content-area").append("<div id='dialog'></div>");
new MoveView.MoveModalView({
collection: move_collection,
el: $("#dialog"),
onmove: this.handle_move,
model: window.current_channel.get_root("main_tree")
});
},
handle_move:function(target, moved, original_parents){
// Recalculate counts
this.reload_ancestors(original_parents, true);
// Remove where node originally was
window.workspace_manager.remove(this.model.id)
// Add nodes to correct place
var content = window.workspace_manager.get(target.id);
if(content && content.list){
content.list.add_nodes(moved);
}
},
open_edit:function(allow_edit){
var UploaderViews = require("edit_channel/uploader/views");
$("#main-content-area").append("<div id='dialog'></div>");
var editCollection = new Models.ContentNodeCollection([this.model]);
var metadata_view = new UploaderViews.MetadataModalView({
collection: editCollection,
el: $("#dialog"),
new_content: false,
model: this.containing_list_view.model,
onsave: this.reload_ancestors,
allow_edit: allow_edit,
onnew: (!this.allow_edit)? this.containing_list_view.add_to_clipboard : null
});
},
handle_drop:function(models){
var self = this;
var promise = new Promise(function(resolve, reject){
var tempCollection = new Models.ContentNodeCollection();
var sort_order = self.model.get("metadata").max_sort_order;
var reload_list = [self.model.get("id")];
models.forEach(function(node){
reload_list.push(node.get("parent"));
reload_list.push(node.get("id"));
node.set({
sort_order: ++sort_order
});
tempCollection.add(node);
});
tempCollection.move(self.model.id).then(function(savedCollection){
self.retrieve_nodes(reload_list, true).then(function(fetched){
self.reload_ancestors(fetched);
resolve(true);
});
});
});
return promise;
},
add_to_trash:function(message){
message=(message!=null)? message: "Deleting Content...";
this.containing_list_view.add_to_trash(new Models.ContentNodeCollection([this.model]), message);
this.remove();
},
add_to_clipboard:function(message){
message=(message!=null)? message: "Moving to Clipboard...";
this.containing_list_view.add_to_clipboard(new Models.ContentNodeCollection([this.model]),message);
},
copy_item:function(message){
message=(message!=null)? message: "Copying to Clipboard...";
var copyCollection = new Models.ContentNodeCollection();
copyCollection.add(this.model);
var self = this;
this.display_load(message, function(resolve, reject){
self.containing_list_view.copy_collection(copyCollection).then(function(collection){
self.containing_list_view.add_to_clipboard(collection, "");
resolve(collection);
}).catch(function(error){reject(error);});
});
},
add_topic: function(){
var UploaderViews = require("edit_channel/uploader/views");
var self = this;
this.containing_list_view.collection.create_new_node({
"kind":"topic",
"title": (this.model.get('parent'))? this.model.get('title') + " Topic" : "Topic",
"sort_order" : this.model.get("metadata").max_sort_order,
"author": get_author(),
}).then(function(new_topic){
var edit_collection = new Models.ContentNodeCollection([new_topic]);
$("#main-content-area").append("<div id='dialog'></div>");
var metadata_view = new UploaderViews.MetadataModalView({
el : $("#dialog"),
collection: edit_collection,
model: self.model,
new_content: true,
new_topic: true,
onsave: self.reload_ancestors,
onnew:self.add_nodes,
allow_edit: true
});
});
},
add_nodes:function(collection){
var self = this;
if(this.subcontent_view){
this.subcontent_view.add_nodes(collection);
}else{
this.fetch_model(this.model).then(function(fetched){
self.reload(fetched);
});
}
}
});
module.exports = {
BaseView: BaseView,
BaseWorkspaceView:BaseWorkspaceView,
BaseModalView:BaseModalView,
BaseListView:BaseListView,
BaseEditableListView:BaseEditableListView,
BaseWorkspaceListView:BaseWorkspaceListView,
BaseListItemView:BaseListItemView,
BaseListNodeItemView:BaseListNodeItemView,
BaseListEditableItemView: BaseListEditableItemView,
BaseWorkspaceListNodeItemView:BaseWorkspaceListNodeItemView,
} |
'use strict';
class ExtendableError extends Error {
constructor (message, meta) {
super();
this.message = message;
this.stack = (new Error(message)).stack;
this.name = this.constructor.name;
Object.assign(this, meta);
}
}
exports.UnknownCRSError = class UnknownCRSError extends ExtendableError {
constructor (crs, meta) {
const m = `Unknown Coordinate Reference System: ${crs}`;
super(m, meta);
}
};
exports.UnknownCRSFormatError = class UnknownCRSFormatError extends ExtendableError {
constructor (format, meta) {
const m = `Unknown Coordinate Reference System format: ${format}`;
super(m, meta);
}
};
exports.InvalidResponseError = class InvalidResponseError extends ExtendableError {
constructor (statusCode, body, params, meta) {
const m = `Invalid Response Status Code: ${statusCode}`;
super(m, meta);
this.requestParams = params;
this.responseBody = body;
this.responseStatusCode = statusCode;
}
};
|
window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
workflow: [
{ handler: "silence", matchId: "ember-getowner-polyfill.import" },
{ handler: "silence", matchId: "ember-runtime.enumerable-contains" }
]
};
|
/*
* grunt-retro
* https://github.com/twolfson/grunt-retro
*
* Copyright (c) 2013 Todd Wolfson
* Licensed under the MIT license.
*/
var assert = require('assert');
module.exports = function (grunt) {
// Proxy registerTask
var registerTaskFn = grunt.registerTask;
grunt.registerTask = function (taskName, taskList, taskFn) {
// Capture arguments for manipulation
var args = [].slice.call(arguments);
// If there is no taskFn
if (!taskFn) {
// and if taskList is not an array
if (!Array.isArray(taskList)) {
args[1] = taskList.split(/\s+/g);
}
}
// Invoke the original function
return registerTaskFn.apply(this, args);
};
// Proxy registerMultiTask
var registerMultiFn = grunt.registerMultiTask;
grunt.registerMultiTask = function (taskName, description, taskFn) {
var args = [].slice.call(arguments);
// Wrap taskFn
args[2] = function proxiedTaskFn () {
// Fallback this.file
// this.file = this.file || this.files[0].orig;
var file = this.file;
if (!file) {
// Taken lovingly from https://github.com/gruntjs/grunt/blob/0.3-stable/lib/grunt/task.js#L79-L89
this.file = {};
// Handle data structured like either:
// 'prop': [srcfiles]
// {prop: {src: [srcfiles], dest: 'destfile'}}.
if (grunt.utils.kindOf(this.data) === 'object') {
if ('src' in this.data) { this.file.src = this.data.src; }
if ('dest' in this.data) { this.file.dest = this.data.dest; }
} else {
this.file.src = this.data;
// (except for this line)
// this.file.dest = target;
this.file.dest = this.target;
}
}
// Call the original function
return taskFn.apply(this, arguments);
};
// Call the original function
return registerMultiFn.apply(this, args);
};
// Fallback grunt.utils and grunt...minimatch
grunt.utils = grunt.utils || grunt.util;
grunt.file.glob.minimatch = grunt.file.glob.minimatch || grunt.file.minimatch;
// Set up storage for helpers
var helpers = {};
// Fallback helper helper
function helper(name) {
// Look up and assert the helper exists
var helperFn = helpers[name];
assert(helperFn, 'GRUNT HELPER: "' + name + '" could not be found.');
// Call the helper with the arguments
var args = [].slice.call(arguments, 1);
return helperFn.apply(this, args);
}
grunt.helper = grunt.helper || helper;
// Fallback registerHelper
function registerHelper(name, fn) {
helpers[name] = fn;
}
grunt.registerHelper = grunt.registerHelper || registerHelper;
// Return grunt for a fluent interface
return grunt;
};
|
// @flow
import type { FormProps } from 'react-redux';
import { Field } from 'redux-form';
import { RenderErrorMessage } from 'app/components/Form/Field';
import { legoForm, TextEditor, SelectInput } from 'app/components/Form';
import Button from 'app/components/Button';
import type { ID, EventPool, User } from 'app/models';
import { waitinglistPoolId } from 'app/actions/EventActions';
type Props = {
eventId: ID,
adminRegister: (ID, ID, ID, string, string) => Promise<*>,
pools: Array<EventPool>,
} & FormProps;
const AdminRegister = ({
eventId,
handleSubmit,
adminRegister,
pools,
invalid,
pristine,
submitting,
error,
}: Props) => {
return (
<div style={{ width: '400px' }}>
<form onSubmit={handleSubmit}>
<Field
placeholder="Begrunnelse"
label="Begrunnelse"
name="adminRegistrationReason"
component={TextEditor.Field}
/>
<Field
placeholder="Tilbakemelding"
label="Tilbakemelding"
name="feedback"
component={TextEditor.Field}
/>
<Field
name="pool"
component={SelectInput.Field}
placeholder="Pool"
label="Pool"
options={pools
.map((pool) => ({ value: pool.id, label: pool.name }))
.concat([{ value: waitinglistPoolId, label: 'Venteliste' }])}
simpleValue
/>
<Field
name="user"
component={SelectInput.AutocompleteField}
filter={['users.user']}
placeholder="Bruker"
label="Bruker"
/>
<RenderErrorMessage error={error} />
<Button type="submit" disabled={invalid || pristine || submitting}>
Registrer
</Button>
</form>
</div>
);
};
function validateForm(data) {
const errors = {};
if (!data.reason) {
errors.reason = 'Forklaring er påkrevet';
}
if (!data.pool) {
errors.pool = 'Pool er påkrevet';
}
if (!data.user) {
errors.user = 'Bruker er påkrevet';
}
return errors;
}
const onSubmit = (
{
user,
pool,
feedback,
adminRegistrationReason,
}: {
user: User,
pool: number,
feedback: string,
adminRegistrationReason: string,
},
dispatch,
{ reset, eventId, adminRegister }: Props
) =>
adminRegister(eventId, user.id, pool, feedback, adminRegistrationReason).then(
() => {
reset();
}
);
export default legoForm({
form: 'adminRegister',
validate: validateForm,
onSubmit,
})(AdminRegister);
|
$(document).on("click", ".search", postData);
$(document).on("keypress", function(e) {
if (e.keyCode === 13) {
postData();
}
});
$(document).on('input', '.js-range-input', function(e) {
$('.js-range-value').html(e.currentTarget.value);
});
function weightSimilarity(enteredWeight, weight) {
var absoluteDiff = Math.abs(enteredWeight - weight);
if (absoluteDiff <= 1.5) {
return "green"
}
else if (absoluteDiff <= 3) {
return "yellow"
}
else {
return "red"
}
};
$(document).on("click", ".clear-results", function() {
$(".red,.yellow,.green, .error").remove();
$(".peptide-weight").empty();
});
function postData(e) {
var enteredWeight = parseFloat($("input[name=weight]").val());
var wildcards = {
"(1X)": $("input[name='(1X)']").val(),
"(2X)": $("input[name='(2X)']").val(),
"(3X)": $("input[name='(3X)']").val(),
}
var mass_type = $(".mass-select select").val();
var enteredSequence = $("input[name=peptide_sequence]").val();
var tolerance = $(".js-range-input").val();
var data = {
peptide_sequence: enteredSequence,
weight: enteredWeight,
wildcards: wildcards,
mass_type: mass_type,
tolerance: tolerance,
};
var params = {
type: 'POST',
data: data,
url: '/possible-matches',
success: function(data) {
data = JSON.parse(data);
var seq_objs = data['possible_sequences'];
$(".peptide-weight").empty().append("<p>Expected [M+H]<span class='superscript'>+</span> is "+data['weight']+"</p>");
if (typeof seq_objs === "string") {
$(".result table").append("<tr><td class='error'>"+seq_objs+"</td></tr>");
return;
}
// Sort closest value to found mass at top.
var sequences = []
for (var k in seq_objs) {
sequences.push({'sequence': k, 'weight': seq_objs[k]});
}
sequences = sequences.sort(function(a, b) {
return Math.abs(a.weight - enteredWeight) - Math.abs(b.weight - enteredWeight);
});
$(".result table").empty();
sequences.forEach(function(match) {
var sequence = match.sequence;
var weight = match.weight;
var regex = /no matches found/i;
var color = (regex.test(sequence) && 'red') || weightSimilarity(enteredWeight, weight);
$(".result table").
append("<tr class="+color+">\
<td class='found-sequence'>"+sequence+"</td><td>"+weight+"</td></tr>");
});
}
}
$.ajax(params);
};
|
var gulp = require('gulp');
var browserSync = require('browser-sync');
var config = require('../config')._browserSync;
gulp.task('serve', ['watch'], function() {
browserSync(config.options);
gulp.watch([config.target], function() {
browserSync.reload();
});
});
|
const EventEmitter = require('events');
const Connector = require('./_connector');
const logger = require('../../config/logger');
const formatEvent = require('../utils/formatEvent');
const { sendEvent } = require('./events');
class QueueApp extends EventEmitter {
constructor(config, prefetch) {
if (!config.updateQueue || !config.updateExchange) {
throw new Error('Missing necessary message queue information');
}
super();
this.config = config;
this.prefetch = prefetch;
this.connection = new Connector(config.rabbitUrl);
this.connection.on('ready', this.onConnected.bind(this));
this.connection.on('lost', this.onLost.bind(this));
this.connection.on('error', this.onError.bind(this));
}
onConnected() {
const options = { durable: true, autoDelete: false };
// Set DL queu for retry
const deadLetterOptions = Object.assign({}, options, {
arguments: {
'x-message-ttl': this.config.deadLetterTTL,
'x-dead-letter-exchange': this.config.updateExchange,
'x-dead-letter-routing-key': this.config.updateQueue
}
});
const ok = this.connection.defaultChannel();
ok.then(() => this.connection.assertExchange(this.config.updateExchange, 'direct', options));
ok.then(() => this.connection.assertQueue(this.config.updateQueue, options));
ok.then(() => this.connection.assertQueue(this.config.deadLetterQueue, deadLetterOptions));
ok.then(() => this.connection.bindQueue(this.config.updateQueue, this.config.updateExchange,
this.config.updateQueue));
ok.then(() => this.connection.bindQueue(this.config.deadLetterQueue, this.config.updateExchange,
this.config.deadLetterQueue));
ok.then(() => this.connection.setPrefetch(this.prefetch));
ok.then(() => this.connection.recover());
ok.then(() => this.emit('ready'));
ok.catch(this.onError);
}
onLost() {
logger.info('connection to queue lost');
this.emit('lost');
}
onError() {
logger.error('error with queue connection');
this.emit('lost');
}
publish(queueName, task) {
return this.connection.publish(this.config.updateExchange, queueName, JSON.stringify(task));
}
countQueueMessages(queueName) {
return this.connection.countMessages(queueName);
}
/* istanbul ignore next */
closeChannel() {
return this.connection.closeChannel();
}
closeConnection() {
return this.connection.closeConnection();
}
purgeQueue(queueName) {
return this.connection.purgeQueue(queueName);
}
startConsumingEvents() {
this.connection.consume(this.config.updateQueue, this.onTask.bind(this));
}
stopConsuming(consumerTag) {
this.connection.cancel(consumerTag);
}
async onTask(task) {
if (!this.eventConsumer) {
this.eventConsumer = task.fields.consumerTag;
}
this.emit('processing-task', 'queue: ' + task.fields.routingKey);
const e = JSON.parse(task.content.toString());
if (!e) {
return this.connection.ack(task);
}
try {
await sendEvent(formatEvent(e));
logger.info('update message processed');
} catch (err) {
logger.error(`Couldn't send event: ${err}`);
try {
await this.publish(this.config.deadLetterQueue, e);
} catch (err) {
logger.error(`Could not publish to DL Queue: ${err}`);
}
}
this.connection.ack(task);
}
}
module.exports = QueueApp;
|
"use strict";
var Page = require("../models/page");
var setProps = require("../lib/set-props");
var setPage = function (req, res) {
var page = res.locals.page;
if (page) {
try {
setProps(req.body, ["title", "content", "tags"], page);
} catch (err) {
return res.send(400, err.message);
}
} else {
page = new Page(req.body);
page.path = req.path;
}
page.modifiedBy = req.cookies.username || "";
return page;
};
var randomItem = function (items) {
if (!items.length) return null;
return items[Math.floor(Math.random() * items.length)];
};
var getImage = function (page) {
var randomImage = randomItem(page.images);
if (randomImage) return "/images/" + page._id + "/" + randomImage;
var attachments = page.attachments.filter(function (attachment) {
return attachment.match(/(.jpeg|.gif|.jpg|.png)$/i);
});
var randomAttachment = randomItem(attachments);
if (randomAttachment) return "/attachments/" + page._id + "/" + randomAttachment;
return "/static-images/noimg.png";
};
module.exports = function (app) {
app.get("/pages", function (req, res) {
Page.all(function (err, pages) {
if (err) {
console.error(err);
res.send(500);
}
return res.render("pages", {
title: "All Pages",
pages: pages,
content: "Own"
});
});
});
app.get("/pages.json", function (req, res) {
var sort = req.query.sort_by || "title";
Page.find({
deleted: false
})
.select("title path")
.sort(sort)
.exec(function (err, pages) {
if (err) {
console.error(err);
res.send(500);
}
res.json(pages);
});
});
app.get("/pages/covers", function (req, res) {
Page.allWithImages(function (err, pages) {
return res.render("pages_cover", {
title: "All Pages",
pages: pages.map(function (page) {
return {
title: page.title,
image: getImage(page),
path: page.path
};
})
});
});
});
app.get("*", function (req, res) {
if (!res.locals.page) {
return res.send(404);
}
return res.render("page", {
title: res.locals.page.title,
page: res.locals.page
});
});
app.post("*", function (req, res) {
if (req.body.lastModified) {
if (!res.locals.page) return res.send(405);
var currentDate = new Date(res.locals.page.lastModified);
var oldTimestamp = req.body.lastModified;
if (currentDate.getTime() > oldTimestamp) {
return res.send(409);
}
}
var page = setPage(req, res);
page.save(function (err) {
if (err) {
console.error(err);
return res.send(400);
}
res.send(200, {
lastModified: page.lastModified.getTime()
});
});
});
var updatePath = function (req, res) {
var page = res.locals.page;
Page.findOne({
path: req.body.newPath,
deleted: false
}, function (err, existingPage) {
if (err) {
console.error(err);
return res.send(500);
}
if (existingPage) {
return res.json({
status: "page-exists"
});
}
page.path = req.body.newPath;
page.save(function (err) {
if (err) {
console.log(err);
return res.send(500);
}
res.json({
status: "page-moved",
target: req.body.newPath
});
});
});
};
var restorePage = function (req, res) {
Page.findOne({
path: req.path,
deleted: true
}, function (err, page) {
if(err) {
console.error(err);
return res.send(500);
}
if (!page) {
return res.send(404);
}
page.restore(function (err) {
if (err) {
console.error(err);
return res.send(500);
}
res.send(205);
});
});
};
app.put("*", function (req, res) {
if (req.body.restore) return restorePage(req, res);
if (!res.locals.page) return res.send(405);
updatePath(req, res);
});
app.delete("*", function (req, res) {
if (!res.locals.page) return res.send(405);
var page = res.locals.page;
page.delete(function (err) {
if (err) {
console.error(err);
return res.send(500);
}
res.send(205);
});
});
};
|
// This was coded while reading:
// "The Nature of Code" by Daniel Shiffman
// http://natureofcode.com/
var Mover = function(m, x, y) {
this.position = createVector(x, y);
this.mass = m;
this.angle = 0;
this.aVelocity = 0;
this.aAcceleration = 0;
this.velocity = createVector(random(-1, 1), random(-1, 1));
this.acceleration = createVector(0, 0);
this.applyForce = function(force) {
var f = p5.Vector.div(force, this.mass);
this.acceleration.add(f);
};
this.update = function () {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.aAcceleration = this.acceleration.x / 10.0;
this.aVelocity += this.aAcceleration;
this.aVelocity = constrain(this.aVelocity, -0.1, 0.1);
this.angle += this.aVelocity;
this.acceleration.mult(0);
};
this.display = function () {
stroke(0);
fill(175, 200);
rectMode(CENTER);
push();
translate(this.position.x, this.position.y);
rotate(this.angle);
rect(0, 0, this.mass*16, this.mass*16);
pop();
};
}; |
var express = require('express'),
ensureLoggedIn = require('../passport/ensureLoggedIn'),
responseObjectHelper = require( '../helpers/responseObjectHelper' );
module.exports = function(passport) {
var router = express.Router();
router.get('/',
ensureLoggedIn,
function(req, res) {
var user = req.user.toObject();
delete user.password;
res.status(200).json(responseObjectHelper.getSuccessResponseObject( 'Success', user ));
}
);
return router;
}; |
const React = require('react');
const IconBase = require('react-icon-base');
export default class NoAlt extends React.Component {
render() {
return (
<IconBase viewBox='0 0 20 20' {...this.props}>
<path d='M14.95 6.46l-3.54 3.54 3.54 3.54-1.41 1.41-3.54-3.53-3.53 3.53-1.42-1.42 3.53-3.53-3.53-3.53 1.42-1.42 3.53 3.53 3.54-3.53z'/>
</IconBase>
);
}
}
|
// # Recline Backbone Models
this.recline = this.recline || {};
this.recline.Model = this.recline.Model || {};
(function(my, recline) {
"use strict";
// use either jQuery or Underscore Deferred depending on what is available
var Deferred = (typeof jQuery !== "undefined" && jQuery.Deferred) || _.Deferred;
// ## <a id="dataset">Dataset</a>
my.Dataset = Backbone.Model.extend({
constructor: function Dataset() {
Backbone.Model.prototype.constructor.apply(this, arguments);
},
// ### initialize
initialize: function() {
var self = this;
_.bindAll(this, 'query');
this.backend = null;
if (this.get('backend')) {
this.backend = this._backendFromString(this.get('backend'));
} else { // try to guess backend ...
if (this.get('records')) {
this.backend = recline.Backend.Memory;
}
}
this.fields = new my.FieldList();
this.records = new my.RecordList();
this._changes = {
deletes: [],
updates: [],
creates: []
};
this.facets = new my.FacetList();
this.recordCount = null;
this.queryState = new my.Query();
this.queryState.bind('change facet:add', function () {
self.query(); // We want to call query() without any arguments.
});
// store is what we query and save against
// store will either be the backend or be a memory store if Backend fetch
// tells us to use memory store
this._store = this.backend;
// if backend has a handleQueryResultFunction, use that
this._handleResult = (this.backend != null && _.has(this.backend, 'handleQueryResult')) ?
this.backend.handleQueryResult : this._handleQueryResult;
if (this.backend == recline.Backend.Memory) {
this.fetch();
}
},
sync: function(method, model, options) {
return this.backend.sync(method, model, options);
},
// ### fetch
//
// Retrieve dataset and (some) records from the backend.
fetch: function() {
var self = this;
var dfd = new Deferred();
if (this.backend !== recline.Backend.Memory) {
this.backend.fetch(this.toJSON())
.done(handleResults)
.fail(function(args) {
dfd.reject(args);
});
} else {
// special case where we have been given data directly
handleResults({
records: this.get('records'),
fields: this.get('fields'),
useMemoryStore: true
});
}
function handleResults(results) {
// if explicitly given the fields
// (e.g. var dataset = new Dataset({fields: fields, ...})
// use that field info over anything we get back by parsing the data
// (results.fields)
var fields = self.get('fields') || results.fields;
var out = self._normalizeRecordsAndFields(results.records, fields);
if (results.useMemoryStore) {
self._store = new recline.Backend.Memory.Store(out.records, out.fields);
}
self.set(results.metadata);
self.fields.reset(out.fields);
self.query()
.done(function() {
dfd.resolve(self);
})
.fail(function(args) {
dfd.reject(args);
});
}
return dfd.promise();
},
// ### _normalizeRecordsAndFields
//
// Get a proper set of fields and records from incoming set of fields and records either of which may be null or arrays or objects
//
// e.g. fields = ['a', 'b', 'c'] and records = [ [1,2,3] ] =>
// fields = [ {id: a}, {id: b}, {id: c}], records = [ {a: 1}, {b: 2}, {c: 3}]
_normalizeRecordsAndFields: function(records, fields) {
// if no fields get them from records
if (!fields && records && records.length > 0) {
// records is array then fields is first row of records ...
if (records[0] instanceof Array) {
fields = records[0];
records = records.slice(1);
} else {
fields = _.map(_.keys(records[0]), function(key) {
return {id: key};
});
}
}
// fields is an array of strings (i.e. list of field headings/ids)
if (fields && fields.length > 0 && (fields[0] === null || typeof(fields[0]) != 'object')) {
// Rename duplicate fieldIds as each field name needs to be
// unique.
var seen = {};
fields = _.map(fields, function(field, index) {
if (field === null) {
field = '';
} else {
field = field.toString();
}
// cannot use trim as not supported by IE7
var fieldId = field.replace(/^\s+|\s+$/g, '');
if (fieldId === '') {
fieldId = '_noname_';
field = fieldId;
}
while (fieldId in seen) {
seen[field] += 1;
fieldId = field + seen[field];
}
if (!(field in seen)) {
seen[field] = 0;
}
// TODO: decide whether to keep original name as label ...
// return { id: fieldId, label: field || fieldId }
return { id: fieldId };
});
}
// records is provided as arrays so need to zip together with fields
// NB: this requires you to have fields to match arrays
if (records && records.length > 0 && records[0] instanceof Array) {
records = _.map(records, function(doc) {
var tmp = {};
_.each(fields, function(field, idx) {
tmp[field.id] = doc[idx];
});
return tmp;
});
}
return {
fields: fields,
records: records
};
},
save: function() {
var self = this;
// TODO: need to reset the changes ...
return this._store.save(this._changes, this.toJSON());
},
// ### query
//
// AJAX method with promise API to get records from the backend.
//
// It will query based on current query state (given by this.queryState)
// updated by queryObj (if provided).
//
// Resulting RecordList are used to reset this.records and are
// also returned.
query: function(queryObj) {
var self = this;
var dfd = new Deferred();
this.trigger('query:start');
if (queryObj) {
var attributes = queryObj;
if (queryObj instanceof my.Query) {
attributes = queryObj.toJSON();
}
this.queryState.set(attributes, {silent: true});
}
var actualQuery = this.queryState.toJSON();
this._store.query(actualQuery, this.toJSON())
.done(function(queryResult) {
self._handleResult(queryResult);
self.trigger('query:done');
dfd.resolve(self.records);
})
.fail(function(args) {
self.trigger('query:fail', args);
dfd.reject(args);
});
return dfd.promise();
},
_handleQueryResult: function(queryResult) {
var self = this;
self.recordCount = queryResult.total;
var docs = _.map(queryResult.hits, function(hit) {
var _doc = new my.Record(hit);
_doc.fields = self.fields;
_doc.bind('change', function(doc) {
self._changes.updates.push(doc.toJSON());
});
_doc.bind('destroy', function(doc) {
self._changes.deletes.push(doc.toJSON());
});
return _doc;
});
self.records.reset(docs);
if (queryResult.facets) {
var facets = _.map(queryResult.facets, function(facetResult, facetId) {
facetResult.id = facetId;
return new my.Facet(facetResult);
});
self.facets.reset(facets);
}
},
toTemplateJSON: function() {
var data = this.toJSON();
data.recordCount = this.recordCount;
data.fields = this.fields.toJSON();
return data;
},
// ### getFieldsSummary
//
// Get a summary for each field in the form of a `Facet`.
//
// @return null as this is async function. Provides deferred/promise interface.
getFieldsSummary: function() {
var self = this;
var query = new my.Query();
query.set({size: 0});
this.fields.each(function(field) {
query.addFacet(field.id);
});
var dfd = new Deferred();
this._store.query(query.toJSON(), this.toJSON()).done(function(queryResult) {
if (queryResult.facets) {
_.each(queryResult.facets, function(facetResult, facetId) {
facetResult.id = facetId;
var facet = new my.Facet(facetResult);
// TODO: probably want replace rather than reset (i.e. just replace the facet with this id)
self.fields.get(facetId).facets.reset(facet);
});
}
dfd.resolve(queryResult);
});
return dfd.promise();
},
// Deprecated (as of v0.5) - use record.summary()
recordSummary: function(record) {
return record.summary();
},
// ### _backendFromString(backendString)
//
// Look up a backend module from a backend string (look in recline.Backend)
_backendFromString: function(backendString) {
var backend = null;
if (recline && recline.Backend) {
_.each(_.keys(recline.Backend), function(name) {
if (name.toLowerCase() === backendString.toLowerCase()) {
backend = recline.Backend[name];
}
});
}
return backend;
}
});
// ## <a id="record">A Record</a>
//
// A single record (or row) in the dataset
my.Record = Backbone.Model.extend({
constructor: function Record() {
Backbone.Model.prototype.constructor.apply(this, arguments);
},
// ### initialize
//
// Create a Record
//
// You usually will not do this directly but will have records created by
// Dataset e.g. in query method
//
// Certain methods require presence of a fields attribute (identical to that on Dataset)
initialize: function() {
_.bindAll(this, 'getFieldValue');
},
// ### getFieldValue
//
// For the provided Field get the corresponding rendered computed data value
// for this record.
//
// NB: if field is undefined a default '' value will be returned
getFieldValue: function(field) {
var val = this.getFieldValueUnrendered(field);
if (field && !_.isUndefined(field.renderer)) {
val = field.renderer(val, field, this.toJSON());
}
return val;
},
// ### getFieldValueUnrendered
//
// For the provided Field get the corresponding computed data value
// for this record.
//
// NB: if field is undefined a default '' value will be returned
getFieldValueUnrendered: function(field) {
if (!field) {
return '';
}
var val = this.get(field.id);
if (field.deriver) {
val = field.deriver(val, field, this);
}
return val;
},
// ### summary
//
// Get a simple html summary of this record in form of key/value list
summary: function(record) {
var self = this;
var html = '<div class="recline-record-summary">';
this.fields.each(function(field) {
if (field.id != 'id') {
html += '<div class="' + field.id + '"><strong>' + field.get('label') + '</strong>: ' + self.getFieldValue(field) + '</div>';
}
});
html += '</div>';
return html;
},
// Override Backbone save, fetch and destroy so they do nothing
// Instead, Dataset object that created this Record should take care of
// handling these changes (discovery will occur via event notifications)
// WARNING: these will not persist *unless* you call save on Dataset
fetch: function() {},
save: function() {},
destroy: function() { this.trigger('destroy', this); }
});
// ## A Backbone collection of Records
my.RecordList = Backbone.Collection.extend({
constructor: function RecordList() {
Backbone.Collection.prototype.constructor.apply(this, arguments);
},
model: my.Record
});
// ## <a id="field">A Field (aka Column) on a Dataset</a>
my.Field = Backbone.Model.extend({
constructor: function Field() {
Backbone.Model.prototype.constructor.apply(this, arguments);
},
// ### defaults - define default values
defaults: {
label: null,
type: 'string',
format: null,
is_derived: false
},
// ### initialize
//
// @param {Object} data: standard Backbone model attributes
//
// @param {Object} options: renderer and/or deriver functions.
initialize: function(data, options) {
// if a hash not passed in the first argument throw error
if ('0' in data) {
throw new Error('Looks like you did not pass a proper hash with id to Field constructor');
}
if (this.attributes.label === null) {
this.set({label: this.id});
}
if (this.attributes.type.toLowerCase() in this._typeMap) {
this.attributes.type = this._typeMap[this.attributes.type.toLowerCase()];
}
if (options) {
this.renderer = options.renderer;
this.deriver = options.deriver;
}
if (!this.renderer) {
this.renderer = this.defaultRenderers[this.get('type')];
}
this.facets = new my.FacetList();
},
_typeMap: {
'text': 'string',
'double': 'number',
'float': 'number',
'numeric': 'number',
'int': 'integer',
'datetime': 'date-time',
'bool': 'boolean',
'timestamp': 'date-time',
'json': 'object'
},
defaultRenderers: {
object: function(val, field, doc) {
return JSON.stringify(val);
},
geo_point: function(val, field, doc) {
return JSON.stringify(val);
},
'number': function(val, field, doc) {
var format = field.get('format');
if (format === 'percentage') {
return val + '%';
}
return val;
},
'string': function(val, field, doc) {
var format = field.get('format');
if (format === 'markdown') {
if (typeof Showdown !== 'undefined') {
var showdown = new Showdown.converter();
out = showdown.makeHtml(val);
return out;
} else {
return val;
}
} else if (format == 'plain') {
return val;
} else {
// as this is the default and default type is string may get things
// here that are not actually strings
if (val && typeof val === 'string') {
val = val.replace(/(https?:\/\/[^ ]+)/g, '<a href="$1">$1</a>');
}
return val;
}
}
}
});
my.FieldList = Backbone.Collection.extend({
constructor: function FieldList() {
Backbone.Collection.prototype.constructor.apply(this, arguments);
},
model: my.Field
});
// ## <a id="query">Query</a>
my.Query = Backbone.Model.extend({
constructor: function Query() {
Backbone.Model.prototype.constructor.apply(this, arguments);
},
defaults: function() {
return {
size: 100,
from: 0,
q: '',
facets: {},
filters: []
};
},
_filterTemplates: {
term: {
type: 'term',
// TODO do we need this attribute here?
field: '',
term: ''
},
range: {
type: 'range',
from: '',
to: ''
},
geo_distance: {
type: 'geo_distance',
distance: 10,
unit: 'km',
point: {
lon: 0,
lat: 0
}
}
},
// ### addFilter(filter)
//
// Add a new filter specified by the filter hash and append to the list of filters
//
// @param filter an object specifying the filter - see _filterTemplates for examples. If only type is provided will generate a filter by cloning _filterTemplates
addFilter: function(filter) {
// crude deep copy
var ourfilter = JSON.parse(JSON.stringify(filter));
// not fully specified so use template and over-write
if (_.keys(filter).length <= 3) {
ourfilter = _.defaults(ourfilter, this._filterTemplates[filter.type]);
}
var filters = this.get('filters');
filters.push(ourfilter);
this.trigger('change:filters:new-blank');
},
replaceFilter: function(filter) {
// delete filter on the same field, then add
var filters = this.get('filters');
var idx = -1;
_.each(this.get('filters'), function(f, key, list) {
if (filter.field == f.field) {
idx = key;
}
});
// trigger just one event (change:filters:new-blank) instead of one for remove and
// one for add
if (idx >= 0) {
filters.splice(idx, 1);
this.set({filters: filters});
}
this.addFilter(filter);
},
updateFilter: function(index, value) {
},
// ### removeFilter
//
// Remove a filter from filters at index filterIndex
removeFilter: function(filterIndex) {
var filters = this.get('filters');
filters.splice(filterIndex, 1);
this.set({filters: filters});
this.trigger('change');
},
// ### addFacet
//
// Add a Facet to this query
//
// See <http://www.elasticsearch.org/guide/reference/api/search/facets/>
addFacet: function(fieldId, size, silent) {
var facets = this.get('facets');
// Assume id and fieldId should be the same (TODO: this need not be true if we want to add two different type of facets on same field)
if (_.contains(_.keys(facets), fieldId)) {
return;
}
facets[fieldId] = {
terms: { field: fieldId }
};
if (!_.isUndefined(size)) {
facets[fieldId].terms.size = size;
}
this.set({facets: facets}, {silent: true});
if (!silent) {
this.trigger('facet:add', this);
}
},
addHistogramFacet: function(fieldId) {
var facets = this.get('facets');
facets[fieldId] = {
date_histogram: {
field: fieldId,
interval: 'day'
}
};
this.set({facets: facets}, {silent: true});
this.trigger('facet:add', this);
},
removeFacet: function(fieldId) {
var facets = this.get('facets');
// Assume id and fieldId should be the same (TODO: this need not be true if we want to add two different type of facets on same field)
if (!_.contains(_.keys(facets), fieldId)) {
return;
}
delete facets[fieldId];
this.set({facets: facets}, {silent: true});
this.trigger('facet:remove', this);
},
clearFacets: function() {
var facets = this.get('facets');
_.each(_.keys(facets), function(fieldId) {
delete facets[fieldId];
});
this.trigger('facet:remove', this);
},
// trigger a facet add; use this to trigger a single event after adding
// multiple facets
refreshFacets: function() {
this.trigger('facet:add', this);
}
});
// ## <a id="facet">A Facet (Result)</a>
my.Facet = Backbone.Model.extend({
constructor: function Facet() {
Backbone.Model.prototype.constructor.apply(this, arguments);
},
defaults: function() {
return {
_type: 'terms',
total: 0,
other: 0,
missing: 0,
terms: []
};
}
});
// ## A Collection/List of Facets
my.FacetList = Backbone.Collection.extend({
constructor: function FacetList() {
Backbone.Collection.prototype.constructor.apply(this, arguments);
},
model: my.Facet
});
// ## Object State
//
// Convenience Backbone model for storing (configuration) state of objects like Views.
my.ObjectState = Backbone.Model.extend({
});
// ## Backbone.sync
//
// Override Backbone.sync to hand off to sync function in relevant backend
// Backbone.sync = function(method, model, options) {
// return model.backend.sync(method, model, options);
// };
}(this.recline.Model, this.recline));
this.recline = this.recline || {};
this.recline.Backend = this.recline.Backend || {};
this.recline.Backend.Memory = this.recline.Backend.Memory || {};
(function(my, recline) {
"use strict";
my.__type__ = 'memory';
// private data - use either jQuery or Underscore Deferred depending on what is available
var Deferred = (typeof jQuery !== "undefined" && jQuery.Deferred) || _.Deferred;
// ## Data Wrapper
//
// Turn a simple array of JS objects into a mini data-store with
// functionality like querying, faceting, updating (by ID) and deleting (by
// ID).
//
// @param records list of hashes for each record/row in the data ({key:
// value, key: value})
// @param fields (optional) list of field hashes (each hash defining a field
// as per recline.Model.Field). If fields not specified they will be taken
// from the data.
my.Store = function(records, fields) {
var self = this;
this.records = records;
// backwards compatability (in v0.5 records was named data)
this.data = this.records;
if (fields) {
this.fields = fields;
} else {
if (records) {
this.fields = _.map(records[0], function(value, key) {
return {id: key, type: 'string'};
});
}
}
this.update = function(doc) {
_.each(self.records, function(internalDoc, idx) {
if(doc.id === internalDoc.id) {
self.records[idx] = doc;
}
});
};
this.remove = function(doc) {
var newdocs = _.reject(self.records, function(internalDoc) {
return (doc.id === internalDoc.id);
});
this.records = newdocs;
};
this.save = function(changes, dataset) {
var self = this;
var dfd = new Deferred();
// TODO _.each(changes.creates) { ... }
_.each(changes.updates, function(record) {
self.update(record);
});
_.each(changes.deletes, function(record) {
self.remove(record);
});
dfd.resolve();
return dfd.promise();
},
this.query = function(queryObj) {
var dfd = new Deferred();
var numRows = queryObj.size || this.records.length;
var start = queryObj.from || 0;
var results = this.records;
results = this._applyFilters(results, queryObj);
results = this._applyFreeTextQuery(results, queryObj);
// TODO: this is not complete sorting!
// What's wrong is we sort on the *last* entry in the sort list if there are multiple sort criteria
_.each(queryObj.sort, function(sortObj) {
var fieldName = sortObj.field;
results = _.sortBy(results, function(doc) {
var _out = doc[fieldName];
return _out;
});
if (sortObj.order == 'desc') {
results.reverse();
}
});
var facets = this.computeFacets(results, queryObj);
var out = {
total: results.length,
hits: results.slice(start, start+numRows),
facets: facets
};
dfd.resolve(out);
return dfd.promise();
};
// in place filtering
this._applyFilters = function(results, queryObj) {
var filters = queryObj.filters;
// register filters
var filterFunctions = {
term : term,
terms : terms,
range : range,
geo_distance : geo_distance
};
var dataParsers = {
integer: function (e) { return parseFloat(e, 10); },
'float': function (e) { return parseFloat(e, 10); },
number: function (e) { return parseFloat(e, 10); },
string : function (e) { return e.toString(); },
date : function (e) { return moment(e).valueOf(); },
datetime : function (e) { return new Date(e).valueOf(); }
};
var keyedFields = {};
_.each(self.fields, function(field) {
keyedFields[field.id] = field;
});
function getDataParser(filter) {
var fieldType = keyedFields[filter.field].type || 'string';
return dataParsers[fieldType];
}
// filter records
return _.filter(results, function (record) {
var passes = _.map(filters, function (filter) {
return filterFunctions[filter.type](record, filter);
});
// return only these records that pass all filters
return _.all(passes, _.identity);
});
// filters definitions
function term(record, filter) {
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var term = parse(filter.term);
return (value === term);
}
function terms(record, filter) {
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var terms = parse(filter.terms).split(",");
return (_.indexOf(terms, value) >= 0);
}
function range(record, filter) {
var fromnull = (_.isUndefined(filter.from) || filter.from === null || filter.from === '');
var tonull = (_.isUndefined(filter.to) || filter.to === null || filter.to === '');
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var from = parse(fromnull ? '' : filter.from);
var to = parse(tonull ? '' : filter.to);
// if at least one end of range is set do not allow '' to get through
// note that for strings '' <= {any-character} e.g. '' <= 'a'
if ((!fromnull || !tonull) && value === '') {
return false;
}
return ((fromnull || value >= from) && (tonull || value <= to));
}
function geo_distance() {
// TODO code here
}
};
// we OR across fields but AND across terms in query string
this._applyFreeTextQuery = function(results, queryObj) {
if (queryObj.q) {
var terms = queryObj.q.split(' ');
var patterns=_.map(terms, function(term) {
return new RegExp(term.toLowerCase());
});
results = _.filter(results, function(rawdoc) {
var matches = true;
_.each(patterns, function(pattern) {
var foundmatch = false;
_.each(self.fields, function(field) {
var value = rawdoc[field.id];
if ((value !== null) && (value !== undefined)) {
value = value.toString();
} else {
// value can be null (apparently in some cases)
value = '';
}
// TODO regexes?
foundmatch = foundmatch || (pattern.test(value.toLowerCase()));
// TODO: early out (once we are true should break to spare unnecessary testing)
// if (foundmatch) return true;
});
matches = matches && foundmatch;
// TODO: early out (once false should break to spare unnecessary testing)
// if (!matches) return false;
});
return matches;
});
}
return results;
};
this.computeFacets = function(records, queryObj) {
var facetResults = {};
if (!queryObj.facets) {
return facetResults;
}
_.each(queryObj.facets, function(query, facetId) {
// TODO: remove dependency on recline.Model
facetResults[facetId] = new recline.Model.Facet({id: facetId}).toJSON();
facetResults[facetId].termsall = {};
});
// faceting
_.each(records, function(doc) {
_.each(queryObj.facets, function(query, facetId) {
var fieldId = query.terms.field;
var val = doc[fieldId];
var tmp = facetResults[facetId];
if (val) {
tmp.termsall[val] = tmp.termsall[val] ? tmp.termsall[val] + 1 : 1;
} else {
tmp.missing = tmp.missing + 1;
}
});
});
_.each(queryObj.facets, function(query, facetId) {
var tmp = facetResults[facetId];
var terms = _.map(tmp.termsall, function(count, term) {
return { term: term, count: count };
});
tmp.terms = _.sortBy(terms, function(item) {
// want descending order
return -item.count;
});
tmp.terms = tmp.terms.slice(0, 10);
});
return facetResults;
};
};
}(this.recline.Backend.Memory, this.recline));
|
var net = require("net");
var util = require("util");
var events = require("events");
var zbx_sender = function (options) {
this.c_opts = {};
if (options) {
if (options["zabbix-server"]) {
this.c_opts["host"] = options["zabbix-server"];
} else {
this.emit('error',new Error('missing required parameter "zabbix-server"'))
}
if (options["port"]) {
this.c_opts["port"] = options["port"]
} else {
this.c_opts["port"] = "10051"
}
if (options["host"]) {
this["host"] = options["host"]
}
if (options["source-address"]) {
this.c_opts["source-address"] = options["source-address"]
}
if (options["verbose"] != null){
this["verbose"] = options["verbose"]
}
if (options["realtime"] != null){
this["realtime"]=options["realtime"]
}
if (options["with-timestamps"]!= null){
this["with-timestamps"] = options["with-timestamps"]
}
}
this.delay = 1000;
this._buffer = [];
this._inProggress = false;
};
util.inherits(zbx_sender, events.EventEmitter);
zbx_sender.prototype._set = function (src, key) {
if (src[key] == null) {
if (this[key] == null) {
throw new Error('missing required parameter "'+key+'"');
} else {
return this[key];
}
} else {
return src[key];
}
};
zbx_sender.prototype._send = function(){
var me = this;
if (me._inProggress){
return;
}
if (!me._buffer.length){
me.emit('error', new Error('nothing to send'));
return;
}
var data=me._buffer.slice(0,250);
me._buffer=data.slice(250);
me.inProggress = true;
if (me["with-timestamps"]){
data["clock"] = new Date().getTime() / 1000 |0 ;
}
var req = {"request": "sender data", "data": data};
var str = JSON.stringify(req)
, message = new Buffer(5 + 8)
, payload = new Buffer(str, "utf8");
message.fill("\x00");
message.write("ZBXD\x01");
message = Buffer.concat([message, payload]);
message.writeUInt32LE(payload.length, 5);
var client = net.connect(this.c_opts,
function () {
client.write(message);
});
var result = new Buffer(0);
client.on("data", function (data) {
result = Buffer.concat([result, data]);
});
client.on("end", function () {
var head = result.slice(0, 5);
if (head.toString() == "ZBXD\x01") {
if (result.length > 5) {
var resp = JSON.parse(result.slice(13));
if (me["verbose"]){
me.emit('data',resp, str);
} else {
me.emit('data',resp);
}
}
} else {
me.emit('error', new SyntaxError("Invalid response"),result, str);
}
me._inProggress = false;
if (me._buffer.length){
me._send();
}
});
client.on("error", function (err) {
me.emit('error',new Error('Network error'), err, str)
})
};
zbx_sender.prototype.send = function (options) {
var me = this;
var temp = {};
if (!options) {
me.emit('error',new Error('missing options'))
} else {
var now = new Date().getTime() / 1000 |0;
if (options instanceof Array) {
options.forEach(function (v) {
try {
var d = {};
d["host"] = me._set(v, "host");
d["key"] = me._set(v, "key");
d["value"] = me._set(v, "value");
if (me["with-timestamps"]){
d["clock"] = v["clock"] || now ;
}
me._buffer.push(d);
} catch (e){
me.emit('error',e,null,v);
}
})
} else {
try {
temp["host"] = me._set(options, "host");
temp["key"] = me._set(options, "key");
temp["value"] = me._set(options, "value");
if (me["with-timestamps"]){
temp["clock"] = options["clock"] || now ;
}
me._buffer.push(temp);
} catch (e){
me.emit('error',e)
}
}
}
if (!me._inProggress ) {
if (me['realtime']) {
me._send();
} else {
if (!me.timeoutId) {
me.timeoutId = setTimeout(function () {
me.timeoutId = 0;
me._send()
}, me.delay);
}
}
}
};
exports.createZabbixSender = function (options) {
return new zbx_sender(options);
};
/*
format for "-T, --with-timestamps" option
{
"request":"sender data",
"data":[
{
"host":"TEST",
"key":"item2",
"value":"201",
"clock":1418670180}],
"clock":1418670320}
*/
|
AmazonRepricingHandler = Class.create(ActionHandler, {
// ---------------------------------------
initialize: function ($super, gridHandler) {
var self = this;
$super(gridHandler);
},
// ---------------------------------------
options: {},
setOptions: function (options) {
this.options = Object.extend(this.options, options);
return this;
},
// ---------------------------------------
openManagement: function () {
window.open(M2ePro.url.get('adminhtml_amazon_listing_repricing/openManagement'));
},
// ---------------------------------------
addToRepricing: function (productsIds)
{
var self = this;
MagentoMessageObj.clearAll();
new Ajax.Request(M2ePro.url.get('adminhtml_amazon_listing_repricing/validateProductsBeforeAdd'), {
method: 'post',
parameters: {
products_ids: productsIds
},
onSuccess: function(transport) {
if (!transport.responseText.isJSON()) {
alert(transport.responseText);
return;
}
var response = transport.responseText.evalJSON();
if(response.products_ids.length === 0) {
MagentoMessageObj['add' + response.type[0].toUpperCase() + response.type.slice(1)](response.message);
return;
}
if (response.products_ids.length === productsIds.split(',').length) {
self.addToRepricingConfirm(productsIds);
return;
}
priceWarningPopUp = Dialog.info(null, {
draggable: true,
resizable: true,
closable: true,
className: "magento",
windowClassName: "popup-window",
title: response.title,
top: 150,
width: 400,
height: 220,
zIndex: 100,
hideEffect: Element.hide,
showEffect: Element.show
});
priceWarningPopUp.options.destroyOnClose = true;
$('modal_dialog_message').update(response.html);
$('modal_dialog_message').down('.confirm-action').observe('click', function () {
self.addToRepricingConfirm(productsIds);
});
setTimeout(function() {
Windows.getFocusedWindow().content.style.height = '';
Windows.getFocusedWindow().content.style.maxHeight = '630px';
}, 50);
}
});
},
addToRepricingConfirm: function (productsIds) {
return this.postForm(M2ePro.url.get('adminhtml_amazon_listing_repricing/openAddProducts'), {'products_ids': productsIds});
},
showDetails: function (productsIds)
{
return this.postForm(M2ePro.url.get('adminhtml_amazon_listing_repricing/openShowDetails'), {'products_ids': productsIds});
},
editRepricing: function (productsIds)
{
return this.postForm(M2ePro.url.get('adminhtml_amazon_listing_repricing/openEditProducts'), {'products_ids': productsIds});
},
removeFromRepricing: function (productsIds)
{
return this.postForm(M2ePro.url.get('adminhtml_amazon_listing_repricing/openRemoveProducts'), {'products_ids': productsIds});
}
// ---------------------------------------
}); |
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
var _interopRequireWildcard = require('babel-runtime/helpers/interop-require-wildcard')['default'];
exports.__esModule = true;
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _errors = require('./errors');
var errors = _interopRequireWildcard(_errors);
/**
* Resolve parser for MarkdownDoc.
*
* @param {Object} env
*
* @return {Promise}
*/
exports['default'] = function (env) {
var logger = env.logger;
/**
* Check if parser exist.
*
* @param {String} module - module name.
*
* @return {String}
*/
function getValidedModuleName(module) {
try {
require.resolve(module);
} catch (err) {
logger.info(new errors.Warning('parser `' + module + '` not found.'));
return '';
}
return module;
}
/**
* Check if module can use 2 Arguments and is a function.
*
* @param {String} module - module name.
*
* @return {function | null}
*/
function getValidedParserFunction(module) {
var parser = module !== '' ? require(module) : '';
var str = Object.prototype.toString;
if (typeof parser !== 'function') {
logger.error(new errors.Warning('Given parser is ' + str(parser) + ', expected ' + str(str) + '.'));
return null;
}
if (parser.length !== 2) {
logger.error('Given parser takes ' + parser.length + ' arguments, expected 2.');
return null;
}
return parser;
}
/**
* Load given resolver module.
*
* @param {String} env
*
* @return {function | null}
*/
function load() {
var name = env.get('parser');
var parser = '';
if (name.indexOf('/') === -1) {
parser = getValidedModuleName('markdowndoc-' + name + '-parser');
} else {
parser = _path2['default'].resolve(process.cwd(), getValidedModuleName(name));
}
if (env.get('debug')) {
env.log('Given parser ' + name + ' is loaded.', 'debug');
}
return getValidedParserFunction(parser);
}
return load(env);
};
module.exports = exports['default'];
|
var wpServer = 'http://hklane2015.uptowncreativeinc.com/wp-json/wp/v2';
$.getJSON(wpServer + '/pages/10', function(data){
var content = $(data.content.rendered);
var section = $("#index-mid");
section.append(content);
section.css({opacity: 1});
$(".loader").fadeOut("slow");
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.