code stringlengths 2 1.05M |
|---|
'use strict';
let gulp=require('gulp');
let wiredep=require('gulp-wiredep');
gulp.task('wiredep',function(cb){
gulp.src('./src/index.html')
.pipe(wiredep({
optional: 'configuration',
goes: 'here'
}))
.pipe(gulp.dest('./dist'));
});
|
import Component from 'flarum/Component';
import listItems from 'flarum/helpers/listItems';
import Button from 'flarum/components/Button';
import LoadingIndicator from 'flarum/components/LoadingIndicator';
import Discussion from 'flarum/models/Discussion';
/**
* The `NotificationList` component displays a list of the logged-in user's
* notifications, grouped by discussion.
*/
export default class NotificationList extends Component {
constructor(...args) {
super(...args);
/**
* Whether or not the notifications are loading.
*
* @type {Boolean}
*/
this.loading = false;
}
view() {
const groups = [];
if (app.cache.notifications) {
const discussions = {};
// Build an array of discussions which the notifications are related to,
// and add the notifications as children.
app.cache.notifications.forEach(notification => {
const subject = notification.subject();
if (typeof subject === 'undefined') return;
// Get the discussion that this notification is related to. If it's not
// directly related to a discussion, it may be related to a post or
// other entity which is related to a discussion.
let discussion = false;
if (subject instanceof Discussion) discussion = subject;
else if (subject && subject.discussion) discussion = subject.discussion();
// If the notification is not related to a discussion directly or
// indirectly, then we will assign it to a neutral group.
const key = discussion ? discussion.id() : 0;
discussions[key] = discussions[key] || {discussion: discussion, notifications: []};
discussions[key].notifications.push(notification);
if (groups.indexOf(discussions[key]) === -1) {
groups.push(discussions[key]);
}
});
}
return (
<div className="NotificationList">
<div className="NotificationList-header">
<div className="App-primaryControl">
{Button.component({
className: 'Button Button--icon Button--link',
icon: 'check',
title: app.trans('core.forum.notifications_mark_all_as_read_tooltip'),
onclick: this.markAllAsRead.bind(this)
})}
</div>
<h4 className="App-titleControl App-titleControl--text">{app.trans('core.forum.notifications_title')}</h4>
</div>
<div className="NotificationList-content">
{groups.length
? groups.map(group => {
const badges = group.discussion && group.discussion.badges().toArray();
return (
<div className="NotificationGroup">
{group.discussion
? (
<a className="NotificationGroup-header"
href={app.route.discussion(group.discussion)}
config={m.route}>
{badges && badges.length ? <ul className="NotificationGroup-badges badges">{listItems(badges)}</ul> : ''}
{group.discussion.title()}
</a>
) : (
<div className="NotificationGroup-header">
{app.forum.attribute('title')}
</div>
)}
<ul className="NotificationGroup-content">
{group.notifications.map(notification => {
const NotificationComponent = app.notificationComponents[notification.contentType()];
return NotificationComponent ? <li>{NotificationComponent.component({notification})}</li> : '';
})}
</ul>
</div>
);
})
: !this.loading
? <div className="NotificationList-empty">{app.trans('core.forum.notifications_empty_text')}</div>
: LoadingIndicator.component({className: 'LoadingIndicator--block'})}
</div>
</div>
);
}
/**
* Load notifications into the application's cache if they haven't already
* been loaded.
*/
load() {
if (app.cache.notifications && !app.session.user.newNotificationsCount()) {
return;
}
this.loading = true;
m.redraw();
app.store.find('notifications').then(notifications => {
app.session.user.pushAttributes({newNotificationsCount: 0});
app.cache.notifications = notifications.sort((a, b) => b.time() - a.time());
this.loading = false;
m.redraw();
});
}
/**
* Mark all of the notifications as read.
*/
markAllAsRead() {
if (!app.cache.notifications) return;
app.session.user.pushAttributes({unreadNotificationsCount: 0});
app.cache.notifications.forEach(notification => notification.pushAttributes({isRead: true}));
app.request({
url: app.forum.attribute('apiUrl') + '/notifications/read',
method: 'POST'
});
}
}
|
Package.describe({
summary: "Stripe.js and Node-Stripe brought to Meteor.",
version: "2.2.1",
name: "mrgalaxy:stripe",
git: "https://github.com/tyler-johnson/stripe-meteor.git"
});
Npm.depends({ "stripe": "4.0.0" });
Package.onUse(function(api) {
api.versionsFrom('1.0.1');
if (api.export) api.export('STRIPEMETEOR');
api.use(['templating'], 'client');
api.addFiles('stripe_client.html', 'client');
api.addFiles('stripe_server.js', 'server');
});
Package.on_test(function(api) {
api.use(['tinytest','mrgalaxy:stripe']);
api.add_files([ "tests/client.js", "tests/checkout.js" ], 'client');
api.add_files([ "tests/server.js" ], 'server');
});
|
(function () {
'use strict';
angular.module('demoApp', ['ui.tree', 'ngRoute', 'ui.bootstrap'])
.config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {
$routeProvider
.when('/basic-example', {
controller: 'BasicExampleCtrl',
templateUrl: 'views/basic-example.html'
})
.when('/cloning', {
controller: 'CloningCtrl',
templateUrl: 'views/cloning.html'
})
.when('/connected-trees', {
controller: 'ConnectedTreesCtrl',
templateUrl: 'views/connected-trees.html'
})
.when('/filter-nodes', {
controller: 'FilterNodesCtrl',
templateUrl: 'views/filter-nodes.html'
})
.when('/nodrop', {
controller: 'BasicExampleCtrl',
templateUrl: 'views/nodrop.html'
})
.when('/table-example', {
controller: 'TableExampleCtrl',
templateUrl: 'views/table-example.html'
})
.when('/drop-confirmation', {
controller: 'DropConfirmationCtrl',
templateUrl: 'views/drop-confirmation.html'
})
.when('/expand-on-hover', {
controller: 'ExpandOnHoverCtrl',
templateUrl: 'views/expand-on-hover.html'
})
.otherwise({
redirectTo: '/basic-example'
});
// testing issue #521
$compileProvider.debugInfoEnabled(false);
}]);
})();
|
import { LessonResource, ContentNodeResource } from 'kolibri.resources';
export function resetLessonSummaryState(store) {
store.commit('RESET_STATE');
store.commit('resources/RESET_STATE');
}
export function addToResourceCache(store, { node }) {
store.commit('ADD_TO_RESOURCE_CACHE', {
node,
channelTitle: store.getters.getChannelForNode(node).title || '',
});
}
export function updateCurrentLesson(store, lessonId) {
return LessonResource.fetchModel({
id: lessonId,
}).then(
lesson => {
store.commit('SET_CURRENT_LESSON', lesson);
return lesson;
},
error => {
return store.dispatch('handleApiError', error, { root: true });
}
);
}
export function getResourceCache(store, resourceIds) {
// duplicate data to remove reliance on state throughout the entire method
const { resourceCache } = Object.assign({}, store.state);
const nonCachedResourceIds = [];
if (resourceCache) {
resourceIds.forEach(id => {
if (!resourceCache[id]) {
nonCachedResourceIds.push(id);
}
});
}
if (nonCachedResourceIds.length) {
return ContentNodeResource.fetchCollection({
getParams: {
ids: nonCachedResourceIds,
},
}).then(contentNodes => {
contentNodes.forEach(contentNode =>
store.commit('ADD_TO_RESOURCE_CACHE', {
node: contentNode,
channelTitle: store.getters.getChannelForNode(contentNode).title,
})
);
return { ...resourceCache };
});
} else {
return Promise.resolve({ ...resourceCache });
}
}
export function saveLessonResources(store, { lessonId, resourceIds }) {
return store.dispatch('getResourceCache', resourceIds).then(resourceCache => {
const resources = resourceIds.map(resourceId => {
const node = resourceCache[resourceId];
return {
contentnode_id: resourceId,
channel_id: node.channel_id,
content_id: node.content_id,
};
});
return LessonResource.saveModel({
id: lessonId,
data: { resources },
}).then(lesson => {
// Update the class summary now that there is a change to a lesson
return store.dispatch('classSummary/refreshClassSummary', null, { root: true }).then(() => {
return lesson;
});
});
});
}
|
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var db = require('../libs/db_connect')();
var Place = Schema({
geo: {
type: [Number],
index: {
type: '2dsphere',
sparse: true
}
},
geo_name: String,
description: String,
user: { type: String, ref: 'User' }
});
module.exports = db.model('Place', Place);
|
var express = require('express');
var bookshelf = require('./bookshelf');
var models = bookshelf.models;
var router = express.Router();
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now().toString());
next()
})
models.forEach(function (model) {
router.get('/' + model.tableName, function(req,res){
bookshelf[model.name].forge()
.fetchAll()
.then(function(rows){
console.log(rows.related())
res.json({error:false, data: rows.toJSON()});
})
.catch(function(err){
res.status(500).json({err:true, data:err.message});
})
})
router.get('/'+model.tableName+'/page/:p?/:s?', function(req, res){
var fetchOptions = {
pageSize: req.params.s,
page: req.params.p,
}
bookshelf[model.name].forge()
.fetchPage({
pageSize: req.params.s,
page: req.params.p,
withRelated: model.options.relations
})
.then(function(rows){
// console.log(rows);
if(model.options.relations){
rows.forEach(function (row) {
var relations = {}
model.options.relations.forEach(function (r) {
relations[r] = row.related(r);
})
row.related = relations;
})
}
res.json({error:false, data: {rows:rows, pagination:rows.pagination}});
})
.catch(function(err){
res.status(500).json({err:true, data:err.message});
})
})
})
var path = '/' + bookshelf.Location.tableName + '/parent/:id?';
router.get(path, function(req, res){
bookshelf.Location.where({parent_id:req.params.id || 0}).fetchAll()
.then(function(rows){
res.json({err:false, data:rows});
})
});
router.get('/', function(req, res){
res.send('Hello api');
})
module.exports = router; |
export class SignupEntity {
constructor() {
this.login = '';
this.password = '';
this.confirmPassword = '';
}
}
|
/*
* @Author: alessandro.fazio
* @Date: 2016-07-15 13:03:51
* @Last Modified by: alessandro.fazio
* @Last Modified time: 2016-07-15 13:39:26
*/
(function() {'use strict';
angular.module('metricapp')
.controller('ExternalMetricModalCtrl', ExternalMetricModalCtrl);
ExternalMetricModalCtrl.$inject = ['$window', '$uibModal', 'MetricService', '$uibModalInstance', 'MetricModalService', 'MeasurementGoalService'];
function ExternalMetricModalCtrl($window, $uibModal, MetricService, $uibModalInstance, MetricModalService, MeasurementGoalService) {
var vm = this;
vm.externalMetricDialog = MetricService.getExternalMetricDialog();
//console.log("External Metric Dialog");
//console.log(vm.externalMetricDialog);
vm.closeModal = closeModal;
vm.setMetricDialog = setMetricDialog;
vm.addMetricToMeasurementGoal = addMetricToMeasurementGoal;
function closeModal(){
$uibModalInstance.dismiss("closing");
};
function setMetricDialog(metricToAssignId){
MetricService.storeMetric(vm.externalMetricDialog[metricToAssignId]);
MetricModalService.openMetricModal();
}
function addMetricToMeasurementGoal(obj){
console.log("Adding item");
if (MeasurementGoalService.addSomethingToMeasurementGoal('Metric',obj)){
$window.alert('Item added');
}
else {
$window.alert('You cannot add this item');
}
}
/*ctrl.editQuestion = function(question){
$uibModalInstance.dismiss("closing");
QuestionStorageFactory.setQuestion(question);
$location.path('/questionUpdate');
};*/
}
})(); |
jest.mock('../words');
jest.unmock('../randomWord');
import { getWord, wordCount } from '../words';
import randomWord from '../randomWord';
describe('The random word generator', () => {
it('should select a word from the list', () => {
// Arrange
const word = 'kiwis';
wordCount.mockImplementation(() => 1);
getWord.mockImplementation(() => word);
// Act
const result = randomWord();
// Assert
expect(result).toBe(word);
});
});
|
'use strict';
var React = require('react');
var IconBase = require(__dirname + 'components/IconBase/IconBase');
var IosCircleOutline = React.createClass({
displayName: 'IosCircleOutline',
render: function render() {
return React.createElement(
IconBase,
null,
React.createElement(
'g',
null,
React.createElement(
'g',
null,
React.createElement('path', { d: 'M256,48C141.1,48,48,141.1,48,256s93.1,208,208,208c114.9,0,208-93.1,208-208S370.9,48,256,48z M256,446.7 c-105.1,0-190.7-85.5-190.7-190.7c0-105.1,85.5-190.7,190.7-190.7c105.1,0,190.7,85.5,190.7,190.7 C446.7,361.1,361.1,446.7,256,446.7z' })
)
)
);
}
}); |
import {
bootstrapDiagram,
inject
} from 'test/TestHelper';
import modelingModule from 'lib/features/modeling';
import replaceModule from 'lib/features/replace';
import {
query as domQuery
} from 'min-dom';
describe('features/replace', function() {
beforeEach(bootstrapDiagram({
modules: [
modelingModule,
replaceModule
]
}));
var rootShape, parentShape, originalShape;
beforeEach(inject(function(elementFactory, canvas) {
rootShape = elementFactory.createRoot({
id: 'root'
});
canvas.setRootElement(rootShape);
parentShape = elementFactory.createShape({
id: 'parent',
x: 100, y: 100, width: 300, height: 300
});
canvas.addShape(parentShape, rootShape);
originalShape = elementFactory.createShape({
id: 'originalShape',
x: 110, y: 110, width: 100, height: 100
});
canvas.addShape(originalShape, parentShape);
}));
describe('#replaceElement', function() {
it('should add new shape', inject(function(elementRegistry, replace) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 200
};
// when
var newShape = replace.replaceElement(originalShape, replacement);
// then
expect(newShape).to.exist;
// expect added
expect(elementRegistry.get('replacement')).to.equal(newShape);
}));
it('should define custom attributes on new shape', inject(function(replace) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 200,
customArray: ['FOO', 'BAR'],
customString: 'foobar'
};
// when
var newShape = replace.replaceElement(originalShape, replacement);
// then
expect(newShape.customArray).to.equal(replacement.customArray);
expect(newShape.customString).to.equal(replacement.customString);
}));
it('should delete old shape', inject(function(elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 200
};
// shape replacement
replace.replaceElement(originalShape, replacement);
// then
expect(originalShape.parent).to.be.null;
}));
it('should return new shape', inject(function(elementRegistry, replace) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 200
};
// shape replacement
var newShape = replace.replaceElement(originalShape, replacement);
// then
expect(newShape).to.exist;
expect(newShape.id).to.equal('replacement');
}));
it('should add correct attributes to new shape', inject(function(elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 200
};
// shape replacement
replace.replaceElement(originalShape, replacement);
// then
var replacementShape = elementRegistry.get('replacement');
expect(replacementShape.x).to.equal(110);
expect(replacementShape.y).to.equal(110);
expect(replacementShape.width).to.equal(200);
expect(replacementShape.height).to.equal(200);
}));
it('should retain position when setting odd height', inject(function(elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 201
};
// shape replacement
replace.replaceElement(originalShape, replacement);
// then
var replacementShape = elementRegistry.get('replacement');
expect(replacementShape.x).to.equal(110);
expect(replacementShape.y).to.equal(110);
expect(replacementShape.width).to.equal(200);
expect(replacementShape.height).to.equal(201);
}));
it('should retain position when setting odd width', inject(function(elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 201,
height: 200
};
// shape replacement
replace.replaceElement(originalShape, replacement);
// then
var replacementShape = elementRegistry.get('replacement');
expect(replacementShape.x).to.equal(110);
expect(replacementShape.y).to.equal(110);
expect(replacementShape.width).to.equal(201);
expect(replacementShape.height).to.equal(200);
}));
it('should retain position when setting odd width and height', inject(function(elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 201,
height: 201
};
// shape replacement
replace.replaceElement(originalShape, replacement);
// then
var replacementShape = elementRegistry.get('replacement');
expect(replacementShape.x).to.equal(110);
expect(replacementShape.y).to.equal(110);
expect(replacementShape.width).to.equal(201);
expect(replacementShape.height).to.equal(201);
}));
});
describe('reconnect', function() {
var sourceShape,
targetShape,
connection;
beforeEach(inject(function(elementFactory, canvas, modeling) {
sourceShape = originalShape;
targetShape = elementFactory.createShape({
id: 'targetShape',
x: 290, y: 110, width: 100, height: 100
});
canvas.addShape(targetShape, parentShape);
connection = modeling.createConnection(sourceShape, targetShape, {
id: 'connection',
waypoints: [ { x: 210, y: 160 }, { x: 290, y: 160 } ]
}, parentShape);
// canvas.addConnection(connection);
}));
it('should reconnect start', inject(function(elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 120,
height: 120
};
// when
var replacedShape = replace.replaceElement(sourceShape, replacement);
// then
expect(replacedShape.outgoing[0]).to.exist;
}));
it('should reconnect end', inject(function(elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 80,
height: 80
};
// when
var replacedShape = replace.replaceElement(targetShape, replacement);
// then
expect(replacedShape.incoming[0]).to.exist;
}));
it('should adopt children', inject(function(elementFactory, replace, elementRegistry, eventBus) {
// given
var replacement = {
id: 'replacement',
width: 300,
height: 300
};
// when
var newShape = replace.replaceElement(parentShape, replacement);
// then
expect(newShape.children).to.contain(originalShape);
expect(newShape.children).to.contain(connection);
expect(newShape.children).to.contain(targetShape);
expect(originalShape.parent).to.eql(newShape);
expect(connection.parent).to.eql(newShape);
expect(targetShape.parent).to.eql(newShape);
expect(originalShape.outgoing).to.contain(connection);
expect(targetShape.incoming).to.contain(connection);
}));
it('should adopt children and show them in the DOM',
inject(function(canvas, elementFactory, replace, elementRegistry) {
// given
var replacement = {
id: 'replacement',
width: 300,
height: 300
};
// when
replace.replaceElement(parentShape, replacement);
var newShapeContainer = domQuery('[data-element-id="replacement"]', canvas.getContainer());
// then
expect(domQuery('[data-element-id="originalShape"]', newShapeContainer.parentNode)).to.exist;
expect(domQuery('[data-element-id="targetShape"]', newShapeContainer.parentNode)).to.exist;
})
);
it('should retain moved children in command context', inject(function(replace, eventBus) {
// given
var replacement = {
id: 'replacement',
width: 300,
height: 300
};
eventBus.on('commandStack.elements.move.postExecuted', function(event) {
// then
var shapes = event.context.shapes;
expect(shapes).not.to.be.empty;
expect(shapes).to.have.length(3);
});
// when
replace.replaceElement(parentShape, replacement);
}));
});
describe('undo/redo support', function() {
it('should undo replace', inject(function(elementFactory, replace, elementRegistry, commandStack) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 200
};
replace.replaceElement(originalShape, replacement);
// when
commandStack.undo();
// then
var shape = elementRegistry.get('originalShape');
expect(shape.width).to.equal(100);
}));
it('should redo', inject(function(elementFactory, replace, elementRegistry, commandStack) {
// given
var replacement = {
id: 'replacement',
width: 200,
height: 200
};
replace.replaceElement(originalShape, replacement);
var replacementShape = elementRegistry.get('replacement');
var replacement2 = {
id: 'replacement2',
width: 280,
height: 280
};
replace.replaceElement(replacementShape, replacement2);
// when
commandStack.undo();
commandStack.undo();
commandStack.redo();
commandStack.redo();
// then
var redoShape = elementRegistry.get('replacement2');
expect(redoShape.width).to.equal(280);
}));
});
});
|
module.exports = exports = configure
/**
* Module dependencies.
*/
var fs = require('graceful-fs')
, path = require('path')
, glob = require('glob')
, log = require('npmlog')
, osenv = require('osenv')
, which = require('which')
, semver = require('semver')
, mkdirp = require('mkdirp')
, cp = require('child_process')
, exec = cp.exec
, spawn = cp.spawn
, execFile = cp.execFile
, win = process.platform == 'win32'
exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module'
function configure (gyp, argv, callback) {
var python = gyp.opts.python || process.env.PYTHON || 'python'
, buildDir = path.resolve('build')
, hasVCExpress = false
, hasVC2012Express = false
, hasWin71SDK = false
, hasWin8SDK = false
, configNames = [ 'config.gypi', 'common.gypi' ]
, configs = []
, nodeDir
if (win) {
checkVCExpress(function () {
if (hasVCExpress || hasVC2012Express) {
checkWinSDK(function () {
checkPython()
})
} else {
checkPython()
}
})
} else {
checkPython()
}
// Check if Python is in the $PATH
function checkPython () {
log.verbose('check python', 'checking for Python executable "%s" in the PATH', python)
which(python, function (err, execPath) {
if (err) {
log.verbose('`which` failed for `%s`', python, err)
if (win) {
guessPython()
} else {
failNoPython()
}
} else {
log.verbose('`which` succeeded for `%s`', python, execPath)
checkPythonVersion()
}
})
}
// Called on Windows when "python" isn't available in the current $PATH.
// We're gonna check if "%SystemDrive%\python27\python.exe" exists.
function guessPython () {
log.verbose('could not find "' + python + '". guessing location')
var rootDir = process.env.SystemDrive || 'C:\\'
if (rootDir[rootDir.length - 1] !== '\\') {
rootDir += '\\'
}
var pythonPath = path.resolve(rootDir, 'Python27', 'python.exe')
log.verbose('ensuring that file exists:', pythonPath)
fs.stat(pythonPath, function (err, stat) {
if (err) {
if (err.code == 'ENOENT') {
failNoPython()
} else {
callback(err)
}
return
}
python = pythonPath
checkPythonVersion()
})
}
function checkPythonVersion () {
execFile(python, ['-c', 'from __future__ import print_function; import platform; print(platform.python_version());'], function (err, stdout) {
if (err) {
return callback(err)
}
log.verbose('check python version', '`%s -c "from __future__ import print_function; import platform; print(platform.python_version());"` returned: %j', python, stdout)
var version = stdout.trim()
if (~version.indexOf('+')) {
log.silly('stripping "+" sign(s) from version')
version = version.replace(/\+/g, '')
}
if (semver.gte(version, '2.5.0') && semver.lt(version, '3.0.0')) {
getNodeDir()
} else {
failPythonVersion(version)
}
})
}
function failNoPython () {
callback(new Error('Can\'t find Python executable "' + python +
'", you can set the PYTHON env variable.'))
}
function failPythonVersion (badVersion) {
callback(new Error('Python executable "' + python +
'" is v' + badVersion + ', which is not supported by gyp.\n' +
'You can pass the --python switch to point to Python >= v2.5.0 & < 3.0.0.'))
}
function checkWinSDK(cb) {
checkWin71SDK(function() {
checkWin8SDK(cb)
})
}
function checkWin71SDK(cb) {
spawn('reg', ['query', 'HKLM\\Software\\Microsoft\\Microsoft SDKs\\Windows\\v7.1', '/v', 'InstallationFolder'])
.on('exit', function (code) {
hasWin71SDK = (code === 0)
cb()
})
}
function checkWin8SDK(cb) {
var cp = spawn('reg', ['query', 'HKLM\\Software\\Microsoft\\Windows Kits\\Installed Products', '/f', 'Windows Software Development Kit x86', '/reg:32'])
cp.on('exit', function (code) {
hasWin8SDK = (code === 0)
cb()
})
}
function checkVC2012Express64(cb) {
var cp = spawn('reg', ['query', 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\VCExpress\\11.0\\Setup\\VC', '/v', 'ProductDir'])
cp.on('exit', function (code) {
hasVC2012Express = (code === 0)
cb()
})
}
function checkVC2012Express(cb) {
var cp = spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\VCExpress\\11.0\\Setup\\VC', '/v', 'ProductDir'])
cp.on('exit', function (code) {
hasVC2012Express = (code === 0)
if (code !== 0) {
checkVC2012Express64(cb)
} else {
cb()
}
})
}
function checkVCExpress64(cb) {
var cp = spawn('cmd', ['/C', '%WINDIR%\\SysWOW64\\reg', 'query', 'HKLM\\Software\\Microsoft\\VCExpress\\10.0\\Setup\\VC', '/v', 'ProductDir'])
cp.on('exit', function (code) {
hasVCExpress = (code === 0)
if (code !== 0) {
checkVC2012Express(cb)
} else {
cb()
}
})
}
function checkVCExpress(cb) {
spawn('reg', ['query', 'HKLM\\Software\\Microsoft\\VCExpress\\10.0\\Setup\\VC', '/v', 'ProductDir'])
.on('exit', function (code) {
if (code !== 0) {
checkVCExpress64(cb)
} else {
cb()
}
})
}
function getNodeDir () {
// 'python' should be set by now
process.env.PYTHON = python
if (gyp.opts.nodedir) {
// --nodedir was specified. use that for the dev files
nodeDir = gyp.opts.nodedir.replace(/^~/, osenv.home())
log.verbose('get node dir', 'compiling against specified --nodedir dev files: %s', nodeDir)
createBuildDir()
} else {
// if no --nodedir specified, ensure node dependencies are installed
var version
var versionStr
if (gyp.opts.target) {
// if --target was given, then determine a target version to compile for
versionStr = gyp.opts.target
log.verbose('get node dir', 'compiling against --target node version: %s', versionStr)
} else {
// if no --target was specified then use the current host node version
versionStr = process.version
log.verbose('get node dir', 'no --target version specified, falling back to host node version: %s', versionStr)
}
// make sure we have a valid version
version = semver.parse(versionStr)
if (!version) {
return callback(new Error('Invalid version number: ' + versionStr))
}
// ensure that the target node version's dev files are installed
gyp.opts.ensure = true
gyp.commands.install([ versionStr ], function (err, version) {
if (err) return callback(err)
log.verbose('get node dir', 'target node version installed:', version)
nodeDir = path.resolve(gyp.devDir, version)
createBuildDir()
})
}
}
function createBuildDir () {
log.verbose('build dir', 'attempting to create "build" dir: %s', buildDir)
mkdirp(buildDir, function (err, isNew) {
if (err) return callback(err)
log.verbose('build dir', '"build" dir needed to be created?', isNew)
createConfigFile()
})
}
function createConfigFile (err) {
if (err) return callback(err)
var configFilename = 'config.gypi'
var configPath = path.resolve(buildDir, configFilename)
log.verbose('build/' + configFilename, 'creating config file')
var config = process.config || {}
, defaults = config.target_defaults
, variables = config.variables
if (!defaults) {
defaults = config.target_defaults = {}
}
if (!variables) {
variables = config.variables = {}
}
if (!defaults.cflags) {
defaults.cflags = []
}
if (!defaults.defines) {
defaults.defines = []
}
if (!defaults.include_dirs) {
defaults.include_dirs = []
}
if (!defaults.libraries) {
defaults.libraries = []
}
// set the default_configuration prop
if ('debug' in gyp.opts) {
defaults.default_configuration = gyp.opts.debug ? 'Debug' : 'Release'
}
if (!defaults.default_configuration) {
defaults.default_configuration = 'Release'
}
// set the target_arch variable
variables.target_arch = gyp.opts.arch || process.arch || 'ia32'
// set the toolset for VCExpress users
if (win) {
if (hasVC2012Express && hasWin8SDK) {
defaults.msbuild_toolset = 'v110'
} else if (hasVCExpress && hasWin71SDK) {
defaults.msbuild_toolset = 'Windows7.1SDK'
}
}
// set the node development directory
variables.nodedir = nodeDir
// don't copy dev libraries with nodedir option
variables.copy_dev_lib = !gyp.opts.nodedir
// loop through the rest of the opts and add the unknown ones as variables.
// this allows for module-specific configure flags like:
//
// $ node-gyp configure --shared-libxml2
Object.keys(gyp.opts).forEach(function (opt) {
if (opt === 'argv') return
if (opt in gyp.configDefs) return
variables[opt.replace(/-/g, '_')] = gyp.opts[opt]
})
// ensures that any boolean values from `process.config` get stringified
function boolsToString (k, v) {
if (typeof v === 'boolean')
return String(v)
return v
}
log.silly('build/' + configFilename, config)
// now write out the config.gypi file to the build/ dir
var prefix = '# Do not edit. File was generated by node-gyp\'s "configure" step'
, json = JSON.stringify(config, boolsToString, 2)
log.verbose('build/' + configFilename, 'writing out config file: %s', configPath)
configs.push(configPath)
fs.writeFile(configPath, [prefix, json, ''].join('\n'), findConfigs)
}
function findConfigs (err) {
if (err) return callback(err)
var name = configNames.shift()
if (!name) return runGyp()
var fullPath = path.resolve(name)
log.verbose(name, 'checking for gypi file: %s', fullPath)
fs.stat(fullPath, function (err, stat) {
if (err) {
if (err.code == 'ENOENT') {
findConfigs() // check next gypi filename
} else {
callback(err)
}
} else {
log.verbose(name, 'found gypi file')
configs.push(fullPath)
findConfigs()
}
})
}
function runGyp (err) {
if (err) return callback(err)
if (!~argv.indexOf('-f') && !~argv.indexOf('--format')) {
if (win) {
log.verbose('gyp', 'gyp format was not specified; forcing "msvs"')
// force the 'make' target for non-Windows
argv.push('-f', 'msvs')
} else {
log.verbose('gyp', 'gyp format was not specified; forcing "make"')
// force the 'make' target for non-Windows
argv.push('-f', 'make')
}
}
function hasMsvsVersion () {
return argv.some(function (arg) {
return arg.indexOf('msvs_version') === 0
})
}
if (win && !hasMsvsVersion()) {
if ('msvs_version' in gyp.opts) {
argv.push('-G', 'msvs_version=' + gyp.opts.msvs_version)
} else {
argv.push('-G', 'msvs_version=auto')
}
}
// include all the ".gypi" files that were found
configs.forEach(function (config) {
argv.push('-I', config)
})
// this logic ported from the old `gyp_addon` python file
var gyp_script = path.resolve(__dirname, '..', 'gyp', 'gyp')
var addon_gypi = path.resolve(__dirname, '..', 'addon.gypi')
var common_gypi = path.resolve(nodeDir, 'common.gypi')
var output_dir = 'build'
if (win) {
// Windows expects an absolute path
output_dir = buildDir
}
argv.push('-I', addon_gypi)
argv.push('-I', common_gypi)
argv.push('-Dlibrary=shared_library')
argv.push('-Dvisibility=default')
argv.push('-Dnode_root_dir=' + nodeDir)
argv.push('-Dmodule_root_dir=' + process.cwd())
argv.push('--depth=.')
// tell gyp to write the Makefile/Solution files into output_dir
argv.push('--generator-output', output_dir)
// tell make to write its output into the same dir
argv.push('-Goutput_dir=.')
// enforce use of the "binding.gyp" file
argv.unshift('binding.gyp')
// execute `gyp` from the current target nodedir
argv.unshift(gyp_script)
var cp = gyp.spawn(python, argv)
cp.on('exit', onCpExit)
}
/**
* Called when the `gyp` child process exits.
*/
function onCpExit (code, signal) {
if (code !== 0) {
callback(new Error('`gyp` failed with exit code: ' + code))
} else {
// we're done
callback()
}
}
}
|
/**
* related to main.ui
*
* @Author : and
* @Timestamp : 2016-10-03
*/
// variable
var dojs = require("dojs");
var do_Page = sm("do_Page");
var root = ui("$");
// event
root.on("usreControlInit", function(_option) {
// 调整大小,如果不需要系统状态栏,则高度减少40
if (_option["noSystemStatusBar"]) {
root.height = root.height - 40;
ui("leftButton").y = ui("leftButton").y - 40;
ui("rightButton").y = ui("rightButton").y - 40;
ui("title_label").y = ui("title_label").y - 40;
}
root.redraw();
// 修改title
if (_option["titleLabel"]) {
ui("title_label").set(_option["titleLabel"]);
}
// 支持背景色或背景图片
var background = _option["background"];
if (background) {
if (background.indexOf("source://") >= 0 || background.indexOf("data://") >= 0) {
root.bgImage = background;
} else {
root.bgColor = background;
}
}
//
if (_option["leftButton"]) {
ui("leftImage").set(_option["leftButton"]);
}
if (_option["rightButton"]) {
ui("rightImage").set(_option["rightButton"]);
}
//
ui("leftButton").on("touch", function() {
root.fire("onLeftButtonTouch")
});
ui("rightButton").on("touch", function() {
root.fire("onRightButtonTouch")
});
dojs.style.css(ui("leftImage"), "dynamicButton");
dojs.style.css(ui("rightImage"), "dynamicButton");
if (_option["leftButtonAllowClose"]) {
dojs.page.allowClose(ui("leftButton"));
}
});
// private Function
|
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
return (num - 1) % 9 + 1;
}; |
import webpack from 'webpack'
import webpackConfigBuilder from '../webpack.config'
import colors from 'colors'
import { argv as args, } from 'yargs'
import { ENV_PROD, } from './Env'
const webpackConfig = webpackConfigBuilder(ENV_PROD)
webpack(webpackConfig).run((err, stats) => {
const inSilentMode = args.s
if (!inSilentMode) {
/* eslint-disable no-console */
console.log('Generating minified bundle for production use via Webpack...'.bold.blue)
/* eslint-enable no-console */
}
if (err) {
console.log(err.bold.red) // eslint-disable-line no-console
return 1
}
const jsonStats = stats.toJson()
if (jsonStats.hasErrors) {
/* eslint-disable no-console */
return jsonStats.errors.map(error => console.log(error.red))
/* eslint-enable no-console */
}
if (jsonStats.hasWarnings && !inSilentMode) {
/* eslint-disable no-console */
console.log('Webpack generated the following warnings: '.bold.yellow)
jsonStats.warnings.map(warning => console.log(warning.yellow))
/* eslint-enable no-console */
}
if (!inSilentMode) {
console.log(`Webpack stats: ${stats}`) // eslint-disable-line no-console
}
/* eslint-disable no-console */
console.log('Your app has been compiled in production mode and written to /dist. It\'s ready to roll!'.green.bold)
/* eslint-enable no-console */
return 0
})
|
import { currentRouteName } from '@ember/test-helpers';
import {
module,
test
} from 'qunit';
import setupAuthentication from 'ilios/tests/helpers/setup-authentication';
import page from 'ilios/tests/pages/dashboard';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
module('Acceptance | Dashboard Reports', function(hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
hooks.beforeEach(async function () {
const school = this.server.create('school');
const user = await setupAuthentication( { school } );
const vocabulary = this.server.create('vocabulary');
const term = this.server.create('term', { vocabulary });
this.server.create('academic-year', {
id: 2015
});
this.server.create('academic-year', {
id: 2016
});
const firstCourse = this.server.create('course', {
school,
year: 2015,
externalId: 'Theoretical Phys Ed',
});
this.server.create('session', {
course: firstCourse,
terms: [term],
});
const secondCourse = this.server.create('course', {
school,
year: 2016,
});
this.server.create('session', {
course: secondCourse,
terms: [term],
});
this.server.create('report', {
title: 'my report 0',
subject: 'session',
prepositionalObject: 'course',
prepositionalObjectTableRowId: firstCourse.id,
user,
school,
});
this.server.create('report', {
title: null,
subject: 'session',
prepositionalObject: 'term',
prepositionalObjectTableRowId: term.id,
user,
school,
});
});
test('visiting /dashboard', async function(assert) {
await page.visit();
assert.equal(currentRouteName(), 'dashboard');
});
test('shows reports', async function(assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
assert.equal(page.myReports.reports[0].title, 'All Sessions for term 0 in school 0');
assert.equal(page.myReports.reports[1].title, 'my report 0');
});
test('first report works', async function(assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'my report 0');
assert.equal(page.myReports.selectedReport.results.length, 1);
assert.equal(page.myReports.selectedReport.results[0].text, '2015 - 2016 course 0 session 0');
});
test('no year filter on reports with a course prepositional object', async function(assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'my report 0');
assert.notOk(page.myReports.selectedReport.yearsFilterExists);
});
test('second report works', async function (assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.reports[0].select();
assert.equal(page.myReports.selectedReport.title, 'All Sessions for term 0 in school 0');
assert.equal(page.myReports.selectedReport.results.length, 2);
assert.equal(page.myReports.selectedReport.results[0].text, '2015 - 2016 course 0 session 0');
assert.equal(page.myReports.selectedReport.results[1].text, '2016 - 2017 course 1 session 1');
});
test('year filter works', async function (assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.reports[0].select();
assert.equal(page.myReports.selectedReport.title, 'All Sessions for term 0 in school 0');
assert.ok(page.myReports.selectedReport.yearsFilterExists);
assert.equal(page.myReports.selectedReport.results.length, 2);
await page.myReports.selectedReport.chooseYear('2016');
assert.equal(page.myReports.selectedReport.results.length, 1);
assert.equal(page.myReports.selectedReport.results[0].text, '2016 - 2017 course 1 session 1');
});
test('create new report', async function (assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.addNewReport();
await page.myReports.newReport.setTitle('New Report');
await page.myReports.newReport.chooseSchool('1');
await page.myReports.newReport.chooseSubject('session');
await page.myReports.newReport.chooseObjectType('course');
await page.myReports.newReport.chooseObject('1');
await page.myReports.newReport.save();
assert.equal(page.myReports.reports.length, 3);
await page.myReports.reports[2].select();
assert.equal(page.myReports.selectedReport.title, 'New Report');
assert.equal(page.myReports.selectedReport.results.length, 1);
assert.equal(page.myReports.selectedReport.results[0].text, '2015 - 2016 course 0 session 0');
});
test('filter courses by year in new report form', async function (assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.addNewReport();
await page.myReports.newReport.chooseSchool('1');
await page.myReports.newReport.chooseSubject('session');
await page.myReports.newReport.chooseObjectType('course');
assert.equal(page.myReports.newReport.objectCount, 2);
await page.myReports.newReport.chooseAcademicYear('2016');
assert.equal(page.myReports.newReport.objectCount, 1);
await page.myReports.newReport.chooseObject('2');
await page.myReports.newReport.save();
assert.equal(page.myReports.reports.length, 3);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'All Sessions for course 1 in school 0');
assert.equal(page.myReports.selectedReport.results.length, 1);
assert.equal(page.myReports.selectedReport.results[0].text, '2016 - 2017 course 1 session 1');
});
test('filter session by year in new report form', async function (assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.addNewReport();
await page.myReports.newReport.chooseSchool('1');
await page.myReports.newReport.chooseSubject('term');
await page.myReports.newReport.chooseObjectType('session');
assert.equal(page.myReports.newReport.objectCount, 2);
await page.myReports.newReport.chooseAcademicYear('2016');
assert.equal(page.myReports.newReport.objectCount, 1);
await page.myReports.newReport.chooseObject('2');
await page.myReports.newReport.save();
assert.equal(page.myReports.reports.length, 3);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'All Terms for session 1 in school 0');
assert.equal(page.myReports.selectedReport.results.length, 1);
assert.equal(page.myReports.selectedReport.results[0].text, 'Vocabulary 1 > term 0');
});
test('get all courses associated with mesh term #3419', async function (assert) {
this.server.create('mesh-descriptor', {
id: 'D1234',
courseIds: [1, 2]
});
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.addNewReport();
await page.myReports.newReport.chooseSchool('1');
await page.myReports.newReport.chooseSubject('course');
await page.myReports.newReport.chooseObjectType('mesh term');
await page.myReports.newReport.fillMeshSearch('0');
await page.myReports.newReport.runMeshSearch();
assert.equal(page.myReports.newReport.meshSearchResults.length, 1);
assert.equal(page.myReports.newReport.meshSearchResults[0].text, 'descriptor 0 D1234');
await page.myReports.newReport.meshSearchResults[0].pick();
await page.myReports.newReport.save();
assert.equal(page.myReports.reports.length, 3);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'All Courses for descriptor 0 in school 0');
assert.equal(page.myReports.selectedReport.results.length, 2);
assert.equal(page.myReports.selectedReport.results[0].text, '2015 - 2016 course 0 (Theoretical Phys Ed)');
assert.equal(page.myReports.selectedReport.results[1].text, '2016 - 2017 course 1');
});
test('Prepositional object resets when a new type is selected', async function (assert) {
this.server.create('course', {
year: '2016',
schoolId: 1
});
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.addNewReport();
await page.myReports.newReport.chooseSchool('1');
await page.myReports.newReport.chooseSubject('term');
await page.myReports.newReport.chooseObjectType('session');
await page.myReports.newReport.chooseObject('2');
await page.myReports.newReport.chooseObjectType('course');
await page.myReports.newReport.save();
assert.equal(page.myReports.reports.length, 3);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'All Terms for course 0 in school 0');
});
test('Report Selector with Academic Year not selecting correct predicate #3427', async function (assert) {
this.server.create('course', {
year: '2016',
schoolId: 1
});
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.addNewReport();
await page.myReports.newReport.chooseSchool('1');
await page.myReports.newReport.chooseSubject('term');
await page.myReports.newReport.chooseObjectType('course');
await page.myReports.newReport.chooseAcademicYear('2016');
await page.myReports.newReport.save();
assert.equal(page.myReports.reports.length, 3);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'All Terms for course 1 in school 0');
});
test('course external Id in report', async function (assert) {
await page.visit();
assert.equal(page.myReports.reports.length, 2);
await page.myReports.addNewReport();
await page.myReports.newReport.chooseSchool('All Schools');
await page.myReports.newReport.chooseSubject('course');
await page.myReports.newReport.save();
assert.equal(page.myReports.reports.length, 3);
await page.myReports.reports[1].select();
assert.equal(page.myReports.selectedReport.title, 'All Courses in All Schools');
assert.equal(page.myReports.selectedReport.results.length, 2);
assert.equal(page.myReports.selectedReport.results[0].text, '2015 - 2016 course 0 (Theoretical Phys Ed)');
assert.equal(page.myReports.selectedReport.results[1].text, '2016 - 2017 course 1');
});
});
|
import Custom from './custom'
const scroll = new Custom({
extends: true,
preload: true,
noscrollbar: true,
section: document.querySelector('.vs-section'),
divs: document.querySelectorAll('.vs-div')
})
scroll.init()
// setTimeout(() => {
// scroll.destroy()
// }, 1500) |
import Charts from 'react-chartjs';
import moment from 'moment';
import numeral from 'numeral';
import GBP from '../model/GBP';
import { Panel } from '../hg/Panel';
import { el, $, Component } from '../react-utils';
console.log('foo');
export class SimpleChart extends Component {
render() {
var transactions = this.props.transactions
, start = moment().startOf('month')
, months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
.reverse()
.map(x => {
return start.clone().subtract(x, 'months')
});
// TODO: This is no good
// Dave's approach is to use a key for each transaction like 'jan-2015'
// and grouping on that instead of running the isSame all the time
var groupedTransactions = months.map(month => {
return transactions.filter(transaction => {
return moment(transaction.date).isSame(month, 'month');
});
});
var monthSums = groupedTransactions.map(group => {
return group
.map(x => x.amount)
.map(x => new GBP(x.pence *= -1)) // Invert
.reduce((x, y) => x.add(y), new GBP())
.pence / 100;
});
var monthLabels = months.map(month => month.format('MMM YYYY'));
return el(Charts.Line, {
className: 'sparkline',
data: {
labels: monthLabels,
datasets: [{
label: 'Total',
strokeColor: 'rgba(255, 255, 255, 0.5)',
// pointColor: 'hsl(174, 67%, 55%)',
data: monthSums
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scaleLineColor: "rgba(0,0,0,0)",
scaleShowLabels: false,
scaleShowGridLines: false,
pointDot: false,
datasetFill: false,
scaleFontSize: 1,
scaleFontColor: "rgba(0,0,0,0)"
}
});
}
}
|
'use strict'
module.exports = function(app, middlewares, routeMiddlewares) {
return middlewares.validToken
}
|
// region import
import crypto from 'crypto'
import jwt from 'jsonwebtoken'
// internal
import {provide} from '../utilities/modules'
// endregion
// region crypto
const key = 'secret'
const hashPassword = ({password, salt}) => new Promise((resolve, reject) =>
crypto.pbkdf2(password, salt, 64000, 512, 'sha512', (error, hash) => error
? reject(error)
: resolve(hash.toString('base64'))
)
)
// endregion
// region export
export const verify = async (token) =>
jwt.verify(token, key, {
algorithms: ['HS256']
})
export const create = async ({name, password}) => {
const {salt, hash} = await provide.user({name})
const realHash = await hashPassword({password, salt})
if (hash === realHash)
return jwt.sign({
name
}, key, {
expiresIn: '86400s'
})
throw 'wrong password'
}
// endregion
|
angular
.module('openeApp.cases.members')
.factory('caseMembersService', caseMembersService);
function caseMembersService($http, $q) {
var service = {
getCaseMembers: getCaseMembers,
createCaseMembers: createCaseMembers,
changeCaseMember: changeCaseMember,
deleteCaseMember: deleteCaseMember
};
return service;
function getCaseMembers(caseId) {
return $http.get('/api/openesdh/case/' + caseId + '/members')
.then(successOrReject);
}
function createCaseMembers(caseId, role, authorities) {
return $http.post('/api/openesdh/case/' + caseId + '/members', null,
{
params: {
authorityNodeRefs: authorities,
role: role
}
}).then(successOrReject);
}
function changeCaseMember(caseId, authority, oldRole, newRole) {
return $http.post('/api/openesdh/case/' + caseId + '/members', null,
{
params: {
authority: authority,
role: newRole,
fromRole: oldRole
}
}).then(successOrReject);
}
function deleteCaseMember(caseId, authority, role) {
return $http.delete('/api/openesdh/case/' + caseId + '/member',
{params: {
authority: authority,
role: role
}}).then(successOrReject);
}
function successOrReject(response) {
if (response.status && response.status !== 200) {
return $q.reject(response);
}
return response.data;
}
} |
var storage = new Firebase('https://fiery-torch-5161.firebaseio.com/'),
rooms = storage.child('rooms'),
currentRoom = null,
currentUrl = null;
// Setup listener for form submit on popup.html
chrome.runtime.onMessage.addListener(function(message,sender,callback) {
if (message.name === 'form_submit') {
currentRoom = message.data;
console.log('currentRoom =', currentRoom);
}
});
// Listen for changes in relevant child
rooms.on('child_changed', function(dataSnapshot) {
var data = dataSnapshot.val(),
childRoom = dataSnapshot.name(),
newUrl = data.url;
if ((childRoom === currentRoom) && !(currentUrl === newUrl)) {
chrome.tabs.query({'active':true, 'lastFocusedWindow': true}, function(result) {
var id = result[0].id;
chrome.tabs.update(id, {url: newUrl});
});
}
});
// If room is set, submit change to relevant child in storage
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (currentRoom && !(currentUrl === tab.url)) {
currentUrl = tab.url;
console.log('Update ',currentRoom)
rooms.child(currentRoom).update({url: tab.url});
}
});
|
var assert = require('assert');
var vows = require('vows');
var EventEmitter = require('../src/eventful.js');
vows.describe('Validations').addBatch({
'An event emitter' : {
topic : function() {
return new EventEmitter();
},
'should only accept functions as callbacks' : function(topic) {
// undefined is not tested as calling on with only an event name is allowed
var invalid = [ null, true, false, 2, 'string', [], {} ];
for (var i in invalid) {
assert.throws(function() { topic.on('foo', invalid[i]); }, Error);
}
},
'should only accept non-empty word strings as events' : function(topic) {
var invalid = [ undefined, null, true, false, 2, [], {}, '', '%/&' ];
var callback = function() {};
for (var i in invalid) {
assert.throws(function() { topic.on(invalid[i], callback); }, Error);
}
},
'should only accept strings as a namespace' : function(topic) {
var invalid = [ null, true, false, 2, [], {} ];
for (var i in invalid) {
assert.throws(function() { topic.namespace(invalid[i])}, Error);
}
}
}
}).export(module);
|
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
/*
* Global setup/hooks for mocha
*/
after(function() {
if (window.__coverage__) {
console.log('Found coverage report, writing to coverage/coverage.json');
var path = require('path');
var fs = require('fs');
var coverageDir = path.resolve(process.cwd(), 'coverage');
if (!fs.existsSync(coverageDir)) {
fs.mkdirSync(coverageDir);
}
fs.writeFileSync(path.resolve(coverageDir, 'coverage.json'), JSON.stringify(window.__coverage__));
}
});
|
var fs = require('fs');
var path = require('path');
module.exports = function(template) {
template.dependencies = [];
var cacheStore = template.cache;
var defaults = template.defaults;
var rExtname;
// 提供新的配置字段
defaults.base = '';
defaults.extname = '.html';
defaults.encoding = 'utf-8';
// 重写引擎编译结果获取方法
template.get = function(filename) {
var fn;
if (cacheStore.hasOwnProperty(filename)) {
// 使用内存缓存
fn = cacheStore[filename];
} else {
// 加载模板并编译
var source = readTemplate(filename);
if (typeof source === 'string') {
fn = template.compile(source, {
filename: filename
});
}
}
return fn;
};
function readTemplate(id) {
id = path.join(defaults.base, id + defaults.extname);
if (id.indexOf(defaults.base) !== 0) {
// 安全限制:禁止超出模板目录之外调用文件
throw new Error('"' + id + '" is not in the template directory');
} else {
try {
return fs.readFileSync(id, defaults.encoding);
} catch (e) {}
}
}
// 重写模板`include``语句实现方法,转换模板为绝对路径
template.utils.$include = function(filename, data, from) {
from = path.dirname(from);
if (filename && filename.charAt('0') === '/') {
filename = path.join(defaults.projectRoot, filename);
} else {
filename = path.join(from, filename);
}
template.dependencies.push(filename);//将被include的文件添加到dependencies
return template.renderFile(filename, data);
}
// express support
template.__express = function(file, options, fn) {
if (typeof options === 'function') {
fn = options;
options = {};
}
if (!rExtname) {
// 去掉 express 传入的路径
rExtname = new RegExp((defaults.extname + '$').replace(/\./g, '\\.'));
}
file = file.replace(rExtname, '');
options.filename = file;
fn(null, template.renderFile(file, options));
};
return template;
}
|
const ERROR = {
SUCCESS: [0, 'success'],
// SYSTEM_ERROR xx
NOT_IMPLEMENTED: [11, '不支持该方法'],
UNKONWN_ERROR: [99, '未知错误'],
// USER_ERROR 1xx
NOT_LOGIN: [101, '未登录']
};
export {ERROR} |
/**
* Created by Administrator on 2017/9/19.
*/
(function () {
'use strict';
angular.module('starter.controllers')
.controller('LoginCtrl',['$scope','localStorageService','$state','$ionicPopup',function ($scope,localStorageService,$state,$ionicPopup) {
var USER_KEY='User';
$scope.user={
username:'',
password:''
};
$scope.login=function () {
var account=localStorageService.get(USER_KEY,{
username:'asd',
password:'123'
});
if (account.username===$scope.user.username&&account.password===$scope.user.password){
account.isLogin=true;
localStorageService.update(USER_KEY,account);
$state.go('app.home');
}
else {
$ionicPopup.alert({
title:'警告',
template:'用户名或密码错误',
okText:'确定',
okType:'button-energized'
});
}
};
}]);
})();
|
var group___f_m_c___l_l___n_o_r_s_r_a_m =
[
[ "NOR SRAM Initialization/de-initialization functions", "group___f_m_c___l_l___n_o_r_s_r_a_m___private___functions___group1.html", null ],
[ "NOR SRAM Control functions", "group___f_m_c___l_l___n_o_r_s_r_a_m___private___functions___group2.html", null ]
]; |
/* global module:false */
module.exports = function(grunt) {
var port = grunt.option('port') || 8000;
var base = grunt.option('base') || '.';
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
build: {
src: 'js/reveal.js',
dest: 'js/reveal.min.js'
}
},
sass: {
core: {
files: {
'css/reveal.css': 'css/reveal.scss',
}
},
themes: {
files: [
{
expand: true,
cwd: 'css/theme/source',
src: ['*.scss'],
dest: 'css/theme',
ext: '.css'
}
]
}
},
autoprefixer: {
dist: {
src: 'css/reveal.css'
}
},
cssmin: {
compress: {
files: {
'css/reveal.min.css': [ 'css/reveal.css' ]
}
}
},
jshint: {
options: {
curly: false,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
eqnull: true,
browser: true,
expr: true,
globals: {
head: false,
module: false,
console: false,
unescape: false,
define: false,
exports: false
}
},
files: [ 'Gruntfile.js', 'js/reveal.js' ]
},
connect: {
server: {
options: {
port: port,
base: base,
livereload: true,
open: true
}
}
},
zip: {
'reveal-js-presentation.zip': [
'index.html',
'css/**',
'js/**',
'lib/**',
'images/**',
'plugin/**'
]
},
watch: {
options: {
livereload: true
},
js: {
files: [ 'Gruntfile.js', 'js/reveal.js' ],
tasks: 'js'
},
theme: {
files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ],
tasks: 'css-themes'
},
css: {
files: [ 'css/reveal.scss' ],
tasks: 'css-core'
},
html: {
files: [ 'index.html']
}
}
});
// Dependencies
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.loadNpmTasks( 'grunt-sass' );
grunt.loadNpmTasks( 'grunt-contrib-connect' );
grunt.loadNpmTasks( 'grunt-autoprefixer' );
grunt.loadNpmTasks( 'grunt-zip' );
// Default task
grunt.registerTask( 'default', [ 'css', 'js' ] );
// JS task
grunt.registerTask( 'js', [ 'jshint', 'uglify' ] );
// Theme CSS
grunt.registerTask( 'css-themes', [ 'sass:themes' ] );
// Core framework CSS
grunt.registerTask( 'css-core', [ 'sass:core', 'autoprefixer', 'cssmin' ] );
// All CSS
grunt.registerTask( 'css', [ 'sass', 'autoprefixer', 'cssmin' ] );
// Package presentation to archive
grunt.registerTask( 'package', [ 'default', 'zip' ] );
// Serve presentation locally
grunt.registerTask( 'serve', [ 'connect', 'watch' ] );
// Run tests
grunt.registerTask( 'test', [ 'jshint' ] );
};
|
describe("x-tag ", function () {
it('should load x-tag.js and fire DOMComponentsLoaded', function (){
var DOMComponentsLoaded = false;
var WebComponentsReady = true;
var HTMLImportsLoaded = false;
document.addEventListener('DOMComponentsLoaded', function (){
DOMComponentsLoaded = true;
});
window.addEventListener('WebComponentsReady', function (){
WebComponentsReady = true;
});
window.addEventListener('HTMLImportsLoaded', function (){
HTMLImportsLoaded = true;
});
var xtagLoaded = false,
script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function(){
xtagLoaded = true;
DOMComponentsLoaded = true;
};
document.querySelector('head').appendChild(script);
script.src = '../src/core.js?d=' + new Date().getTime();
waitsFor(function(){
return xtagLoaded && DOMComponentsLoaded && WebComponentsReady && xtag;
}, "document.register should be polyfilled", 1000);
runs(function () {
expect(xtag).toBeDefined();
});
});
it('upgrades all elements synchronously when registered', function (){
var createdFired = false;
xtag.register('x-sync', {
lifecycle: {
created: function (){
createdFired = true;
}
},
accessors: {
foo: {
get: function(){
return 'bar';
}
}
}
});
var created = document.createElement('x-sync');
var existing = document.getElementById('sync_element');
waitsFor(function (){
return createdFired;
}, "new tag lifecycle event CREATED should fire", 500);
runs(function (){
expect(existing.foo).toEqual('bar');
});
});
it('all new element proto objects should be unique', function (){
var createdFired = false;
xtag.register('x-unique', {
lifecycle: {
created: function (){
createdFired = true;
}
}
});
var u1 = document.createElement('x-unique');
var u2 = document.createElement('x-unique');
waitsFor(function (){
return createdFired;
}, "new tag lifecycle event CREATED should fire", 500);
runs(function (){
expect(u1.xtag == u2.xtag).toEqual(false);
});
});
it('all elements should be parsed for attributes and sync to setters', function (){
var createdFired = false,
foo = 0,
bar = 0,
baz = 0,
zoo = 0;
def = 0;
xtag.register('x-attr', {
lifecycle: {
created: function (){
createdFired = true;
this.innerHTML = '<div foo="bar">';
}
},
accessors: {
foo: {
attribute: {
selector: 'div'
},
set: function (value){
foo++;
}
},
bar: {
attribute: { boolean: true },
set: function (value){
bar++;
}
},
baz: {
attribute: {},
set: function (value){
baz++;
}
},
zoo: {
attribute: { boolean: true },
set: function (value){
zoo++;
}
},
defAttr: {
attribute: { def: 'seahawks' },
set: function (value){
def++;
}
}
}
});
var el = document.getElementById('attr_element');
//var el = document.createElement('x-attr');
el.foo = 'foo-1';
el.setAttribute('foo', 'foo-2');
el.setAttribute('foo', 'foo-2');
el.foo = 'foo-2';
el.removeAttribute('foo');
el.setAttribute('foo', 'foo-3');
el.setAttribute('bar', true);
el.bar = false;
el.bar = true;
el.removeAttribute('bar');
el.bar = 'bar';
el.bar = false;
el.baz = 'baz-0';
el.removeAttribute('baz');
el.setAttribute('baz', 'baz-1');
el.setAttribute('baz', 'baz-1');
el.removeAttribute('baz');
el.zoo = false;
el.zoo = true;
el.removeAttribute('zoo');
el.setAttribute('zoo', true);
el.setAttribute('zoo', true);
el.zoo = true;
waitsFor(function (){
return createdFired;
}, "new tag lifecycle event CREATED should fire", 500);
runs(function (){
expect(el.foo).toEqual('foo-3');
expect(el.getAttribute('foo')).toEqual('foo-3');
expect(el.bar).toEqual(false);
expect(el.getAttribute('bar')).toEqual(null);
expect(el.baz).toEqual(null);
expect(el.getAttribute('baz')).toEqual(null);
expect(el.zoo).toEqual(true);
expect(el.getAttribute('zoo')).toEqual('');
expect(el.defAttr).toEqual('seahawks');
expect(foo == 6 && bar == 7 && baz == 6 && zoo == 7 && def == 1).toEqual(true);
});
});
it('should set the default value when provided', function(){
var valueOnCreate, valueOnAccess;
xtag.register('x-set-default-value', {
lifecycle: {
finalized: function(){
valueOnCreate = this.foo;
}
},
accessors: {
foo: {
attribute: {
def: 5
}
}
}
});
var node = document.createElement('x-set-default-value');
valueOnAccess = node.foo;
waitsFor(function(){
return valueOnCreate && valueOnAccess;
});
runs(function (){
expect(valueOnCreate == 5).toEqual(true);
expect(valueOnAccess == 5).toEqual(true);
});
});
it('should fire attributeChanged when attributes are updated', function(){
var attributeChanged = false;
xtag.register('x-foo1', {
lifecycle: {
attributeChanged: function(){
attributeChanged = true;
}
}
});
var foo1 = document.createElement('x-foo1');
foo1.setAttribute('foo', 'bar');
foo1.setAttribute('foo', 'adf');
waitsFor(function(){
return attributeChanged;
});
runs(function (){
expect(attributeChanged).toEqual(true);
});
});
it('should fire lifecycle event CREATED when a new tag is created', function (){
var createdFired = false;
xtag.register('x-foo2', {
lifecycle: {
created: function (){
createdFired = true;
}
}
});
var foo = document.createElement('x-foo2');
waitsFor(function (){
return createdFired;
}, "new tag lifecycle event CREATED should fire", 500);
runs(function (){
expect(createdFired).toEqual(true);
});
});
describe('using testbox', function (){
var testbox;
beforeEach(function (){
testbox = document.getElementById('testbox');
});
afterEach(function (){
testbox.innerHTML = "";
});
it('testbox should exist', function (){
expect(testbox).toBeDefined();
});
it('should fire CREATED when tag is added to innerHTML', function (){
var created = false;
xtag.register('x-foo3', {
lifecycle: {
created: function (){
created = true;
}
},
methods: {
bar: function (){
return true;
}
}
});
xtag.set(testbox, 'innerHTML', '<x-foo3 id="foo"></x-foo3>');
waitsFor(function (){
return created;
}, "new tag lifecycle event {created} should fire", 500);
runs(function (){
var fooElement = document.getElementById('foo');
expect(created).toEqual(true);
expect(fooElement.bar()).toEqual(true);
});
});
it('should fire CREATED when custom element is added within a parent to innerHTML', function (){
var created = false;
xtag.register('x-foo4', {
lifecycle: {
created: function(){
created = true;
}
},
methods: {
bar: function (){
return true;
},
zoo: function(){
return true;
}
}
});
xtag.set(testbox, 'innerHTML', '<div><x-foo4 id="foo" class="zoo"></x-foo4></div>');
waitsFor(function (){
return created;
}, "new tag lifecycle event {created} should fire", 500);
runs(function (){
var fooElement = document.getElementById('foo');
expect(created).toEqual(true);
expect(fooElement.bar()).toEqual(true);
});
});
it('should fire INSERTED when injected into the DOM', function (){
var inserted = false;
xtag.register('x-foo5', {
lifecycle: {
inserted: function (){
inserted = true;
}
}
});
var foo = document.createElement('x-foo5');
testbox.appendChild(foo);
waitsFor(function (){
return inserted;
}, "new tag onInsert should fire", 1000);
runs(function (){
expect(inserted).toEqual(true);
});
});
it('should fire REMOVED when removed into the DOM (w/inserted)', function (){
var removed = false;
xtag.register('x-foo5-removed', {
lifecycle: {
inserted: function (){},
removed: function (){
removed = true;
}
}
});
var foo = document.createElement('x-foo5-removed');
testbox.appendChild(foo);
setTimeout(function(){
testbox.removeChild(foo);
},100);
waitsFor(function (){
return removed;
}, "new tag removed should fire", 500);
runs(function (){
expect(removed).toEqual(true);
});
});
it('should fire REMOVED when removed into the DOM', function (){
var removed = false;
xtag.register('x-foo5-removed-1', {
lifecycle: {
removed: function (){
removed = true;
}
}
});
var foo = document.createElement('x-foo5-removed-1');
testbox.appendChild(foo);
setTimeout(function(){
testbox.removeChild(foo);
},100);
waitsFor(function (){
return removed;
}, "new tag removed should fire", 500);
runs(function (){
expect(removed).toEqual(true);
});
});
it('should parse new tag as soon as it is registered', function (){
var foo = document.createElement('x-foo6');
testbox.appendChild(foo);
xtag.register('x-foo6', {
methods: {
bar: function(){ return 'baz'; }
}
});
runs(function (){
expect(foo.bar()).toEqual('baz');
});
});
it('should register methods for element', function (){
xtag.register('x-foo7', {
methods: {
baz: function (){ }
}
});
var foo = document.createElement('x-foo7');
testbox.appendChild(foo);
expect(foo.baz).toBeDefined();
});
it('should register getters for element', function (){
xtag.register('x-foo8', {
accessors: {
name: {
get: function (){
return this.nodeName;
}
}
}
});
var foo = document.createElement('x-foo8');
testbox.appendChild(foo);
expect(foo.name).toEqual('X-FOO8');
});
it('should register setters for element', function (){
xtag.register('x-foo9', {
accessors: {
name: {
set: function (value){
this.setAttribute('name', value);
}
}
}
});
var foo = document.createElement('x-foo9');
testbox.appendChild(foo);
foo.name = 'pizza';
expect(foo.getAttribute('name')).toEqual('pizza');
});
it('xtag.innerHTML should instantiate x-tags in innerHTML', function (){
xtag.register('x-foo10', {
accessors: {
name: {
set: function (value){
this.setAttribute('name', value);
}
}
}
});
xtag.innerHTML(testbox, '<x-foo10 id="foo"></x-foo10>');
var foo = document.getElementById('foo');
foo.name = "Bob";
expect(foo.getAttribute('name')).toEqual('Bob');
});
it('should only fire INSERT when inserted into the DOM', function (){
var inserted = false;
xtag.register('x-foo11', {
lifecycle: {
inserted: function (){
inserted = true;
}
}
});
var temp = document.createElement('div');
temp.id = 'ZZZZZZZZZZZZZZZZZZZZZ';
temp.appendChild(document.createElement('x-foo11'));
expect(inserted).toEqual(false);
testbox.appendChild(temp);
waitsFor(function (){
return inserted;
}, "new tag onInsert should fire", 500);
runs(function (){
expect(inserted).toEqual(true);
});
});
it("mixins should not override existing properties", function (){
var onCreateFired = 0;
xtag.mixins.test = {
lifecycle: {
created: function (){
onCreateFired++;
}
}
};
xtag.register('x-foo12', {
mixins: ['test'],
lifecycle: {
created: function (){
onCreateFired++;
}
}
});
var foo = document.createElement('x-foo12');
expect(2).toEqual(onCreateFired);
});
it("should create a mixin, fire CREATED", function (){
var onCreateFired = false;
xtag.mixins.test = {
lifecycle: {
created: function (){
onCreateFired = true;
}
}
};
xtag.register('x-foo13', {
mixins: ['test']
});
var foo = document.createElement('x-foo13');
expect(true).toEqual(onCreateFired);
});
it("should create a mixin, fire inserted", function (){
var onInsertFired = false;
xtag.mixins.test = {
lifecycle: {
inserted: function (){
onInsertFired = true;
}
}
};
xtag.register('x-foo14', {
mixins: ['test']
});
var foo = document.createElement('x-foo14');
testbox.appendChild(foo);
waitsFor(function (){
return onInsertFired;
}, "new tag mixin inserted should fire", 500);
runs(function (){
expect(true).toEqual(onInsertFired);
});
});
it("mixins should wrap functions by default", function (){
var count = 0,
mixinFired,
originalFired;
xtag.mixins.wrapFn = {
lifecycle: {
created: function (){
mixinFired = ++count;
}
}
};
xtag.register('x-foo-mixin-fn', {
mixins: ['wrapFn'],
lifecycle: {
'created:mixins': function (){
originalFired = ++count;
}
}
});
var foo = document.createElement('x-foo-mixin-fn');
waitsFor(function (){
return mixinFired && originalFired;
}, "new tag mixin created should fire", 500);
runs(function (){
expect(1).toEqual(mixinFired);
expect(2).toEqual(originalFired);
});
});
it("should fire all mixins, even when there is no base function", function (){
var count = 0,
mixinOne,
mixinTwo;
xtag.mixins.mixinOne = {
lifecycle: {
created: function (){
mixinOne = ++count;
}
}
};
xtag.mixins.mixinTwo = {
lifecycle: {
created: function (){
mixinTwo = ++count;
}
}
};
xtag.register('x-foo-multi-mixin', {
mixins: ['mixinOne', 'mixinTwo']
});
var foo = document.createElement('x-foo-multi-mixin');
waitsFor(function (){
return count == 2;
}, "new tag mixin created should fire", 500);
runs(function (){
expect(2).toEqual(mixinOne);
expect(1).toEqual(mixinTwo);
});
});
it("it should fire the mixin created function BEFORE the element's", function (){
var count = 0,
createdFired1,
createdFired2;
xtag.mixins.test = {
lifecycle: {
created: function (){
createdFired1 = ++count;
}
}
};
xtag.register('x-foo15', {
mixins: ['test'],
lifecycle: {
'created:mixins(before)': function (){
createdFired2 = ++count;
}
}
});
var foo = document.createElement('x-foo15');
testbox.appendChild(foo);
waitsFor(function (){
return createdFired1 && createdFired2;
}, "new tag mixin created should fire", 500);
runs(function (){
expect(1).toEqual(createdFired1);
expect(2).toEqual(createdFired2);
});
});
it("it should fire the mixin created function AFTER the element's", function (){
var count = 0,
createdFired1,
createdFired2;
xtag.mixins.test = {
lifecycle: {
'created': function (){
createdFired2 = ++count;
}
}
};
xtag.register('x-foo16', {
mixins: ['test'],
lifecycle: {
'created:mixins(after)': function (){
createdFired1 = ++count;
}
}
});
var foo = document.createElement('x-foo16');
testbox.appendChild(foo);
waitsFor(function (){
return createdFired1 && createdFired2;
}, "new tag mixin created should fire", 500);
runs(function (){
expect(1).toEqual(createdFired1);
expect(2).toEqual(createdFired2);
});
});
it("it should fire the mixin created function BEFORE, WHEN NO OPTION IS PASSED the element's", function (){
var count = 0,
createdFired1,
createdFired2;
xtag.mixins.test = {
lifecycle: {
'created': function (){
createdFired2 = ++count;
}
}
};
xtag.register('x-foo17', {
mixins: ['test'],
lifecycle: {
'created:mixins': function (){
createdFired1 = ++count;
}
}
});
var foo = document.createElement('x-foo17');
testbox.appendChild(foo);
waitsFor(function (){
return createdFired1 && createdFired2;
}, "new tag mixin created should fire", 500);
runs(function (){
expect(2).toEqual(createdFired1);
expect(1).toEqual(createdFired2);
});
});
it("should allow mixins to create getters", function (){
var count = 0, base, mixin;
xtag.mixins.test = {
accessors: {
bar: {
get: function (){
mixin = ++count;
return "barr";
}
}
}
};
xtag.register('x-foo18', {
mixins: ['test'],
accessors: {
bar: {
'get:mixins': function (){
base = ++count;
return "barr";
}
}
}
});
var foo = document.createElement('x-foo18');
var testing = foo.bar;
expect(mixin).toEqual(1);
expect(base).toEqual(2);
});
it("should allow mixins to create setters", function (){
xtag.mixins.test = {
accessors: {
foo: {
set: function (value){
this.setAttribute('foo', value);
}
}
}
};
xtag.register('x-foo19', {
mixins: ['test']
});
var foo = document.createElement('x-foo19');
foo.foo = 'barr';
expect('barr').toEqual(foo.getAttribute('foo'));
});
it("should allow mixins to handle events", function (){
var mixinEvent1 = 0,
mixinEvent2 = 0,
mixinEvent3 = 0,
mixinEvent4 = 0,
count = 0;
xtag.mixins.test = {
events: {
'click': function(e){
mixinEvent1 = ++count;
},
'bar': function(){
mixinEvent4 = ++count;
}
}
};
xtag.register('x-foo20', {
mixins: ['test'],
events: {
'click': function(e){
mixinEvent2 = ++count;
},
'foo': function(e){
mixinEvent3 = ++count;
xtag.fireEvent(this, 'bar');
}
}
});
var foo = document.createElement('x-foo20');
testbox.appendChild(foo);
xtag.fireEvent(foo, 'click');
xtag.fireEvent(foo, 'foo');
runs(function (){
expect(mixinEvent1).toEqual(2);
expect(mixinEvent2).toEqual(1);
expect(mixinEvent3).toEqual(3);
expect(mixinEvent4).toEqual(4);
});
});
it('delegate event pseudo should pass the custom element as second param', function (){
var customElement, currentTarget;
xtag.register('x-foo21', {
lifecycle: {
created: function (){
customElement = this;
this.innerHTML = '<div><div></div></div>';
}
},
events: {
'click:delegate(div > div:first-child)': function (e, elem){
currentTarget = e.currentTarget;
}
}
});
var foo = document.createElement('x-foo21');
testbox.appendChild(foo);
waitsFor(function (){
return customElement;
}, "new tag mixin onInsert should fire", 500);
runs(function (){
xtag.fireEvent(xtag.query(customElement, 'div')[1], 'click');
expect(customElement).toEqual(currentTarget);
});
});
it('delegate event pseudo should register a click on an inner element', function (){
var clicked = false, customElement;
xtag.register('x-foo22', {
lifecycle: {
created: function (){
customElement = this;
this.innerHTML = '<div><div></div></div>';
}
},
events: {
'click:delegate(div:not(:nth-child(2)))': function (e, elem){
clicked = true;
}
}
});
var foo = document.createElement('x-foo22');
testbox.appendChild(foo);
waitsFor(function (){
return customElement;
}, "new tag mixin onInsert should fire", 500);
runs(function (){
xtag.fireEvent(xtag.query(customElement, 'div')[1], 'click');
expect(clicked).toEqual(true);
});
});
it('delegate event pseudo should register a click on an inner pseudo element', function (){
var clicked = false, customElement;
xtag.register('x-foo22-b', {
lifecycle: {
created: function (){
customElement = this;
this.innerHTML = '<div></div><div></div>';
}
},
events: {
'click:delegate(div:nth-child(2))': function (e, elem){
clicked = true;
}
}
});
var foo = document.createElement('x-foo22-b');
testbox.appendChild(foo);
waitsFor(function (){
return customElement;
}, "new tag mixin onInsert should fire", 1000);
runs(function (){
xtag.fireEvent(xtag.query(customElement, 'div')[1], 'click');
expect(clicked).toEqual(true);
});
});
it('delegate event pseudo "this" should be the element filtered by pseudo', function (){
var customElement, delegateElement;
xtag.register('x-foo23', {
lifecycle: {
created: function (){
customElement = this;
this.innerHTML = '<div></div>';
}
},
events: {
'click:delegate(div)': function (e, elem){
delegateElement = this;
}
}
});
var foo = document.createElement('x-foo23');
testbox.appendChild(foo);
waitsFor(function (){
return customElement;
}, "new tag mixin onInsert should fire", 500);
runs(function (){
xtag.fireEvent(xtag.query(customElement, 'div')[0], 'click');
expect(delegateElement).toEqual(customElement.firstElementChild);
});
});
it('delegate event pseudo should support chaining', function (){
var clickThis = null;
xtag.register('x-foo24', {
lifecycle: {
created: function (){
this.innerHTML = '<div><foo><bazz></bazz></foo></div>';
}
},
events: {
'click:delegate(div):delegate(bazz)': function (e, elem){
clickThis = this;
}
}
});
var foo = document.createElement('x-foo24');
testbox.appendChild(foo);
var innerDiv = xtag.query(foo,'bazz')[0];
xtag.fireEvent(innerDiv,'click');
expect(innerDiv).toEqual(clickThis);
});
it('setter foo should setAttribute foo on target', function (){
xtag.register('x-foo25', {
accessors:{
foo: { attribute: {} }
}
});
var foo = document.createElement('x-foo25');
testbox.appendChild(foo);
foo.foo = 'bar';
expect(foo.getAttribute('foo')).toEqual('bar');
});
it('setter foo should setAttribute bar on target', function (){
xtag.register('x-foo26', {
accessors:{
foo: {
attribute: { name: 'bar' }
}
}
});
var foo = document.createElement('x-foo26');
testbox.appendChild(foo);
foo.foo = 'bar';
expect(foo.getAttribute('bar')).toEqual('bar');
});
it('setter fooBar should auto link to the attribute name foo-bar', function (){
xtag.register('x-foo-auto-attr-name', {
accessors:{
fooBar: {
attribute: {}
}
}
});
var foo = document.createElement('x-foo-auto-attr-name');
testbox.appendChild(foo);
foo.fooBar = 'bar';
expect(foo.getAttribute('foo-bar')).toEqual('bar');
});
it('setter fooBar should run the validate and pass along the modified value', function (){
var filteredValue;
xtag.register('x-foo-attr-validate', {
accessors:{
fooBar: {
attribute: {
validate: function(value){
return value | 0;
}
},
set: function(value){
filteredValue = value;
}
}
}
});
var foo = document.createElement('x-foo-attr-validate');
testbox.appendChild(foo);
foo.fooBar = 'bar';
expect(foo.getAttribute('foo-bar')).toEqual('0');
});
it('x-tag pseudos should allow css pseudos', function (){
var clickThis = null;
xtag.register('x-foo27', {
lifecycle: {
created: function (){
this.innerHTML = '<div><foo><bazz><button></button></bazz></foo></div>';
}
},
events: {
'click:delegate(div):delegate(bazz:first-child)': function (e, elem){
clickThis = this;
}
}
});
var foo = document.createElement('x-foo27');
testbox.appendChild(foo);
var button = xtag.query(foo,'button')[0];
xtag.fireEvent(button,'click');
expect(button).toEqual(clickThis.childNodes[0]);
});
it('the currentTarget property should always be populated with the attached element', function (){
var foo, count = 0;
xtag.register('x-foo30', {
events: {
bar: function (e, elem){
if (e.currentTarget == foo) count++;
},
click: function (e, elem){
if (e.currentTarget == foo) count++;
},
barf: function(e, elem){
if (e.currentTarget == foo) count++;
},
'barf:delegate(div)': function(e, elem){
if (e.currentTarget == foo) count++;
}
}
});
foo = document.createElement('x-foo30');
var d1 = document.createElement('div');
foo.appendChild(d1);
var foo2 = document.createElement('x-foo30');
testbox.appendChild(foo);
testbox.appendChild(foo2);
var event = document.createEvent('MouseEvent');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
foo.dispatchEvent(event);
xtag.fireEvent(foo, 'bar');
xtag.fireEvent(d1, 'barf');
waitsFor(function(){
return count == 4;
}, 'both clicks to bubble', 500);
runs(function (){
expect(count).toEqual(4);
});
});
it('custom event pseudo should fire', function (){
var pseudoFired = false,
clickThis = null;
xtag.pseudos.blah = {
action: function (pseudo, event){
pseudoFired = true;
event.foo = this;
return true;
}
};
xtag.register('x-foo28', {
lifecycle: {
created: function (){
this.innerHTML = '<div><foo><bazz></bazz></foo></div>';
}
},
events: {
'click:delegate(div):blah:delegate(bazz)': function (e, elem){
clickThis = this;
}
}
});
var foo = document.createElement('x-foo28');
testbox.appendChild(foo);
var innerDiv = xtag.query(foo,'bazz')[0];
xtag.fireEvent(innerDiv,'click');
expect(pseudoFired).toEqual(true);
expect(innerDiv).toEqual(clickThis);
});
it('extends should allow elements to use other elements base functionality', function(){
xtag.register("x-foo29", {
extends: 'div',
lifecycle: {
created: function() {
var nodes = xtag.createFragment('<div>hello</div>').cloneNode(true);
this.appendChild(nodes);
}
}
});
var foo = document.createElement('div', 'x-foo29');
expect(foo.innerHTML).toEqual('<div>hello</div>');
});
it('extends should instantiate elements in natural source', function(){
xtag.register("x-extendelement1",{
extends: 'div',
lifecycle: {
created: function() {
var nodes = xtag.createFragment('<div>hello</div>').cloneNode(true);
this.appendChild(nodes);
}
}
});
var foo = document.getElementById('extend_element');
expect(foo.innerHTML).toEqual('<div>hello</div>');
});
it('is="" should bootstrap element', function(){
var count = 0;
xtag.register("x-superdivo", {
extends: 'div',
methods: {
test: function(){
count++;
}
}
});
var foo = document.createElement('div', 'x-superdivo');
expect(foo.test).toBeDefined();
foo.test();
expect(count).toEqual(1);
});
it('should allow a custom prototype to be used', function(){
xtag.register("x-raw-proto", {
prototype: { fn: { value: function(){
return 'passed';
}}}
});
var foo = document.createElement('x-raw-proto');
expect(foo.fn).toBeDefined();
expect(foo.fn()).toEqual('passed');
expect(foo.click).toBeDefined();
});
it('should allow an inherited custom element prototype to be used', function(){
var count = 0;
xtag.mixins.compACreated = {
content: '<div>foo</div>',
lifecycle: {
created: function(){
count++;
}
}
};
var CompA = xtag.register('comp-a', {
mixins: ['compACreated'],
lifecycle: {
created: function(){
count++;
}
},
accessors: {
foo: {
set: function(){
count++;
},
get: function(){
return count;
}
}
},
methods: {
sayHi: function () {
return count + 1;
}
}
});
xtag.register('comp-b', {
prototype: CompA.prototype,
content: '<div>bar</div>',
lifecycle: {
created: function(){
count++;
}
}
});
var compb = document.createElement('comp-b');
compb.foo = 'bar';
expect(compb.children[0].textContent).toEqual('foo');
expect(compb.children[1].textContent).toEqual('bar');
expect(count).toEqual(4);
expect(compb.foo).toEqual(4);
expect(compb.sayHi()).toEqual(5);
});
it('should be able to extend existing elements', function(){
xtag.register("x-foo-extend", {
extends: 'input'
});
var foo = document.createElement('input', 'x-foo-extend');
testbox.appendChild(foo);
expect(foo.value).toBeDefined();
});
it('should pass the previous parentNode as the first parameter in the lifecycle removed callback', function(){
var insertParent, removedParent, removed;
xtag.register("x-foo31", {
lifecycle: {
inserted: function() {
insertParent = this.parentNode;
},
removed: function(parent) {
if(!removed) {
removedParent = parent;
removed = true;
}
}
}
});
var foo = document.createElement('x-foo31');
testbox.appendChild(foo);
setTimeout(function(){ testbox.removeChild(foo); }, 200);
waitsFor(function(){
return removed;
}, 'removed to be passed the last parentNode', 300);
runs(function (){
expect(insertParent == removedParent).toEqual(true);
});
});
it('should add Shadow DOM to the element', function (){
xtag.register('x-foo-shadow', {
shadow: '<div>bar</div>'
});
var foo = document.createElement('x-foo-shadow');
expect(Element.prototype.createShadowRoot ? foo.shadowRoot.firstElementChild.textContent == 'bar' : !foo.firstElementChild).toEqual(true);
});
it('should add default content to the element', function (){
xtag.register('x-foo-content', {
content: '<div>bar</div>'
});
var foo = document.createElement('x-foo-content');
expect(foo.firstElementChild.textContent).toEqual('bar');
});
});
describe('helper methods', function (){
describe('class', function (){
var body;
beforeEach(function (){
body = document.body;
});
afterEach(function (){
body.removeAttribute('class');
});
it('hasClass', function (){
expect(xtag.hasClass(body, 'foo')).toEqual(false);
body.setAttribute('class', 'foo');
expect(xtag.hasClass(body, 'foo')).toEqual(true);
});
it('addClass', function (){
expect(xtag.hasClass(body, 'foo')).toEqual(false);
xtag.addClass(body,'foo');
expect(xtag.hasClass(body, 'foo')).toEqual(true);
xtag.addClass(body,'bar');
expect(xtag.hasClass(body, 'bar')).toEqual(true);
expect('foo bar').toEqual(body.getAttribute('class'));
expect(2).toEqual(body.getAttribute('class').split(' ').length);
xtag.addClass(body,'biz red');
expect('foo bar biz red').toEqual(body.getAttribute('class'));
// prevent dups
xtag.addClass(body,'foo red');
expect('foo bar biz red').toEqual(body.getAttribute('class'));
});
it('removeClass', function (){
xtag.addClass(body,'foo');
xtag.addClass(body,'bar');
xtag.addClass(body,'baz');
expect('foo bar baz').toEqual(body.getAttribute('class'));
xtag.removeClass(body,'bar');
expect('foo baz').toEqual(body.getAttribute('class'));
xtag.addClass(body,'bar');
expect('foo baz bar').toEqual(body.getAttribute('class'));
xtag.removeClass(body,'foo');
expect('baz bar').toEqual(body.getAttribute('class'));
xtag.removeClass(body,'baz');
expect('bar').toEqual(body.getAttribute('class'));
xtag.removeClass(body,'random');
body.setAttribute('class',' foo bar baz red ');
xtag.removeClass(body,'bar');
expect('foo baz red').toEqual(body.getAttribute('class'));
});
it('toggleClass', function (){
xtag.toggleClass(body, 'foo');
expect('foo').toEqual(body.getAttribute('class'));
xtag.toggleClass(body, 'foo');
expect('').toEqual(body.getAttribute('class'));
xtag.addClass(body, 'baz');
xtag.toggleClass(body, 'baz');
expect('').toEqual(body.getAttribute('class'));
});
it('Random combination of Class tests', function (){
body.setAttribute('class', 'flex-stack');
xtag.addClass(body, 'small_desktop');
expect('flex-stack small_desktop').toEqual(body.getAttribute('class'));
body.setAttribute('class', 'flex-stack');
xtag.addClass(body, 'small_desktop');
xtag.removeClass(body, 'small_desktop');
expect('flex-stack').toEqual(body.getAttribute('class'));
body.setAttribute('class', 'small_desktop flex-stack');
xtag.removeClass(body, 'small_desktop');
expect('flex-stack').toEqual(body.getAttribute('class'));
body.setAttribute('class', 'small_desktop flex-stack');
xtag.removeClass(body, 'small_desktop');
xtag.removeClass(body, 'large_desktop');
expect('flex-stack').toEqual(body.getAttribute('class'));
});
});
describe('utils', function (){
it('typeOf', function (){
expect('object').toEqual(xtag.typeOf({}));
expect('array').toEqual(xtag.typeOf([]));
expect('string').toEqual(xtag.typeOf('d'));
expect('number').toEqual(xtag.typeOf(42));
});
it('toArray', function (){
expect([]).toEqual(xtag.toArray({}));
});
it('uid', function(){
expect(xtag.uid).toBeDefined();
expect('string').toEqual(typeof xtag.uid());
});
describe('wrap', function(){
it('should create new function that calls both functions', function(){
var f1Called = false,
f1 = function(){
f1Called = true;
};
var f2Called = false,
f2 = function(){
f2Called = true;
};
var f3 = xtag.wrap(f1, f2);
f3();
expect(f1Called).toEqual(true);
expect(f2Called).toEqual(true);
});
});
it('queryChildren', function(){
testbox.appendChild(document.createElement('a'));
testbox.appendChild(document.createElement('a'));
var div = document.createElement('div');
div.appendChild(document.createElement('a'));
testbox.appendChild(div);
expect(2).toEqual(xtag.queryChildren(testbox, 'a').length);
expect(div.parentElement).toBeDefined();
});
it('queryChildren no parent', function(){
var div = document.createElement('div');
div.appendChild(document.createElement('a'));
div.appendChild(document.createElement('a'));
expect(2).toEqual(xtag.queryChildren(div, 'a').length);
expect(div.parentElement).toBeNull();
});
});
});
});
|
// @license Copyright (C) 2015 Erik Ringsmuth - MIT license
(function(window, document) {
var utilities = {};
var importedURIs = {};
var isIE = 'ActiveXObject' in window;
var previousUrl = {};
// <app-router [init="auto|manual"] [mode="auto|hash|pushstate"] [trailingSlash="strict|ignore"] [shadow]></app-router>
var AppRouter = Object.create(HTMLElement.prototype);
AppRouter.util = utilities;
// <app-route path="/path" [import="/page/cust-el.html"] [element="cust-el"] [template]></app-route>
document.registerElement('app-route', {
prototype: Object.create(HTMLElement.prototype)
});
// Initial set up when attached
AppRouter.attachedCallback = function() {
// init="auto|manual"
if(this.getAttribute('init') !== 'manual') {
this.init();
}
};
// Initialize the router
AppRouter.init = function() {
var router = this;
if (router.isInitialized) {
return;
}
router.isInitialized = true;
// trailingSlash="strict|ignore"
if (!router.hasAttribute('trailingSlash')) {
router.setAttribute('trailingSlash', 'strict');
}
// mode="auto|hash|pushstate"
if (!router.hasAttribute('mode')) {
router.setAttribute('mode', 'auto');
}
// typecast="auto|string"
if (!router.hasAttribute('typecast')) {
router.setAttribute('typecast', 'auto');
}
// <app-router core-animated-pages transitions="hero-transition cross-fade">
if (router.hasAttribute('core-animated-pages')) {
// use shadow DOM to wrap the <app-route> elements in a <core-animated-pages> element
// <app-router>
// # shadowRoot
// <core-animated-pages>
// # content in the light DOM
// <app-route element="home-page">
// <home-page>
// </home-page>
// </app-route>
// </core-animated-pages>
// </app-router>
router.createShadowRoot();
router.coreAnimatedPages = document.createElement('core-animated-pages');
router.coreAnimatedPages.appendChild(document.createElement('content'));
// don't know why it needs to be static, but absolute doesn't display the page
router.coreAnimatedPages.style.position = 'static';
// toggle the selected page using selected="path" instead of selected="integer"
router.coreAnimatedPages.setAttribute('valueattr', 'path');
// pass the transitions attribute from <app-router core-animated-pages transitions="hero-transition cross-fade">
// to <core-animated-pages transitions="hero-transition cross-fade">
router.coreAnimatedPages.setAttribute('transitions', router.getAttribute('transitions'));
// set the shadow DOM's content
router.shadowRoot.appendChild(router.coreAnimatedPages);
// when a transition finishes, remove the previous route's content. there is a temporary overlap where both
// the new and old route's content is in the DOM to animate the transition.
router.coreAnimatedPages.addEventListener('core-animated-pages-transition-end', function() {
// with core-animated-pages, navigating to the same route twice quickly will set the new route to both the
// activeRoute and the previousRoute before the animation finishes. we don't want to delete the route content
// if it's actually the active route.
if (router.previousRoute && !router.previousRoute.hasAttribute('active')) {
removeRouteContent(router.previousRoute);
}
});
}
// listen for URL change events
router.stateChangeHandler = stateChange.bind(null, router);
window.addEventListener('popstate', router.stateChangeHandler, false);
if (isIE) {
// IE bug. A hashchange is supposed to trigger a popstate event, making popstate the only event you
// need to listen to. That's not the case in IE so we make another event listener for it.
window.addEventListener('hashchange', router.stateChangeHandler, false);
}
// load the web component for the current route
stateChange(router);
};
// clean up global event listeners
AppRouter.detachedCallback = function() {
window.removeEventListener('popstate', this.stateChangeHandler, false);
if (isIE) {
window.removeEventListener('hashchange', this.stateChangeHandler, false);
}
};
// go(path, options) Navigate to the path
//
// options = {
// replace: true
// }
AppRouter.go = function(path, options) {
if (this.getAttribute('mode') !== 'pushstate') {
// mode == auto or hash
path = '#' + path;
}
if (options && options.replace === true) {
window.history.replaceState(null, null, path);
} else {
window.history.pushState(null, null, path);
}
// dispatch a popstate event
try {
var popstateEvent = new PopStateEvent('popstate', {
bubbles: false,
cancelable: false,
state: {}
});
if ('dispatchEvent_' in window) {
// FireFox with polyfill
window.dispatchEvent_(popstateEvent);
} else {
// normal
window.dispatchEvent(popstateEvent);
}
} catch(error) {
// Internet Exploder
var fallbackEvent = document.createEvent('CustomEvent');
fallbackEvent.initCustomEvent('popstate', false, false, { state: {} });
window.dispatchEvent(fallbackEvent);
}
};
// fire(type, detail, node) - Fire a new CustomEvent(type, detail) on the node
//
// listen with document.querySelector('app-router').addEventListener(type, function(event) {
// event.detail, event.preventDefault()
// })
function fire(type, detail, node) {
// create a CustomEvent the old way for IE9/10 support
var event = document.createEvent('CustomEvent');
// initCustomEvent(type, bubbles, cancelable, detail)
event.initCustomEvent(type, false, true, detail);
// returns false when event.preventDefault() is called, true otherwise
return node.dispatchEvent(event);
}
// Find the first <app-route> that matches the current URL and change the active route
function stateChange(router) {
var url = utilities.parseUrl(window.location.href, router.getAttribute('mode'));
// don't load a new route if only the hash fragment changed
if (url.hash !== previousUrl.hash && url.path === previousUrl.path && url.search === previousUrl.search && url.isHashPath === previousUrl.isHashPath) {
scrollToHash(url.hash);
return;
}
previousUrl = url;
// fire a state-change event on the app-router and return early if the user called event.preventDefault()
var eventDetail = {
path: url.path
};
if (!fire('state-change', eventDetail, router)) {
return;
}
// find the first matching route
var route = router.firstElementChild;
while (route) {
if (route.tagName === 'APP-ROUTE' && utilities.testRoute(route.getAttribute('path'), url.path, router.getAttribute('trailingSlash'), route.hasAttribute('regex'))) {
activateRoute(router, route, url);
return;
}
route = route.nextSibling;
}
fire('not-found', eventDetail, router);
}
// Activate the route
function activateRoute(router, route, url) {
if (route.hasAttribute('redirect')) {
router.go(route.getAttribute('redirect'), {replace: true});
return;
}
var eventDetail = {
path: url.path,
route: route,
oldRoute: router.activeRoute
};
if (!fire('activate-route-start', eventDetail, router)) {
return;
}
if (!fire('activate-route-start', eventDetail, route)) {
return;
}
// keep track of the route currently being loaded
router.loadingRoute = route;
// import custom element or template
if (route.hasAttribute('import')) {
importAndActivate(router, route.getAttribute('import'), route, url, eventDetail);
}
// pre-loaded custom element
else if (route.hasAttribute('element')) {
activateCustomElement(router, route.getAttribute('element'), route, url, eventDetail);
}
// inline template
else if (route.firstElementChild && route.firstElementChild.tagName === 'TEMPLATE') {
// mark the route as an inline template so we know how to clean it up when we remove the route's content
route.isInlineTemplate = true;
activateTemplate(router, route.firstElementChild, route, url, eventDetail);
}
}
// Import and activate a custom element or template
function importAndActivate(router, importUri, route, url, eventDetail) {
var importLink;
function importLoadedCallback() {
importLink.loaded = true;
activateImport(router, importLink, importUri, route, url, eventDetail);
}
if (!importedURIs.hasOwnProperty(importUri)) {
// hasn't been imported yet
importLink = document.createElement('link');
importLink.setAttribute('rel', 'import');
importLink.setAttribute('href', importUri);
importLink.addEventListener('load', importLoadedCallback);
importLink.loaded = false;
document.head.appendChild(importLink);
importedURIs[importUri] = importLink;
} else {
// previously imported. this is an async operation and may not be complete yet.
importLink = importedURIs[importUri];
if (!importLink.loaded) {
importLink.addEventListener('load', importLoadedCallback);
} else {
activateImport(router, importLink, importUri, route, url, eventDetail);
}
}
}
// Activate the imported custom element or template
function activateImport(router, importLink, importUri, route, url, eventDetail) {
// allow referencing the route's import link in the activate-route-end callback
route.importLink = importLink;
// make sure the user didn't navigate to a different route while it loaded
if (route === router.loadingRoute) {
if (route.hasAttribute('template')) {
// template
activateTemplate(router, importLink.import.querySelector('template'), route, url, eventDetail);
} else {
// custom element
activateCustomElement(router, route.getAttribute('element') || importUri.split('/').slice(-1)[0].replace('.html', ''), route, url, eventDetail);
}
}
}
// Data bind the custom element then activate it
function activateCustomElement(router, elementName, route, url, eventDetail) {
var customElement = document.createElement(elementName);
var model = createModel(router, route, url, eventDetail);
for (var property in model) {
if (model.hasOwnProperty(property)) {
customElement[property] = model[property];
}
}
activateElement(router, customElement, url, eventDetail);
}
// Create an instance of the template
function activateTemplate(router, template, route, url, eventDetail) {
var templateInstance;
if ('createInstance' in template) {
// template.createInstance(model) is a Polymer method that binds a model to a template and also fixes
// https://github.com/erikringsmuth/app-router/issues/19
var model = createModel(router, route, url, eventDetail);
templateInstance = template.createInstance(model);
} else {
templateInstance = document.importNode(template.content, true);
}
activateElement(router, templateInstance, url, eventDetail);
}
// Create the route's model
function createModel(router, route, url, eventDetail) {
var model = utilities.routeArguments(route.getAttribute('path'), url.path, url.search, route.hasAttribute('regex'), router.getAttribute('typecast') === 'auto');
if (route.hasAttribute('bindRouter') || router.hasAttribute('bindRouter')) {
model.router = router;
}
eventDetail.model = model;
fire('before-data-binding', eventDetail, router);
fire('before-data-binding', eventDetail, eventDetail.route);
return eventDetail.model;
}
// Replace the active route's content with the new element
function activateElement(router, element, url, eventDetail) {
// when using core-animated-pages, the router doesn't remove the previousRoute's content right away. if you
// navigate between 3 routes quickly (ex: /a -> /b -> /c) you might set previousRoute to '/b' before '/a' is
// removed from the DOM. this verifies old content is removed before switching the reference to previousRoute.
removeRouteContent(router.previousRoute);
// update references to the activeRoute, previousRoute, and loadingRoute
router.previousRoute = router.activeRoute;
router.activeRoute = router.loadingRoute;
router.loadingRoute = null;
if (router.previousRoute) {
router.previousRoute.removeAttribute('active');
}
router.activeRoute.setAttribute('active', 'active');
// remove the old route's content before loading the new route. core-animated-pages temporarily needs the old and
// new route in the DOM at the same time to animate the transition, otherwise we can remove the old route's content
// right away. there is one exception for core-animated-pages where the route we're navigating to matches the same
// route (ex: path="/article/:id" navigating from /article/0 to /article/1). in this case we have to simply replace
// the route's content instead of animating a transition.
if (!router.hasAttribute('core-animated-pages') || eventDetail.route === eventDetail.oldRoute) {
removeRouteContent(router.previousRoute);
}
// add the new content
router.activeRoute.appendChild(element);
// animate the transition if core-animated-pages are being used
if (router.hasAttribute('core-animated-pages')) {
router.coreAnimatedPages.selected = router.activeRoute.getAttribute('path');
// the 'core-animated-pages-transition-end' event handler in init() will call removeRouteContent() on the previousRoute
}
// scroll to the URL hash if it's present
if (url.hash && !router.hasAttribute('core-animated-pages')) {
scrollToHash(url.hash);
}
fire('activate-route-end', eventDetail, router);
fire('activate-route-end', eventDetail, eventDetail.route);
}
// Remove the route's content
function removeRouteContent(route) {
if (route) {
var node = route.firstChild;
// don't remove an inline <template>
if (route.isInlineTemplate) {
node = route.querySelector('template').nextSibling;
}
while (node) {
var nodeToRemove = node;
node = node.nextSibling;
route.removeChild(nodeToRemove);
}
}
}
// scroll to the element with id="hash" or name="hash"
function scrollToHash(hash) {
if (!hash) return;
// wait for the browser's scrolling to finish before we scroll to the hash
// ex: http://example.com/#/page1#middle
// the browser will scroll to an element with id or name `/page1#middle` when the page finishes loading. if it doesn't exist
// it will scroll to the top of the page. let the browser finish the current event loop and scroll to the top of the page
// before we scroll to the element with id or name `middle`.
setTimeout(function() {
var hashElement = document.querySelector('html /deep/ ' + hash) || document.querySelector('html /deep/ [name="' + hash.substring(1) + '"]');
if (hashElement && hashElement.scrollIntoView) {
hashElement.scrollIntoView(true);
}
}, 0);
}
// parseUrl(location, mode) - Augment the native URL() constructor to get info about hash paths
//
// Example parseUrl('http://domain.com/other/path?queryParam3=false#/example/path?queryParam1=true&queryParam2=example%20string#middle', 'auto')
//
// returns {
// path: '/example/path',
// hash: '#middle'
// search: '?queryParam1=true&queryParam2=example%20string',
// isHashPath: true
// }
//
// Note: The location must be a fully qualified URL with a protocol like 'http(s)://'
utilities.parseUrl = function(location, mode) {
var url = {
isHashPath: mode === 'hash'
};
if (typeof URL === 'function') {
// browsers that support `new URL()`
var nativeUrl = new URL(location);
url.path = nativeUrl.pathname;
url.hash = nativeUrl.hash;
url.search = nativeUrl.search;
} else {
// IE
var anchor = document.createElement('a');
anchor.href = location;
url.path = anchor.pathname;
if (url.path.charAt(0) !== '/') {
url.path = '/' + url.path;
}
url.hash = anchor.hash;
url.search = anchor.search;
}
if (mode !== 'pushstate') {
// auto or hash
// check for a hash path
if (url.hash.substring(0, 2) === '#/') {
// hash path
url.isHashPath = true;
url.path = url.hash.substring(1);
} else if (url.hash.substring(0, 3) === '#!/') {
// hashbang path
url.isHashPath = true;
url.path = url.hash.substring(2);
} else if (url.isHashPath) {
// still use the hash if mode="hash"
if (url.hash.length === 0) {
url.path = '/';
} else {
url.path = url.hash.substring(1);
}
}
if (url.isHashPath) {
url.hash = '';
// hash paths might have an additional hash in the hash path for scrolling to a specific part of the page #/hash/path#elementId
var secondHashIndex = url.path.indexOf('#');
if (secondHashIndex !== -1) {
url.hash = url.path.substring(secondHashIndex);
url.path = url.path.substring(0, secondHashIndex);
}
// hash paths get the search from the hash if it exists
var searchIndex = url.path.indexOf('?');
if (searchIndex !== -1) {
url.search = url.path.substring(searchIndex);
url.path = url.path.substring(0, searchIndex);
}
}
}
return url;
};
// testRoute(routePath, urlPath, trailingSlashOption, isRegExp) - Test if the route's path matches the URL's path
//
// Example routePath: '/user/:userId/**'
// Example urlPath = '/user/123/bio'
utilities.testRoute = function(routePath, urlPath, trailingSlashOption, isRegExp) {
// try to fail or succeed as quickly as possible for the most common cases
// handle trailing slashes (options: strict (default), ignore)
if (trailingSlashOption === 'ignore') {
// remove trailing / from the route path and URL path
if(urlPath.slice(-1) === '/') {
urlPath = urlPath.slice(0, -1);
}
if(routePath.slice(-1) === '/' && !isRegExp) {
routePath = routePath.slice(0, -1);
}
}
// test regular expressions
if (isRegExp) {
return utilities.testRegExString(routePath, urlPath);
}
// if the urlPath is an exact match or '*' then the route is a match
if (routePath === urlPath || routePath === '*') {
return true;
}
// relative routes a/b/c are the same as routes that start with a globstar /**/a/b/c
if (routePath.charAt(0) !== '/') {
routePath = '/**/' + routePath;
}
// recursively test if the segments match (start at 1 because 0 is always an empty string)
return segmentsMatch(routePath.split('/'), 1, urlPath.split('/'), 1)
};
// segmentsMatch(routeSegments, routeIndex, urlSegments, urlIndex, pathVariables)
// recursively test the route segments against the url segments in place (without creating copies of the arrays
// for each recursive call)
//
// example routeSegments ['', 'user', ':userId', '**']
// example urlSegments ['', 'user', '123', 'bio']
function segmentsMatch(routeSegments, routeIndex, urlSegments, urlIndex, pathVariables) {
var routeSegment = routeSegments[routeIndex];
var urlSegment = urlSegments[urlIndex];
// if we're at the last route segment and it is a globstar, it will match the rest of the url
if (routeSegment === '**' && routeIndex === routeSegments.length - 1) {
return true;
}
// we hit the end of the route segments or the url segments
if (typeof routeSegment === 'undefined' || typeof urlSegment === 'undefined') {
// return true if we hit the end of both at the same time meaning everything else matched, else return false
return routeSegment === urlSegment;
}
// if the current segments match, recursively test the remaining segments
if (routeSegment === urlSegment || routeSegment === '*' || routeSegment.charAt(0) === ':') {
// store the path variable if we have a pathVariables object
if (routeSegment.charAt(0) === ':' && typeof pathVariables !== 'undefined') {
pathVariables[routeSegment.substring(1)] = urlSegments[urlIndex];
}
return segmentsMatch(routeSegments, routeIndex + 1, urlSegments, urlIndex + 1, pathVariables);
}
// globstars can match zero to many URL segments
if (routeSegment === '**') {
// test if the remaining route segments match any combination of the remaining url segments
for (var i = urlIndex; i < urlSegments.length; i++) {
if (segmentsMatch(routeSegments, routeIndex + 1, urlSegments, i, pathVariables)) {
return true;
}
}
}
// all tests failed, the route segments do not match the url segments
return false;
}
// routeArguments(routePath, urlPath, search, isRegExp) - Gets the path variables and query parameter values from the URL
utilities.routeArguments = function(routePath, urlPath, search, isRegExp, typecast) {
var args = {};
// regular expressions can't have path variables
if (!isRegExp) {
// relative routes a/b/c are the same as routes that start with a globstar /**/a/b/c
if (routePath.charAt(0) !== '/') {
routePath = '/**/' + routePath;
}
// get path variables
// urlPath '/customer/123'
// routePath '/customer/:id'
// parses id = '123'
segmentsMatch(routePath.split('/'), 1, urlPath.split('/'), 1, args);
}
var queryParameters = search.substring(1).split('&');
// split() on an empty string has a strange behavior of returning [''] instead of []
if (queryParameters.length === 1 && queryParameters[0] === '') {
queryParameters = [];
}
for (var i = 0; i < queryParameters.length; i++) {
var queryParameter = queryParameters[i];
var queryParameterParts = queryParameter.split('=');
args[queryParameterParts[0]] = queryParameterParts.splice(1, queryParameterParts.length - 1).join('=');
}
if (typecast) {
// parse the arguments into unescaped strings, numbers, or booleans
for (var arg in args) {
args[arg] = utilities.typecast(args[arg]);
}
}
return args;
};
// typecast(value) - Typecast the string value to an unescaped string, number, or boolean
utilities.typecast = function(value) {
// bool
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
// number
if (!isNaN(value) && value !== '' && value.charAt(0) !== '0') {
return +value;
}
// string
return decodeURIComponent(value);
};
// testRegExString(pattern, value) - Parse HTML attribute path="/^\/\w+\/\d+$/i" to a regular
// expression `new RegExp('^\/\w+\/\d+$', 'i')` and test against it.
//
// note that 'i' is the only valid option. global 'g', multiline 'm', and sticky 'y' won't be valid matchers for a path.
utilities.testRegExString = function(pattern, value) {
if (pattern.charAt(0) !== '/') {
// must start with a slash
return false;
}
pattern = pattern.slice(1);
var options = '';
if (pattern.slice(-1) === '/') {
pattern = pattern.slice(0, -1);
}
else if (pattern.slice(-2) === '/i') {
pattern = pattern.slice(0, -2);
options = 'i';
}
else {
// must end with a slash followed by zero or more options
return false;
}
return new RegExp(pattern, options).test(value);
};
document.registerElement('app-router', {
prototype: AppRouter
});
})(window, document);
|
var tweetServices = angular.module('tweetServices', ['ngResource']);
tweetServices.factory('Tweet', ['$resource',
function($resource){
return $resource('/api/tweet/:tweetId.json', {}, {
query: {method:'GET', params:{tweetId:'tweets'}, isArray:true}
});
}]); |
"use strict";
var Stream = require("stream").Stream,
utillib = require("util"),
net = require("net"),
tls = require("tls"),
oslib = require("os"),
xoauth2 = require("xoauth2"),
crypto = require("crypto"),
fs = require('fs');
// expose to the world
module.exports = function(port, host, options){
var connection = new SMTPClient(port, host, options);
if(typeof setImmediate == "function"){
setImmediate(connection.connect.bind(connection));
}else{
process.nextTick(connection.connect.bind(connection));
}
return connection;
};
/**
* <p>Generates a SMTP connection object</p>
*
* <p>Optional options object takes the following possible properties:</p>
* <ul>
* <li><b>secureConnection</b> - use SSL</li>
* <li><b>name</b> - the name of the client server</li>
* <li><b>auth</b> - authentication object <code>{user:"...", pass:"..."}</code>
* <li><b>ignoreTLS</b> - ignore server support for STARTTLS</li>
* <li><b>tls</b> - options for createCredentials</li>
* <li><b>debug</b> - output client and server messages to console</li>
* <li><b>logFile</b> - output client and server messages to file</li>
* <li><b>instanceId</b> - unique instance id for debugging</li>
* <li><b>localAddress</b> - outbound address to bind to (see: http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener)</li>
* <li><b>greetingTimeout</b> - Time to wait in ms until greeting message is received from the server (defaults to 10000)</li>
* <li><b>socketTimeout</b> - Time of inactivity until the connection is closed (defaults to 1 hour)</li>
* </ul>
*
* @constructor
* @namespace SMTP Client module
* @param {Number} [port=25] Port number to connect to
* @param {String} [host="localhost"] Hostname to connect to
* @param {Object} [options] Option properties
*/
function SMTPClient(port, host, options){
Stream.call(this);
this.writable = true;
this.readable = true;
this.stage = "init";
this.options = options || {};
this.port = port || (this.options.secureConnection ? 465 : 25);
this.host = host || "localhost";
this.options.secureConnection = !!this.options.secureConnection;
this.options.auth = this.options.auth || false;
this.options.maxConnections = this.options.maxConnections || 5;
this.options.enableDotEscaping = this.options.enableDotEscaping || false;
if(!this.options.name){
// defaul hostname is machine hostname or [IP]
var defaultHostname = (oslib.hostname && oslib.hostname()) || "";
if(defaultHostname.indexOf('.')<0){
defaultHostname = "[127.0.0.1]";
}
if(defaultHostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)){
defaultHostname = "["+defaultHostname+"]";
}
this.options.name = defaultHostname;
}
this._init();
}
utillib.inherits(SMTPClient, Stream);
/**
* <p>Initializes instance variables</p>
*/
SMTPClient.prototype._init = function(){
/**
* Defines if the current connection is secure or not. If not,
* STARTTLS can be used if available
* @private
*/
this._secureMode = false;
/**
* Ignore incoming data on TLS negotiation
* @private
*/
this._ignoreData = false;
/**
* Store incomplete messages coming from the server
* @private
*/
this._remainder = "";
/**
* If set to true, then this object is no longer active
* @private
*/
this.destroyed = false;
/**
* The socket connecting to the server
* @publick
*/
this.socket = false;
/**
* Lists supported auth mechanisms
* @private
*/
this._supportedAuth = [];
/**
* Currently in data transfer state
* @private
*/
this._dataMode = false;
/**
* Keep track if the client sends a leading \r\n in data mode
* @private
*/
this._lastDataBytes = new Buffer(2);
this._lastDataBytes[0] = 0x0D;
this._lastDataBytes[1] = 0x0A;
/**
* Function to run if a data chunk comes from the server
* @private
*/
this._currentAction = false;
/**
* Timeout variable for waiting the greeting
* @private
*/
this._greetingTimeout = false;
/**
* Timeout variable for waiting the connection to start
* @private
*/
this._connectionTimeout = false;
/**
* Timeout variable for NOOP when idling
* @private
*/
this._noopTimeout = false;
if(this.options.ignoreTLS || this.options.secureConnection){
this._secureMode = true;
}
/**
* XOAuth2 token generator if XOAUTH2 auth is used
* @private
*/
this._xoauth2 = false;
if(typeof this.options.auth.XOAuth2 == "object" && typeof this.options.auth.XOAuth2.getToken == "function"){
this._xoauth2 = this.options.auth.XOAuth2;
}else if(typeof this.options.auth.XOAuth2 == "object"){
if(!this.options.auth.XOAuth2.user && this.options.auth.user){
this.options.auth.XOAuth2.user = this.options.auth.user;
}
this._xoauth2 = xoauth2.createXOAuth2Generator(this.options.auth.XOAuth2);
}
};
/**
* <p>Creates a connection to a SMTP server and sets up connection
* listener</p>
*/
SMTPClient.prototype.connect = function(){
var opts = {};
if(this.options.secureConnection){
if (this.options.tls) {
Object.keys(this.options.tls).forEach((function(key) {
opts[key] = this.options.tls[key];
}).bind(this));
}
if(!("rejectUnauthorized" in opts)){
opts.rejectUnauthorized = !!this.options.rejectUnauthorized;
}
if(this.options.localAddress){
opts.localAddress = this.options.localAddress;
}
this.socket = tls.connect(this.port, this.host, opts, this._onConnect.bind(this));
}else{
opts = {
port: this.port,
host: this.host
};
if(this.options.localAddress){
opts.localAddress = this.options.localAddress;
}
this.socket = net.connect(opts, this._onConnect.bind(this));
}
if(this.options.connectionTimeout){
this._connectionTimeout = setTimeout((function(){
var error = new Error("Connection timeout");
error.code = "ETIMEDOUT";
error.errno = "ETIMEDOUT";
error.stage = this.stage;
this.emit("error", error);
this.close();
}).bind(this), this.options.connectionTimeout);
}
this.socket.on("drain", this._onDrain.bind(this));
this.socket.on("error", this._onError.bind(this));
};
/**
* <p>Upgrades the connection to TLS</p>
*
* @param {Function} callback Callback function to run when the connection
* has been secured
*/
SMTPClient.prototype._upgradeConnection = function(callback){
this._ignoreData = true;
this.socket.removeAllListeners("data");
this.socket.removeAllListeners("error");
var opts = {
socket: this.socket,
host: this.host,
rejectUnauthorized: !!this.options.rejectUnauthorized
};
Object.keys(this.options.tls || {}).forEach((function(key){
opts[key] = this.options.tls[key];
}).bind(this));
this.socket = tls.connect(opts, (function(){
this._ignoreData = false;
this._secureMode = true;
this.socket.on("data", this._onData.bind(this));
return callback(null, true);
}).bind(this));
this.socket.on("error", this._onError.bind(this));
};
/**
* <p>Connection listener that is run when the connection to
* the server is opened</p>
*
* @event
*/
SMTPClient.prototype._onConnect = function(){
this.stage = "connect";
clearTimeout(this._connectionTimeout);
if("setKeepAlive" in this.socket){
this.socket.setKeepAlive(true);
}
if("setNoDelay" in this.socket){
this.socket.setNoDelay(true);
}
this.socket.on("data", this._onData.bind(this));
this.socket.on("close", this._onClose.bind(this));
this.socket.on("end", this._onEnd.bind(this));
this.socket.setTimeout(this.options.socketTimeout || (3 * 3600 * 1000)); // 1 hours
this.socket.on("timeout", this._onTimeout.bind(this));
this._greetingTimeout = setTimeout((function(){
// if still waiting for greeting, give up
if(this.socket && !this._destroyed && this._currentAction == this._actionGreeting){
var error = new Error("Greeting never received");
error.code = "ETIMEDOUT";
error.errno = "ETIMEDOUT";
error.stage = this.stage;
this.emit("error", error);
this.close();
}
}).bind(this), this.options.greetingTimeout || 10000);
this._currentAction = this._actionGreeting;
};
/**
* <p>Destroys the client - removes listeners etc.</p>
*/
SMTPClient.prototype._destroy = function(){
if(this._destroyed)return;
this._destroyed = true;
this._ignoreData = true;
this.emit("end");
this.removeAllListeners();
};
/**
* <p>'data' listener for data coming from the server</p>
*
* @event
* @param {Buffer} chunk Data chunk coming from the server
*/
SMTPClient.prototype._onData = function(chunk){
var str;
clearTimeout(this._noopTimeout);
if(this._ignoreData || !chunk || !chunk.length){
return;
}
// Wait until end of line
if(chunk.readUInt8(chunk.length-1) != 0x0A){
this._remainder += chunk.toString();
return;
}else{
str = (this._remainder + chunk.toString()).trim();
this._remainder = "";
}
// if this is a multi line reply, wait until the ending
if(str.match(/(?:^|\n)\d{3}-.+$/)){
this._remainder = str + "\r\n";
return;
}
if(this.options.debug){
console.log("SERVER"+(this.options.instanceId?" "+
this.options.instanceId:"")+":\n└──"+str.replace(/\r?\n/g,"\n "));
}
if(this.options.logFile){
this.log("SERVER"+(this.options.instanceId?" "+
this.options.instanceId:"")+":\n└──"+str.replace(/\r?\n/g,"\n ")
);
}
if(typeof this._currentAction == "function"){
this._currentAction.call(this, str);
}
};
/**
* <p>'error' listener for the socket</p>
*
* @event
* @param {Error} err Error object
* @param {String} type Error name
*/
SMTPClient.prototype._onError = function(err, type, data){
if(type && type != "Error"){
err.name = type;
}
if(data){
err.data = data;
}
err.stage = this.stage;
this.emit("error", err);
this.close();
};
/**
* <p>'drain' listener for the socket</p>
*
* @event
*/
SMTPClient.prototype._onDrain = function(){
this.emit("drain");
};
/**
* <p>'close' listener for the socket</p>
*
* @event
*/
SMTPClient.prototype._onClose = function(){
if([this._actionGreeting, this._actionIdle, this.close].indexOf(this._currentAction) < 0){
return this._onError(new Error("Connection closed unexpectedly"));
}
this.stage = "close";
this._destroy();
};
/**
* <p>'end' listener for the socket</p>
*
* @event
*/
SMTPClient.prototype._onEnd = function(){
this.stage = "end";
this._destroy();
};
/**
* <p>'timeout' listener for the socket</p>
*
* @event
*/
SMTPClient.prototype._onTimeout = function(){
this.close();
};
/**
* <p>Passes data stream to socket if in data mode</p>
*
* @param {Buffer} chunk Chunk of data to be sent to the server
*/
SMTPClient.prototype.write = function(chunk){
// works only in data mode
if(!this._dataMode || this._destroyed){
// this line should never be reached but if it does, then
// say act like everything's normal.
return true;
}
if(typeof chunk == "string"){
chunk = new Buffer(chunk, "utf-8");
}
if (!this.options.enableDotEscaping) {
if (chunk.length>=2) {
this._lastDataBytes[0] = chunk[chunk.length-2];
this._lastDataBytes[1] = chunk[chunk.length-1];
} else if (chunk.length==1) {
this._lastDataBytes[0] = this._lastDataBytes[1];
this._lastDataBytes[1] = chunk[0];
}
} else {
chunk = this._escapeDot(chunk);
}
if(this.options.debug){
console.log("CLIENT (DATA)"+(this.options.instanceId?" "+
this.options.instanceId:"")+":\n└──"+chunk.toString().trim().replace(/\n/g,"\n "));
}
if(this.options.logFile){
this.log("CLIENT (DATA)"+(this.options.instanceId?" "+
this.options.instanceId:"")+":\n└──"+chunk.toString().trim().replace(/\n/g,"\n "));
}
// pass the chunk to the socket
return this.socket.write(chunk);
};
/**
* <p>Indicates that a data stream for the socket is ended. Works only
* in data mode.</p>
*
* @param {Buffer} [chunk] Chunk of data to be sent to the server
*/
SMTPClient.prototype.end = function(chunk){
// works only in data mode
if(!this._dataMode || this._destroyed){
// this line should never be reached but if it does, then
// say act like everything's normal.
return true;
}
if(chunk && chunk.length){
this.write(chunk);
}
// redirect output from the server to _actionStream
this._currentAction = this._actionStream;
// indicate that the stream has ended by sending a single dot on its own line
// if the client already closed the data with \r\n no need to do it again
if(this._lastDataBytes[0] == 0x0D && this._lastDataBytes[1] == 0x0A){
this.socket.write(new Buffer(".\r\n", "utf-8"));
}else if(this._lastDataBytes[1] == 0x0D){
this.socket.write(new Buffer("\n.\r\n"));
}else{
this.socket.write(new Buffer("\r\n.\r\n"));
}
this._lastDataBytes[0] = 0x0D;
this._lastDataBytes[1] = 0x0A;
// end data mode
this._dataMode = false;
};
/**
* <p>Send a command to the server, append \r\n</p>
*
* @param {String} str String to be sent to the server
*/
SMTPClient.prototype.sendCommand = function(str){
if(this._destroyed){
// Connection already closed, can't send any more data
return;
}
if(this.socket.destroyed){
return this.close();
}
if(this.options.debug){
console.log("CLIENT"+(this.options.instanceId?" "+
this.options.instanceId:"")+":\n└──"+(str || "").toString().trim().replace(/\n/g,"\n "));
}
if(this.options.logFile){
this.log("CLIENT"+(this.options.instanceId?" "+
this.options.instanceId:"")+":\n└──"+(str || "").toString().trim().replace(/\n/g,"\n "));
}
this.socket.write(new Buffer(str+"\r\n", "utf-8"));
};
/**
* <p>Sends QUIT</p>
*/
SMTPClient.prototype.quit = function(){
this.sendCommand("QUIT");
this._currentAction = this.close;
};
/**
* <p>Closes the connection to the server</p>
*/
SMTPClient.prototype.close = function(){
if(this.options.debug){
console.log("Closing connection to the server");
}
if(this.options.logFile){
this.log("Closing connection to the server");
}
var closeMethod = "end";
// Clear current job
this._currentAction = this._actionIdle;
clearTimeout(this._noopTimeout);
if (this.stage === "init") {
// Clear connection timeout timer if other than timeout error occurred
clearTimeout(this._connectionTimeout);
// Close the socket immediately when connection timed out
closeMethod = "destroy";
}
if(this.socket && this.socket.socket && this.socket.socket[closeMethod] && !this.socket.socket.destroyed){
this.socket.socket[closeMethod]();
}
if(this.socket && this.socket[closeMethod] && !this.socket.destroyed){
this.socket[closeMethod]();
}
this._destroy();
};
/**
* <p>Initiates a new message by submitting envelope data, starting with
* <code>MAIL FROM:</code> command</p>
*
* @param {Object} envelope Envelope object in the form of
* <code>{from:"...", to:["..."]}</code>
* or
* <code>{from:{address:"...",name:"..."}, to:[address:"...",name:"..."]}</code>
*/
SMTPClient.prototype.useEnvelope = function(envelope){
this._envelope = envelope || {};
this._envelope.from = this._envelope.from && this._envelope.from.address || this._envelope.from || ("anonymous@"+this.options.name);
this._envelope.to = [].concat(this._envelope.to || []).map(function(to){
return to && to.address || to;
});
// clone the recipients array for latter manipulation
this._envelope.rcptQueue = JSON.parse(JSON.stringify(this._envelope.to || []));
this._envelope.rcptFailed = [];
this._currentAction = this._actionMAIL;
this.sendCommand("MAIL FROM:<"+(this._envelope.from)+">");
};
/**
* <p>If needed starts the authentication, if not emits 'idle' to
* indicate that this client is ready to take in an outgoing mail</p>
*/
SMTPClient.prototype._authenticateUser = function(){
this.stage = "auth";
if(!this.options.auth){
// no need to authenticate, at least no data given
this._enterIdle();
return;
}
var auth;
if(this.options.auth.XOAuthToken && this._supportedAuth.indexOf("XOAUTH")>=0){
auth = "XOAUTH";
}else if(this._xoauth2 && this._supportedAuth.indexOf("XOAUTH2")>=0){
auth = "XOAUTH2";
}else if(this.options.authMethod) {
auth = this.options.authMethod.toUpperCase().trim();
}else{
// use first supported
auth = (this._supportedAuth[0] || "PLAIN").toUpperCase().trim();
}
switch(auth){
case "XOAUTH":
this._currentAction = this._actionAUTHComplete;
if(typeof this.options.auth.XOAuthToken == "object" &&
typeof this.options.auth.XOAuthToken.generate == "function"){
this.options.auth.XOAuthToken.generate((function(err, XOAuthToken){
if(this._destroyed){
// Nothing to do here anymore, connection already closed
return;
}
if(err){
return this._onError(err, "XOAuthTokenError");
}
this.sendCommand("AUTH XOAUTH " + XOAuthToken);
}).bind(this));
}else{
this.sendCommand("AUTH XOAUTH " + this.options.auth.XOAuthToken.toString());
}
return;
case "XOAUTH2":
this._currentAction = this._actionAUTHComplete;
this._xoauth2.getToken((function(err, token){
if(this._destroyed){
// Nothing to do here anymore, connection already closed
return;
}
if(err){
this._onError(err, "XOAUTH2Error");
return;
}
this.sendCommand("AUTH XOAUTH2 " + token);
}).bind(this));
return;
case "LOGIN":
this._currentAction = this._actionAUTH_LOGIN_USER;
this.sendCommand("AUTH LOGIN");
return;
case "PLAIN":
this._currentAction = this._actionAUTHComplete;
this.sendCommand("AUTH PLAIN "+new Buffer(
//this.options.auth.user+"\u0000"+
"\u0000"+ // skip authorization identity as it causes problems with some servers
this.options.auth.user+"\u0000"+
this.options.auth.pass,"utf-8").toString("base64"));
return;
case "CRAM-MD5":
this._currentAction = this._actionAUTH_CRAM_MD5;
this.sendCommand("AUTH CRAM-MD5");
return;
}
this._onError(new Error("Unknown authentication method - "+auth), "UnknowAuthError");
};
/** ACTIONS **/
/**
* <p>Will be run after the connection is created and the server sends
* a greeting. If the incoming message starts with 220 initiate
* SMTP session by sending EHLO command</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionGreeting = function(str){
this.stage = "greeting";
clearTimeout(this._greetingTimeout);
if(str.substr(0,3) != "220"){
this._onError(new Error("Invalid greeting from server - "+str), false, str);
return;
}
this._currentAction = this._actionEHLO;
this.sendCommand("EHLO "+this.options.name);
};
/**
* <p>Handles server response for EHLO command. If it yielded in
* error, try HELO instead, otherwise initiate TLS negotiation
* if STARTTLS is supported by the server or move into the
* authentication phase.</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionEHLO = function(str){
this.stage = "ehlo";
if(str.substr(0, 3) == "421") {
this._onError(new Error("Server terminates connection - "+str), false, str);
return;
}
if(str.charAt(0) != "2"){
// Try HELO instead
this._currentAction = this._actionHELO;
this.sendCommand("HELO "+this.options.name);
return;
}
// Detect if the server supports STARTTLS
if(!this._secureMode && str.match(/[ \-]STARTTLS\r?$/mi)){
this.sendCommand("STARTTLS");
this._currentAction = this._actionSTARTTLS;
return;
}
// Detect if the server supports PLAIN auth
if(str.match(/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)PLAIN/i)){
this._supportedAuth.push("PLAIN");
}
// Detect if the server supports LOGIN auth
if(str.match(/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)LOGIN/i)){
this._supportedAuth.push("LOGIN");
}
// Detect if the server supports CRAM-MD5 auth
if(str.match(/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)CRAM-MD5/i)){
this._supportedAuth.push("CRAM-MD5");
}
// Detect if the server supports XOAUTH auth
if(str.match(/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH/i)){
this._supportedAuth.push("XOAUTH");
}
// Detect if the server supports XOAUTH2 auth
if(str.match(/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH2/i)){
this._supportedAuth.push("XOAUTH2");
}
this._authenticateUser.call(this);
};
/**
* <p>Handles server response for HELO command. If it yielded in
* error, emit 'error', otherwise move into the authentication phase.</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionHELO = function(str){
this.stage = "helo";
if(str.charAt(0) != "2"){
this._onError(new Error("Invalid response for EHLO/HELO - "+str), false, str);
return;
}
this._authenticateUser.call(this);
};
/**
* <p>Handles server response for STARTTLS command. If there's an error
* try HELO instead, otherwise initiate TLS upgrade. If the upgrade
* succeedes restart the EHLO</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionSTARTTLS = function(str){
this.stage = "starttls";
if(str.charAt(0) != "2"){
// Try HELO instead
this._currentAction = this._actionHELO;
this.sendCommand("HELO "+this.options.name);
return;
}
this._upgradeConnection((function(err, secured){
if(err){
this._onError(new Error("Error initiating TLS - "+(err.message || err)), "TLSError");
return;
}
if(this.options.debug){
console.log("Connection secured");
}
if(this.options.logFile){
this.log("Connection secured");
}
if(secured){
// restart session
this._currentAction = this._actionEHLO;
this.sendCommand("EHLO "+this.options.name);
}else{
this._authenticateUser.call(this);
}
}).bind(this));
};
/**
* <p>Handle the response for AUTH LOGIN command. We are expecting
* '334 VXNlcm5hbWU6' (base64 for 'Username:'). Data to be sent as
* response needs to be base64 encoded username.</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionAUTH_LOGIN_USER = function(str){
if(str != "334 VXNlcm5hbWU6"){
this._onError(new Error("Invalid login sequence while waiting for '334 VXNlcm5hbWU6' - "+str), false, str);
return;
}
this._currentAction = this._actionAUTH_LOGIN_PASS;
this.sendCommand(new Buffer(
this.options.auth.user + "", "utf-8").toString("base64"));
};
/**
* <p>Handle the response for AUTH CRAM-MD5 command. We are expecting
* '334 <challenge string>'. Data to be sent as response needs to be
* base64 decoded challenge string, MD5 hashed using the password as
* a HMAC key, prefixed by the username and a space, and finally all
* base64 encoded again.</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionAUTH_CRAM_MD5 = function(str) {
var challengeMatch = str.match(/^334\s+(.+)$/),
challengeString = "";
if (!challengeMatch) {
this._onError(new Error("Invalid login sequence while waiting for server challenge string - "+str), false, str);
return;
} else {
challengeString = challengeMatch[1];
}
// Decode from base64
var base64decoded = new Buffer(challengeString, 'base64').toString('ascii'),
hmac_md5 = crypto.createHmac('md5', this.options.auth.pass);
hmac_md5.update(base64decoded);
var hex_hmac = hmac_md5.digest('hex'),
prepended = this.options.auth.user + " " + hex_hmac;
this._currentAction = this._actionAUTH_CRAM_MD5_PASS;
this.sendCommand(new Buffer(prepended).toString("base64"));
};
/**
* <p>Handles the response to CRAM-MD5 authentication, if there's no error,
* the user can be considered logged in. Emit 'idle' and start
* waiting for a message to send</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionAUTH_CRAM_MD5_PASS = function(str) {
if (!str.match(/^235\s+/)) {
this._onError(new Error("Invalid login sequence while waiting for '235 go ahead' - "+str), false, str);
return;
}
this._enterIdle();
};
/**
* <p>Handle the response for AUTH LOGIN command. We are expecting
* '334 UGFzc3dvcmQ6' (base64 for 'Password:'). Data to be sent as
* response needs to be base64 encoded password.</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionAUTH_LOGIN_PASS = function(str){
if(str != "334 UGFzc3dvcmQ6"){
this._onError(new Error("Invalid login sequence while waiting for '334 UGFzc3dvcmQ6' - "+str), false, str);
return;
}
this._currentAction = this._actionAUTHComplete;
this.sendCommand(new Buffer(this.options.auth.pass + "", "utf-8").toString("base64"));
};
/**
* <p>Handles the response for authentication, if there's no error,
* the user can be considered logged in. Emit 'idle' and start
* waiting for a message to send</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionAUTHComplete = function(str){
var response;
if(this._xoauth2 && str.substr(0, 3) == "334"){
try{
response = str.split(" ");
response.shift();
response = JSON.parse(new Buffer(response.join(" "), "base64").toString("utf-8"));
if((!this._xoauth2.reconnectCount || this._xoauth2.reconnectCount < 200) && ['400','401'].indexOf(response.status)>=0){
this._xoauth2.reconnectCount = (this._xoauth2.reconnectCount || 0) + 1;
this._currentAction = this._actionXOAUTHRetry;
}else{
this._xoauth2.reconnectCount = 0;
this._currentAction = this._actionAUTHComplete;
}
this.sendCommand(new Buffer(0));
return;
}catch(E){}
}
this._xoauth2.reconnectCount = 0;
if(str.charAt(0) != "2"){
this._onError(new Error("Invalid login - "+str), "AuthError", str);
return;
}
this._enterIdle();
};
/**
* If XOAUTH2 authentication failed, try again by generating
* new access token
*/
SMTPClient.prototype._actionXOAUTHRetry = function(){
// ensure that something is listening unexpected responses
this._currentAction = this._actionIdle;
this._xoauth2.generateToken((function(err, token){
if(this._destroyed){
// Nothing to do here anymore, connection already closed
return;
}
if(err){
this._onError(err, "XOAUTH2Error");
return;
}
this._currentAction = this._actionAUTHComplete;
this.sendCommand("AUTH XOAUTH2 " + token);
}).bind(this));
};
/**
* <p>This function is not expected to run. If it does then there's probably
* an error (timeout etc.)</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionIdle = function(str){
this.stage = "idle";
if(Number(str.charAt(0)) > 3){
this._onError(new Error(str), false, str);
return;
}
// this line should never get called
};
/**
* <p>Handle response for a <code>MAIL FROM:</code> command</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionMAIL = function(str){
this.stage = "mail";
if(Number(str.charAt(0)) != "2"){
this._onError(new Error("Mail from command failed - " + str), "SenderError", str);
return;
}
if(!this._envelope.rcptQueue.length){
this._onError(new Error("Can't send mail - no recipients defined"), "RecipientError", str);
}else{
this._envelope.curRecipient = this._envelope.rcptQueue.shift();
this._currentAction = this._actionRCPT;
this.sendCommand("RCPT TO:<"+this._envelope.curRecipient+">"+this._getDSN());
}
};
/**
* Emits "idle" and starts a NOOP timer
*/
SMTPClient.prototype._enterIdle = function(){
clearTimeout(this._noopTimeout);
this._noopTimeout = setTimeout(function(){
// Return to idle mode once NOOP has been accepted
this._currentAction = this._enterIdle;
this.sendCommand("NOOP");
}.bind(this), 60 * 1000);
this._currentAction = this._actionIdle;
this.emit("idle"); // ready to take orders
};
/**
* <p>SetsUp DSN</p>
*/
SMTPClient.prototype._getDSN = function(){
var ret = "", n = [], dsn;
if (this.currentMessage && this.currentMessage.options && "dsn" in this.currentMessage.options){
dsn = this.currentMessage.options.dsn;
if(dsn.success){
n.push("SUCCESS");
}
if(dsn.failure){
n.push("FAILURE");
}
if(dsn.delay){
n.push("DELAY");
}
if(n.length > 0){
ret = " NOTIFY=" + n.join(",") + " ORCPT=rfc822;" + this.currentMessage._message.from;
}
}
return ret;
};
/**
* <p>Handle response for a <code>RCPT TO:</code> command</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionRCPT = function(str){
this.stage = "rcpt";
if(Number(str.charAt(0)) != "2"){
// this is a soft error
this._envelope.rcptFailed.push(this._envelope.curRecipient);
}
if(!this._envelope.rcptQueue.length){
if(this._envelope.rcptFailed.length < this._envelope.to.length){
if(this._envelope.rcptFailed.length){
this.emit("rcptFailed", this._envelope.rcptFailed);
}
this._currentAction = this._actionDATA;
this.sendCommand("DATA");
}else{
this._onError(new Error("Can't send mail - all recipients were rejected"), "RecipientError", str);
return;
}
}else{
this._envelope.curRecipient = this._envelope.rcptQueue.shift();
this._currentAction = this._actionRCPT;
this.sendCommand("RCPT TO:<"+this._envelope.curRecipient+">");
}
};
/**
* <p>Handle response for a <code>DATA</code> command</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionDATA = function(str){
this.stage = "data";
// response should be 354 but according to this issue https://github.com/eleith/emailjs/issues/24
// some servers might use 250 instead, so lets check for 2 or 3 as the first digit
if([2,3].indexOf(Number(str.charAt(0)))<0){
this._onError(new Error("Data command failed - " + str), false, str);
return;
}
// Emit that connection is set up for streaming
this._dataMode = true;
this._currentAction = this._actionIdle;
this.emit("message");
};
/**
* <p>Handle response for a <code>DATA</code> stream</p>
*
* @param {String} str Message from the server
*/
SMTPClient.prototype._actionStream = function(str){
if(Number(str.charAt(0)) != "2"){
// Message failed
this.emit("ready", false, str);
}else{
// Message sent succesfully
this.emit("ready", true, str);
}
// Waiting for new connections
this._currentAction = this._actionIdle;
if(typeof setImmediate == "function"){
setImmediate(this._enterIdle.bind(this));
}else{
process.nextTick(this._enterIdle.bind(this));
}
};
/**
* <p>Log debugs to given file</p>
*
* @param {String} str Log message
*/
SMTPClient.prototype.log = function(str) {
fs.appendFile(this.options.logFile, str + "\n", function(err) {
if (err) {
console.log('Log write failed. Data to log: ' + str);
}
});
};
/**
* <p>Inserts an extra dot at the begining of a line if it starts with a dot
* See RFC 2821 Section 4.5.2</p>
*
* @param {Buffer} chunk The chunk that will be send.
*/
SMTPClient.prototype._escapeDot = function(chunk) {
var pos, OutBuff, i;
OutBuff = new Buffer(chunk.length * 2);
pos = 0;
for (i=0; i<chunk.length; i++) {
if (this._lastDataBytes[0] == 0x0D && this._lastDataBytes[1] == 0x0A && chunk[i] == 0x2E) {
OutBuff[pos] = 0x2E;
pos +=1;
}
OutBuff[pos] = chunk[i];
pos += 1;
this._lastDataBytes[0] = this._lastDataBytes[1];
this._lastDataBytes[1] = chunk[i];
}
return OutBuff.slice(0,pos);
};
|
// Shared directive between room.ejs and screen.ejs
// This handles OpenTok screensharing and sets `$scope.sharingMyScreen` to true
// when you are ready to share your screen. Then you need to include an ot-publisher
// somewhere else in your application using the screenPublisherProps and the id 'screenPublisher'
angular.module('opentok-meet').directive('screenShareDialogs', () => ({
restrict: 'E',
template: `<div id="screenShareFailed" class="statusMessage" ng-if="screenShareFailed">
Screen Share Failed {{screenShareFailed}}</div>
<div id="installScreenshareExtension" class="statusMessage" ng-if="promptToInstall">
You need a Chrome extension to share your screen.
<a href="{{ 'https://chrome.google.com/webstore/detail/' + chromeExtensionId }}" target="_blank">Install Screensharing Extension</a>.
Once you have installed refresh your browser and click the share screen button again.
</div>
<div id="screenShareUnsupported" class="statusMessage" ng-if="!screenShareSupported">
Screen Sharing currently requires Google Chrome or Firefox on Desktop.
</div>`,
controller: ['$scope', 'chromeExtensionId', function controller($scope, chromeExtensionId) {
$scope.promptToInstall = false;
$scope.selectingScreenSource = false;
$scope.sharingMyScreen = false;
$scope.screenShareSupported = true;
$scope.screenShareFailed = null;
$scope.chromeExtensionId = chromeExtensionId;
$scope.screenPublisherProps = {
name: 'screen',
style: {
nameDisplayMode: 'off',
},
publishAudio: false,
videoSource: 'screen',
};
OT.registerScreenSharingExtension('chrome', chromeExtensionId);
OT.checkScreenSharingCapability((response) => {
const supported = response.supported && response.extensionRegistered !== false;
if (supported !== $scope.screenShareSupported) {
$scope.screenShareSupported = supported;
$scope.$apply();
}
});
$scope.$on('otPublisherError', (event, error, publisher) => {
if (publisher.id === 'screenPublisher') {
$scope.$apply(() => {
$scope.screenShareFailed = error.message;
$scope.toggleShareScreen();
});
}
});
$scope.$on('otStreamDestroyed', (event) => {
if (event.targetScope.publisher.id === 'screenPublisher') {
$scope.$apply(() => {
$scope.sharingMyScreen = false;
});
}
});
$scope.toggleShareScreen = () => {
if (!$scope.sharingMyScreen && !$scope.selectingScreenSource) {
$scope.selectingScreenSource = true;
$scope.screenShareFailed = null;
OT.checkScreenSharingCapability((response) => {
if (!response.supported || response.extensionRegistered === false) {
$scope.screenShareSupported = false;
$scope.selectingScreenSource = false;
} else if (response.extensionInstalled === false && response.extensionRegistered) {
$scope.promptToInstall = true;
$scope.selectingScreenSource = false;
} else {
$scope.sharingMyScreen = true;
$scope.selectingScreenSource = false;
}
$scope.$apply();
});
} else if ($scope.sharingMyScreen) {
$scope.sharingMyScreen = false;
}
};
}],
}));
|
/**
* Created by tsotne on 5/29/15.
*/
Ext.define('AA.view.coding.Tape', {
extend: 'Ext.panel.Panel',
layout: 'hbox',
border: false,
bodyPadding: 5,
style: 'border-radius: 5px',
constructor: function (cfg) {
cfg = cfg || {};
var me = this;
Tape = me;
var _ = {xtype: 'splitter', width: 2};
var tape = Ext.create('Ext.form.Panel', {
flex: 1,
layout: 'hbox',
border: false,
//style: 'border-top : 0px; border-right : 1px solid black; border-bottom: 0px; border-left : 1px solid black;',
margin: '0 5 0 5'
});
me.l = Ext.create('Ext.Button', {
text: '❰',
handler: function () {
me.move(-1);
}
});
me.ll = Ext.create('Ext.Button', {
text: '❰x10',
handler: function () {
me.move(-10);
}
});
me.r = Ext.create('Ext.Button', {
text: '❱',
handler: function () {
me.move(1);
}
});
me.rr = Ext.create('Ext.Button', {
text: '10x❱',
handler: function () {
me.move(10);
}
});
me.items = [me.ll, _, me.l, _, tape, _, me.r, _, me.rr];
me.tape = tape;
me.callParent(arguments);
function addItem(id, v) {
var item = Ext.create('Ext.form.field.Text', {
cls: 'tape-item',
fieldStyle: 'background-color: rgb(232, 232, 232);',
value: v,
name: "id" + id,
id: id,
emptyText: '_',
maxLength: 1,
enforceMaxLength: true,
enableKeyEvents: true,
listeners: {
keydown: function (t, e) {
if (e.keyCode == 37) moveCursor(-1);
if (e.keyCode == 39) moveCursor(1)
},
focus: function () {
tape.focusedPos = id;
},
blur: function () {
tape.focusedPos = null;
}
}
});
tape.add(item);
}
function moveCursor(v) {
var dest = tape.focusedPos + v;
if (dest === undefined || dest < 0 || dest >= tape.totalItems) return;
tape.items.getRange()[dest].focus();
}
me.on('afterrender', function () {
addItem(0);
me.values = [];
setTimeout(function () {
tape.totalItems = Math.round(($(tape.el.dom).width() ) / $(tape.items.items[0].el.dom).width());
for (var i = 1; i < tape.totalItems; i++) {
addItem(i);
}
//tape.tapeDiv = $(tape.el.dom).find("[data-ref=targetEl]");
tape.currentPos = Math.round(tape.totalItems / 2) - 1;
me.totalPos = 0;
tape.current = tape.items.items[tape.currentPos];
tape.current.addCls("tape-center-item");
tape.halfSize = tape.currentPos;
}, 0);
setTimeout(function () {
slideValues(0);
}, 100);
});
me.move = function (v) {
if (tape.currentPos + v >= tape.totalItems - 1 || tape.currentPos + v <= 0)
slideValues(v);
tape.items.items[tape.currentPos].removeCls("tape-center-item");
tape.currentPos += v;
tape.current = tape.items.items[tape.currentPos];
tape.current.addCls("tape-center-item");
}
function slideValues(v) {
var values = tape.getForm().getValues();
tape.getForm().reset();
for (var i = me.totalPos, j = 0; j < tape.totalItems; i++, j++) {
me.values[i] = values["id" + j]
}
me.totalPos += v;
values = {};
for (var i = me.totalPos, j = 0; j < tape.totalItems; i++, j++) {
values["id" + j] = me.values[i];
}
tape.getForm().setValues(values);
me.move(-v);
}
me.getValues = function () {
slideValues(0);
return me.values;
}
}
});
/*
tape.items.items[tape.currentPos].removeCls("tape-center-item");
tape.currentPos += v;
tape.current = tape.items.items[tape.currentPos];
tape.current.addCls("tape-center-item");
var itemWidth = $(tape.items.items[0].el.dom).width();
$(tape.tapeDiv).animate({left: '+=' + itemWidth * (-v) + 'px'}, 10);
*/ |
export const addZero = (n) => n < 10
? '0' + n
: n;
/**
*
*
* @param {Date} d
* @returns
*/
function Chinese(d) {
if (Object.prototype.toString.call(d) !== '[object Date]') {
let origin = d;
d = new Date(d);
let temp = d.getDate();
if (temp !== temp) {
if (d === undefined) {
return '某个时刻'
} else if (typeof origin === 'string') {
return origin; //原样返回时间,可能第三方已经处理了时间了
}
return '(时间参数不合法)'
}
};
let fullYear = d.getFullYear(),
month = d.getMonth(),
date = d.getDate(),
hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds(),
now = new Date(),
_fullYear = now.getFullYear(),
_month = now.getMonth(),
_date = now.getDate(),
_hours = now.getHours(),
_minutes = now.getMinutes(),
_seconds = now.getSeconds();
//刚刚 ,15秒前,3分钟前 ,3小时前 ,昨天 3:22, 前天 14:30,3天前,
if (_fullYear === fullYear) {
if (_month === month) {
if (_date === date) {
if (_hours === hours) {
if (_minutes === minutes) {
if (_seconds === seconds) {
return '刚刚'
} else {
return `${_seconds - seconds}秒前`
}
} else {
return `${_minutes - minutes}分钟前`
}
} else {
return `今天 ${addZero(hours)}:${addZero(minutes)}`
}
} else if ((_date - date) == 1) {
return `昨天 ${addZero(hours)}:${addZero(minutes)}`
} else if ((_date - date) == 2) {
return `前天 ${addZero(hours)}:${addZero(minutes)}`
} else {
return `${month + 1}月${date}日 ${addZero(hours)}:${addZero(minutes)}`
}
} else {
return `${month + 1}月${date}日 ${addZero(hours)}:${addZero(minutes)}`
}
} else {
return `${fullYear}年${month + 1}月${date}日 ${addZero(hours)}:${addZero(minutes)}`
}
}
export default Chinese; |
/*
* Copyright (c) 2012-2016 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
export let foo = () => "standard-index";
|
const DefaultSeleniumDriver = require('./');
const Concurrency = require('../../runner/concurrency/');
const SeleniumServerBuilder = require('./service-builders/selenium.js');
module.exports = class SeleniumServer extends DefaultSeleniumDriver {
/**
* Used when running in parallel with start_process=true
*/
static startServer(settings) {
const Options = require('./options.js');
const opts = new Options({settings});
opts.updateWebdriverPath();
const seleniumService = new SeleniumServerBuilder(settings);
const moduleKey = settings.webdriver.log_file_name || '';
seleniumService.setOutputFile(moduleKey);
return seleniumService;
}
get defaultBrowser() {
return 'firefox';
}
get ServiceBuilder() {
return SeleniumServerBuilder;
}
get defaultServerUrl() {
return 'http://127.0.0.1:4444';
}
get defaultPathPrefix() {
return '/wd/hub';
}
constructor(nightwatchInstance, browserName) {
if (nightwatchInstance.settings.selenium && nightwatchInstance.settings.selenium['[_started]']) {
nightwatchInstance.settings.selenium.start_process = false;
nightwatchInstance.settings.webdriver.start_process = false;
}
super(nightwatchInstance, {isSelenium: true, browserName});
}
async closeDriver() {}
async sessionFinished(reason) {
this.emit('session:finished', reason);
// TODO: refactor this, selenium server management has moved to runner/cli
if (this.driverService) {
const {service} = this.driverService;
if (service && service.kill) {
// Give the selenium server some time to close down its browser drivers
return new Promise((resolve, reject) => {
setTimeout(() => {
service.kill()
.catch(err => reject(err))
.then(() => this.driverService.stop())
.then(() => resolve());
}, 100);
});
}
}
}
setBuilderOptions({builder, options}) {
const serverUrl = this.getServerUrl();
builder
.usingServer(serverUrl)
.withCapabilities(this.initialCapabilities);
return super.setBuilderOptions({builder, options});
}
};
|
import fs from 'fs'
import path from 'path'
import { expect } from 'chai'
import proxyquire from 'proxyquire'
import td from 'testdouble'
describe('[Integration] Itaú conta corrente', () => {
var downloadMock
var displayErrorMessageMock
var contentScript
var browserHelper
beforeEach(() => {
let htmlPath = path.join(__dirname, 'fixtures', 'itau.contacorrente.html')
let html = fs.readFileSync(htmlPath, 'utf8')
document.body.innerHTML = html
downloadMock = td.object(['createTextFileForDownload'])
browserHelper = td.object(['getUrl'])
displayErrorMessageMock = td.function('Display error')
// subject:
contentScript = proxyquire('../../src/scripts/contentscript', {
'./utils/ext': {
runtime: {
onMessage: { addListener: td.function() },
sendMessage: displayErrorMessageMock
}
},
'./utils/download': downloadMock,
'./utils/browser-helper': browserHelper
})
})
afterEach(() => {
td.reset()
})
it('should read content and generate CSV', () => {
// given:
td.replace(window, 'getSelection', () => {
return {
anchorNode: {parentElement: document.querySelector('#selectionStart0')},
focusNode: {parentElement: document.querySelector('#selectionEnd0')}
}
})
td.when(browserHelper.getUrl()).thenReturn('https://itaubankline.itau.com.br/GRIPNET/bklcom.dll')
// when:
contentScript.ynabExportSelection()
// then:
let expectedCSV = `Date,Payee,Category,Memo,Outflow,Inflow
17/05/2017,REND PAGO APLIC AUT MAIS,,,,1.30
18/05/2017,VENCIMENTO COMPROMISSADA,,,,87016.77
19/05/2017,INT PAG TIT BANCO 104,,,,-367.02
19/05/2017,REND PAGO APLIC AUT MAIS,,,,0.69
23/05/2017,TBI 8062.09114-8haithai,,,,-102.11
23/05/2017,INT APLICACAO EXCELLENCE,,,,-145000.00
23/05/2017,INT PERS VISA,,,,-16.90
23/05/2017,REND PAGO APLIC AUT MAIS,,,,101.84`
td.verify(displayErrorMessageMock(), {times: 0, ignoreExtraArgs: true})
td.verify(downloadMock.createTextFileForDownload(global.window, expectedCSV, 'text/csv'))
})
})
|
module.exports = function (grunt) {
"use strict";
var {{ bundle.getName() }};
var resourcesPath = 'src/{{ bundle.namespace|replace({'\\':'/'}) }}/Resources/';
{{ bundle.getName() }} = {
'destination': 'web/frontend/',
'js': [resourcesPath+'public/**/*.js', '!'+ resourcesPath+'public/vendor/**/*.js', 'Gruntfile.js'],
'all_scss': [resourcesPath+'public/scss/**/*.scss'],
'scss': [resourcesPath+'public/scss/style.scss', resourcesPath+'public/scss/legacy/ie/ie7.scss', resourcesPath+'public/scss/legacy/ie/ie8.scss'],
'twig': [resourcesPath+'views/**/*.html.twig'],
'img': [resourcesPath+'public/img/**/*.{png,jpg,jpeg,gif,webp}'],
'svg': [resourcesPath+'public/img/**/*.svg']
};
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
{{ bundle.getName() }}Scss: {
files: {{ bundle.getName() }}.all_scss,
tasks: ['sass', 'cmq', 'cssmin']
},
{{ bundle.getName() }}Js: {
files: {{ bundle.getName() }}.js,
tasks: ['uglify', 'concat']
},
{{ bundle.getName() }}Images: {
files: {{ bundle.getName() }}.img,
tasks: ['imagemin:{{ bundle.getName() }}'],
options: {
event: ['added', 'changed']
}
},
{{ bundle.getName() }}Svg: {
files: {{ bundle.getName() }}.svg,
tasks: ['svg2png:{{ bundle.getName() }}', 'svgmin'],
options: {
event: ['added', 'changed']
}
},
livereload: {
files: ['web/frontend/css/style.min.css', 'web/frontend/js/footer.min.js'],
options: {
livereload: true
}
}
},
sass: {
{{ bundle.getName() }}: {
options: {
style: 'compressed'
},
files: {
'web/frontend/.temp/css/style.css': resourcesPath+'public/scss/style.scss',
'web/frontend/.temp/css/ie8.css': resourcesPath+'public/scss/legacy/ie/ie8.scss',
'web/frontend/.temp/css/ie7.css': resourcesPath+'public/scss/legacy/ie/ie7.scss'
}
}
},
cmq: {
{{ bundle.getName() }}: {
files: {
'web/frontend/.temp/css/': 'web/frontend/.temp/css/style.css'
}
}
},
cssmin: {
{{ bundle.getName() }}: {
files: {
'web/frontend/css/style.min.css': [
'web/vendor/flexslider/flexslider.css',
'web/frontend/.temp/css/style.css'
],
'web/frontend/css/ie8.min.css': [
'web/vendor/flexslider/flexslider.css',
'web/frontend/.temp/css/ie8.css'
],
'web/frontend/css/ie7.min.css': [
'web/vendor/flexslider/flexslider.css',
'web/frontend/.temp/css/ie7.css'
]
}
}
},
jshint: {
options: {
camelcase: true,
curly: true,
eqeqeq: true,
eqnull: true,
forin: true,
indent: 4,
trailing: true,
undef: true,
browser: true,
devel: true,
node: true,
globals: {
jQuery: true,
$: true
}
},
{{ bundle.getName() }}: {
files: {
src: {{ bundle.getName() }}.js
}
}
},
uglify: {
analytics: {
files: {
'web/frontend/js/analytics.min.js': [
'vendor/kunstmaan/seo-bundle/Kunstmaan/SeoBundle/Resources/public/js/analytics.js'
]
}
},
vendors: {
options: {
mangle: {
except: ['jQuery']
}
},
files: {
'web/frontend/.temp/js/vendors.min.js': [
'web/vendor/jquery/dist/jquery.js',
'web/vendor/sass-bootstrap/js/modal.js',
'web/vendor/flexslider/jquery.flexslider.js',
'web/vendor/jquery.equalheights/jquery.equalheights.js',
'web/vendor/fitvids/jquery.fitvids.js',
'web/vendor/fancybox/source/jquery.fancybox.js',
'web/vendor/cupcake/js/navigation/jquery.navigation.js',
'web/vendor/cupcake/js/slider/jquery.slider.js'
]
}
},
{{ bundle.getName() }}: {
files: {
'web/frontend/.temp/js/app.min.js': [resourcesPath+'public/js/**/*.js']
}
}
},
concat: {
js: {
src: [
'web/frontend/js/modernizr-custom.js',
'web/frontend/.temp/js/vendors.min.js',
'web/frontend/.temp/js/app.min.js'
],
dest: 'web/frontend/js/footer.min.js'
}
},
imagemin: {
{{ bundle.getName() }}: {
options: {
optimizationLevel: 3,
progressive: true
},
files: [{
expand: true,
cwd: 'src/{{ bundle.namespace|replace({'\\':'/'}) }}/Resources/public/img',
src: '**/*.{png,jpg,jpeg,gif,webp}',
dest: 'src/{{ bundle.namespace|replace({'\\':'/'}) }}/Resources/public/img'
}]
}
},
svg2png: {
{{ bundle.getName() }}: {
files: [{
src: {{ bundle.getName() }}.svg
}]
}
},
svgmin: {
{{ bundle.getName() }}: {
options: {
plugins: [{
removeViewBox: false
}]
},
files: [{
expand: true,
cwd: 'src/{{ bundle.namespace|replace({'\\':'/'}) }}/Resources/public/img',
src: '**/*.svg',
dest: 'src/{{ bundle.namespace|replace({'\\':'/'}) }}/Resources/public/img'
}]
}
},
modernizr: {
{{ bundle.getName() }}: {
devFile: 'remote',
parseFiles: true,
files: {
src: [
{{ bundle.getName() }}.js,
{{ bundle.getName() }}.all_scss,
{{ bundle.getName() }}.twig
]
},
outputFile: {{ bundle.getName() }}.destination + 'js/modernizr-custom.js',
extra: {
'shiv' : false,
'printshiv' : false,
'load' : true,
'mq' : false,
'cssclasses' : true
},
extensibility: {
'addtest' : false,
'prefixed' : false,
'teststyles' : false,
'testprops' : false,
'testallprops' : false,
'hasevents' : false,
'prefixes' : false,
'domprefixes' : false
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-svg2png');
grunt.loadNpmTasks('grunt-svgmin');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks("grunt-modernizr");
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-combine-media-queries');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default', ['watch']);
grunt.registerTask('build', ['sass', 'cmq', 'cssmin', 'modernizr', 'uglify', 'concat']);
};
|
Clazz.declarePackage ("J.viewer");
Clazz.load (null, "J.viewer.OutputManager", ["java.lang.Boolean", "java.util.Date", "$.Hashtable", "$.Map", "JU.List", "$.PT", "$.SB", "J.api.Interface", "J.i18n.GT", "J.io.JmolBinary", "J.util.Escape", "$.Logger", "$.Txt", "J.viewer.FileManager", "$.JC", "$.Viewer"], function () {
c$ = Clazz.decorateAsClass (function () {
this.viewer = null;
this.privateKey = 0;
Clazz.instantialize (this, arguments);
}, J.viewer, "OutputManager");
$_M(c$, "setViewer",
function (viewer, privateKey) {
this.viewer = viewer;
this.privateKey = privateKey;
return this;
}, "J.viewer.Viewer,~N");
$_M(c$, "writeToOutputChannel",
($fz = function (params) {
var type = params.get ("type");
var fileName = params.get ("fileName");
var text = params.get ("text");
var bytes = params.get ("bytes");
var quality = J.viewer.OutputManager.getInt (params, "quality", -2147483648);
var out = params.get ("outputChannel");
var closeStream = (out == null);
var len = -1;
try {
if (!this.viewer.checkPrivateKey (this.privateKey)) return "ERROR: SECURITY";
if (bytes != null) {
if (out == null) out = this.openOutputChannel (this.privateKey, fileName, false, false);
out.write (bytes, 0, bytes.length);
} else if (text != null) {
if (out == null) out = this.openOutputChannel (this.privateKey, fileName, true, false);
out.append (text);
} else {
var errMsg = this.getOrSaveImage (params);
if (errMsg != null) return errMsg;
len = (params.get ("byteCount")).intValue ();
}} catch (exc) {
if (Clazz.exceptionOf (exc, Exception)) {
J.util.Logger.errorEx ("IO Exception", exc);
return exc.toString ();
} else {
throw exc;
}
} finally {
if (out != null) {
if (closeStream) out.closeChannel ();
len = out.getByteCount ();
}}
return (len < 0 ? "Creation of " + fileName + " failed: " + this.viewer.getErrorMessageUn () : "OK " + type + " " + (len > 0 ? len + " " : "") + fileName + (quality == -2147483648 ? "" : "; quality=" + quality));
}, $fz.isPrivate = true, $fz), "java.util.Map");
$_M(c$, "getOrSaveImage",
($fz = function (params) {
var bytes = null;
var errMsg = null;
var type = (params.get ("type")).toUpperCase ();
var fileName = params.get ("fileName");
var scripts = params.get ("scripts");
var objImage = params.get ("image");
var out = params.get ("outputChannel");
var asBytes = (out == null && fileName == null);
var closeChannel = (out == null && fileName != null);
var releaseImage = (objImage == null);
var image = (objImage == null ? this.viewer.getScreenImageBuffer (null, true) : objImage);
var isOK = false;
try {
if (image == null) return errMsg = this.viewer.getErrorMessage ();
if (out == null) out = this.openOutputChannel (this.privateKey, fileName, false, false);
if (out == null) return errMsg = "ERROR: canceled";
fileName = out.getFileName ();
var comment = null;
var stateData = null;
params.put ("date", this.viewer.apiPlatform.getDateFormat (false));
if (type.startsWith ("JP")) {
type = JU.PT.simpleReplace (type, "E", "");
if (type.equals ("JPG64")) {
params.put ("outputChannelTemp", this.getOutputChannel (null, null));
comment = "";
} else {
comment = (!asBytes ? this.getWrappedState (null, null, image, null) : "");
}} else if (type.equals ("PDF")) {
comment = "";
} else if (type.startsWith ("PNG")) {
comment = "";
var isPngj = type.equals ("PNGJ");
if (isPngj) {
var outTemp = this.getOutputChannel (null, null);
this.getWrappedState (fileName, scripts, image, outTemp);
stateData = outTemp.toByteArray ();
} else if (!asBytes) {
stateData = (this.getWrappedState (null, scripts, image, null)).getBytes ();
}if (stateData != null) {
params.put ("applicationData", stateData);
params.put ("applicationPrefix", "Jmol Type");
}if (type.equals ("PNGT")) params.put ("transparentColor", Integer.$valueOf (this.viewer.getBackgroundArgb ()));
type = "PNG";
}if (comment != null) params.put ("comment", comment.length == 0 ? J.viewer.Viewer.getJmolVersion () : comment);
var errRet = new Array (1);
isOK = this.createTheImage (image, type, out, params, errRet);
if (closeChannel) out.closeChannel ();
if (isOK) {
if (asBytes) bytes = out.toByteArray ();
else if (params.containsKey ("captureByteCount")) errMsg = "OK: " + params.get ("captureByteCount").toString () + " bytes";
} else {
errMsg = errRet[0];
}} finally {
if (releaseImage) this.viewer.releaseScreenImage ();
params.put ("byteCount", Integer.$valueOf (bytes != null ? bytes.length : isOK ? out.getByteCount () : -1));
if (objImage != null) {
return fileName;
}}
return (errMsg == null ? bytes : errMsg);
}, $fz.isPrivate = true, $fz), "java.util.Map");
$_M(c$, "getWrappedState",
function (fileName, scripts, objImage, out) {
var width = this.viewer.apiPlatform.getImageWidth (objImage);
var height = this.viewer.apiPlatform.getImageHeight (objImage);
if (width > 0 && !this.viewer.global.imageState && out == null || !this.viewer.global.preserveState) return "";
var s = this.viewer.getStateInfo3 (null, width, height);
if (out != null) {
if (fileName != null) this.viewer.fileManager.clearPngjCache (fileName);
return this.createZipSet (s, scripts, true, out);
}try {
s = J.viewer.JC.embedScript (J.viewer.FileManager.setScriptFileReferences (s, ".", null, null));
} catch (e) {
J.util.Logger.error ("state could not be saved: " + e.toString ());
s = "Jmol " + J.viewer.Viewer.getJmolVersion ();
}
return s;
}, "~S,~A,~O,JU.OC");
$_M(c$, "createTheImage",
($fz = function (objImage, type, out, params, errRet) {
type = type.substring (0, 1) + type.substring (1).toLowerCase ();
var ie = J.api.Interface.getInterface ("J.image." + type + "Encoder");
if (ie == null) {
errRet[0] = "Image encoder type " + type + " not available";
return false;
}return ie.createImage (this.viewer.apiPlatform, type, objImage, out, params, errRet);
}, $fz.isPrivate = true, $fz), "~O,~S,JU.OC,java.util.Map,~A");
$_M(c$, "outputToFile",
function (params) {
return this.handleOutputToFile (params, true);
}, "java.util.Map");
$_M(c$, "getOutputChannel",
function (fileName, fullPath) {
if (!this.viewer.haveAccess (J.viewer.Viewer.ACCESS.ALL)) return null;
if (fileName != null) {
fileName = this.getOutputFileNameFromDialog (fileName, -2147483648);
if (fileName == null) return null;
}if (fullPath != null) fullPath[0] = fileName;
var localName = (J.viewer.FileManager.isLocal (fileName) ? fileName : null);
try {
return this.openOutputChannel (this.privateKey, localName, false, false);
} catch (e) {
if (Clazz.exceptionOf (e, java.io.IOException)) {
J.util.Logger.info (e.toString ());
return null;
} else {
throw e;
}
}
}, "~S,~A");
$_M(c$, "processWriteOrCapture",
function (params) {
var fileName = params.get ("fileName");
if (fileName == null) return this.viewer.clipImageOrPasteText (params.get ("text"));
var bsFrames = params.get ("bsFrames");
var nVibes = J.viewer.OutputManager.getInt (params, "nVibes", 0);
return (bsFrames != null || nVibes != 0 ? this.processMultiFrameOutput (fileName, bsFrames, nVibes, params) : this.handleOutputToFile (params, true));
}, "java.util.Map");
c$.getInt = $_M(c$, "getInt",
($fz = function (params, key, def) {
var p = params.get (key);
return (p == null ? def : p.intValue ());
}, $fz.isPrivate = true, $fz), "java.util.Map,~S,~N");
$_M(c$, "processMultiFrameOutput",
($fz = function (fileName, bsFrames, nVibes, params) {
var info = "";
var n = 0;
var quality = J.viewer.OutputManager.getInt (params, "quality", -1);
fileName = this.setFullPath (params, this.getOutputFileNameFromDialog (fileName, quality));
if (fileName == null) return null;
var ptDot = fileName.indexOf (".");
if (ptDot < 0) ptDot = fileName.length;
var froot = fileName.substring (0, ptDot);
var fext = fileName.substring (ptDot);
var sb = new JU.SB ();
if (bsFrames == null) {
this.viewer.transformManager.vibrationOn = true;
sb = new JU.SB ();
for (var i = 0; i < nVibes; i++) {
for (var j = 0; j < 20; j++) {
this.viewer.transformManager.setVibrationT (j / 20 + 0.2501);
if (!this.writeFrame (++n, froot, fext, params, sb)) return "ERROR WRITING FILE SET: \n" + info;
}
}
this.viewer.setVibrationOff ();
} else {
for (var i = bsFrames.nextSetBit (0); i >= 0; i = bsFrames.nextSetBit (i + 1)) {
this.viewer.setCurrentModelIndex (i);
if (!this.writeFrame (++n, froot, fext, params, sb)) return "ERROR WRITING FILE SET: \n" + info;
}
}if (info.length == 0) info = "OK\n";
return info + "\n" + n + " files created";
}, $fz.isPrivate = true, $fz), "~S,JU.BS,~N,java.util.Map");
$_M(c$, "setFullPath",
($fz = function (params, fileName) {
var fullPath = params.get ("fullPath");
if (fullPath != null) fullPath[0] = fileName;
if (fileName == null) return null;
params.put ("fileName", fileName);
return fileName;
}, $fz.isPrivate = true, $fz), "java.util.Map,~S");
$_M(c$, "getOutputFromExport",
function (params) {
var width = J.viewer.OutputManager.getInt (params, "width", 0);
var height = J.viewer.OutputManager.getInt (params, "height", 0);
var fileName = params.get ("fileName");
if (fileName != null) {
fileName = this.setFullPath (params, this.getOutputFileNameFromDialog (fileName, -2147483648));
if (fileName == null) return null;
}this.viewer.mustRender = true;
var saveWidth = this.viewer.dimScreen.width;
var saveHeight = this.viewer.dimScreen.height;
this.viewer.resizeImage (width, height, true, true, false);
this.viewer.setModelVisibility ();
var data = this.viewer.repaintManager.renderExport (this.viewer.gdata, this.viewer.modelSet, params);
this.viewer.resizeImage (saveWidth, saveHeight, true, true, true);
return data;
}, "java.util.Map");
$_M(c$, "getImageAsBytes",
function (type, width, height, quality, errMsg) {
var saveWidth = this.viewer.dimScreen.width;
var saveHeight = this.viewer.dimScreen.height;
this.viewer.mustRender = true;
this.viewer.resizeImage (width, height, true, false, false);
this.viewer.setModelVisibility ();
this.viewer.creatingImage = true;
var bytes = null;
try {
var params = new java.util.Hashtable ();
params.put ("type", type);
if (quality > 0) params.put ("quality", Integer.$valueOf (quality));
var bytesOrError = this.getOrSaveImage (params);
if (Clazz.instanceOf (bytesOrError, String)) errMsg[0] = bytesOrError;
else bytes = bytesOrError;
} catch (e$$) {
if (Clazz.exceptionOf (e$$, Exception)) {
var e = e$$;
{
errMsg[0] = e.toString ();
this.viewer.setErrorMessage ("Error creating image: " + e, null);
}
} else if (Clazz.exceptionOf (e$$, Error)) {
var er = e$$;
{
this.viewer.handleError (er, false);
this.viewer.setErrorMessage ("Error creating image: " + er, null);
errMsg[0] = this.viewer.getErrorMessage ();
}
} else {
throw e$$;
}
}
this.viewer.creatingImage = false;
this.viewer.resizeImage (saveWidth, saveHeight, true, false, true);
return bytes;
}, "~S,~N,~N,~N,~A");
$_M(c$, "writeFileData",
function (fileName, type, modelIndex, parameters) {
var fullPath = new Array (1);
var out = this.getOutputChannel (fileName, fullPath);
if (out == null) return "";
fileName = fullPath[0];
var pathName = (type.equals ("FILE") ? this.viewer.getFullPathName () : null);
var getCurrentFile = (pathName != null && (pathName.equals ("string") || pathName.indexOf ("[]") >= 0 || pathName.equals ("JSNode")));
var asBytes = (pathName != null && !getCurrentFile);
if (asBytes) {
pathName = this.viewer.getModelSetPathName ();
if (pathName == null) return null;
}out.setType (type);
var msg = (type.equals ("PDB") || type.equals ("PQR") ? this.viewer.getPdbAtomData (null, out) : type.startsWith ("PLOT") ? this.viewer.modelSet.getPdbData (modelIndex, type.substring (5), this.viewer.getSelectionSet (false), parameters, out) : getCurrentFile ? out.append (this.viewer.getCurrentFileAsString ()).toString () : this.viewer.getFileAsBytes (pathName, out));
out.closeChannel ();
if (msg != null) msg = "OK " + msg + " " + fileName;
return msg;
}, "~S,~S,~N,~A");
$_M(c$, "writeFrame",
($fz = function (n, froot, fext, params, sb) {
var fileName = "0000" + n;
fileName = this.setFullPath (params, froot + fileName.substring (fileName.length - 4) + fext);
var msg = this.handleOutputToFile (params, false);
this.viewer.scriptEcho (msg);
sb.append (msg).append ("\n");
return msg.startsWith ("OK");
}, $fz.isPrivate = true, $fz), "~N,~S,~S,java.util.Map,JU.SB");
$_M(c$, "getOutputFileNameFromDialog",
($fz = function (fileName, quality) {
if (fileName == null || this.viewer.$isKiosk) return null;
var useDialog = (fileName.indexOf ("?") == 0);
if (useDialog) fileName = fileName.substring (1);
useDialog = new Boolean (useDialog | (this.viewer.isApplet () && (fileName.indexOf ("http:") < 0))).valueOf ();
fileName = J.viewer.FileManager.getLocalPathForWritingFile (this.viewer, fileName);
if (useDialog) fileName = this.viewer.dialogAsk (quality == -2147483648 ? "Save" : "Save Image", fileName);
return fileName;
}, $fz.isPrivate = true, $fz), "~S,~N");
$_M(c$, "handleOutputToFile",
function (params, doCheck) {
var sret = null;
var fileName = params.get ("fileName");
if (fileName == null) return null;
var type = params.get ("type");
var text = params.get ("text");
var width = J.viewer.OutputManager.getInt (params, "width", 0);
var height = J.viewer.OutputManager.getInt (params, "height", 0);
var quality = J.viewer.OutputManager.getInt (params, "quality", -2147483648);
var captureMode = J.viewer.OutputManager.getInt (params, "captureMode", -2147483648);
if (captureMode != -2147483648 && !this.viewer.allowCapture ()) return "ERROR: Cannot capture on this platform.";
var mustRender = (quality != -2147483648);
var localName = null;
if (captureMode != -2147483648) {
doCheck = false;
mustRender = false;
type = "GIF";
}if (doCheck) fileName = this.getOutputFileNameFromDialog (fileName, quality);
fileName = this.setFullPath (params, fileName);
if (fileName == null) return null;
params.put ("fileName", fileName);
if (J.viewer.FileManager.isLocal (fileName)) localName = fileName;
var saveWidth = this.viewer.dimScreen.width;
var saveHeight = this.viewer.dimScreen.height;
this.viewer.creatingImage = true;
if (mustRender) {
this.viewer.mustRender = true;
this.viewer.resizeImage (width, height, true, false, false);
this.viewer.setModelVisibility ();
}try {
if (type.equals ("JMOL")) type = "ZIPALL";
if (type.equals ("ZIP") || type.equals ("ZIPALL")) {
var scripts = params.get ("scripts");
if (scripts != null && type.equals ("ZIP")) type = "ZIPALL";
var out = this.getOutputChannel (fileName, null);
sret = this.createZipSet (text, scripts, type.equals ("ZIPALL"), out);
} else if (type.equals ("SCENE")) {
sret = this.createSceneSet (fileName, text, width, height);
} else {
var bytes = params.get ("bytes");
sret = this.viewer.statusManager.createImage (fileName, type, text, bytes, quality);
if (sret == null) {
var msg = null;
if (captureMode != -2147483648) {
var out = null;
var cparams = this.viewer.captureParams;
switch (captureMode) {
case 1073742032:
if (cparams != null) (cparams.get ("outputChannel")).closeChannel ();
out = this.getOutputChannel (localName, null);
if (out == null) {
sret = msg = "ERROR: capture canceled";
this.viewer.captureParams = null;
} else {
localName = out.getFileName ();
msg = type + "_STREAM_OPEN " + localName;
this.viewer.captureParams = params;
params.put ("captureFileName", localName);
params.put ("captureCount", Integer.$valueOf (1));
params.put ("captureMode", Integer.$valueOf (1073742032));
}break;
default:
if (cparams == null) {
sret = msg = "ERROR: capture not active";
} else {
params = cparams;
switch (captureMode) {
default:
sret = msg = "ERROR: CAPTURE MODE=" + captureMode + "?";
break;
case 1276118017:
if (Boolean.FALSE === params.get ("captureEnabled")) {
sret = msg = "capturing OFF; use CAPTURE ON/END/CANCEL to continue";
} else {
var count = J.viewer.OutputManager.getInt (params, "captureCount", 1);
params.put ("captureCount", Integer.$valueOf (++count));
msg = type + "_STREAM_ADD " + count;
}break;
case 1048589:
case 1048588:
params = cparams;
params.put ("captureEnabled", (captureMode == 1048589 ? Boolean.TRUE : Boolean.FALSE));
sret = type + "_STREAM_" + (captureMode == 1048589 ? "ON" : "OFF");
params.put ("captureMode", Integer.$valueOf (1276118017));
break;
case 1150985:
case 1073741874:
params = cparams;
params.put ("captureMode", Integer.$valueOf (captureMode));
fileName = params.get ("captureFileName");
msg = type + "_STREAM_" + (captureMode == 1150985 ? "CLOSE " : "CANCEL ") + params.get ("captureFileName");
this.viewer.captureParams = null;
this.viewer.prompt (J.i18n.GT._ ("Capture") + ": " + (captureMode == 1073741874 ? J.i18n.GT._ ("canceled") : J.i18n.GT.o (J.i18n.GT._ ("{0} saved"), fileName)), "OK", null, true);
}
break;
}break;
}
if (out != null) params.put ("outputChannel", out);
}params.put ("fileName", localName);
if (sret == null) sret = this.writeToOutputChannel (params);
this.viewer.statusManager.createImage (sret, type, null, null, quality);
if (msg != null) this.viewer.showString (msg + " (" + params.get ("captureByteCount") + " bytes)", false);
}}} catch (er) {
J.util.Logger.error (this.viewer.setErrorMessage (sret = "ERROR creating image??: " + er, null));
} finally {
this.viewer.creatingImage = false;
if (quality != -2147483648) this.viewer.resizeImage (saveWidth, saveHeight, true, false, true);
}
return sret;
}, "java.util.Map,~B");
$_M(c$, "setLogFile",
function (value) {
var path = null;
var logFilePath = this.viewer.getLogFilePath ();
if (logFilePath == null || value.indexOf ("\\") >= 0) {
value = null;
} else if (value.startsWith ("http://") || value.startsWith ("https://")) {
path = value;
} else if (value.indexOf ("/") >= 0) {
value = null;
} else if (value.length > 0) {
if (!value.startsWith ("JmolLog_")) value = "JmolLog_" + value;
path = this.getLogPath (logFilePath + value);
}if (path == null) value = null;
else J.util.Logger.info (J.i18n.GT.o (J.i18n.GT._ ("Setting log file to {0}"), path));
if (value == null || !this.viewer.haveAccess (J.viewer.Viewer.ACCESS.ALL)) {
J.util.Logger.info (J.i18n.GT._ ("Cannot set log file path."));
value = null;
} else {
this.viewer.logFileName = path;
this.viewer.global.setS ("_logFile", this.viewer.isApplet () ? value : path);
}return value;
}, "~S");
$_M(c$, "logToFile",
function (data) {
try {
var doClear = (data.equals ("$CLEAR$"));
if (data.indexOf ("$NOW$") >= 0) data = JU.PT.simpleReplace (data, "$NOW$", this.viewer.apiPlatform.getDateFormat (false));
if (this.viewer.logFileName == null) {
J.util.Logger.info (data);
return;
}var out = (this.viewer.haveAccess (J.viewer.Viewer.ACCESS.ALL) ? this.openOutputChannel (this.privateKey, this.viewer.logFileName, true, !doClear) : null);
if (!doClear) {
var ptEnd = data.indexOf ('\0');
if (ptEnd >= 0) data = data.substring (0, ptEnd);
out.append (data);
if (ptEnd < 0) out.append ("\n");
}var s = out.closeChannel ();
J.util.Logger.info (s);
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
if (J.util.Logger.debugging) J.util.Logger.debug ("cannot log " + data);
} else {
throw e;
}
}
}, "~S");
$_M(c$, "createZipSet",
($fz = function (script, scripts, includeRemoteFiles, out) {
var v = new JU.List ();
var fm = this.viewer.fileManager;
var fileNames = new JU.List ();
var crcMap = new java.util.Hashtable ();
var haveSceneScript = (scripts != null && scripts.length == 3 && scripts[1].startsWith ("###scene.spt###"));
var sceneScriptOnly = (haveSceneScript && scripts[2].equals ("min"));
if (!sceneScriptOnly) {
J.io.JmolBinary.getFileReferences (script, fileNames);
if (haveSceneScript) J.io.JmolBinary.getFileReferences (scripts[1], fileNames);
}var haveScripts = (!haveSceneScript && scripts != null && scripts.length > 0);
if (haveScripts) {
script = this.wrapPathForAllFiles ("script " + J.util.Escape.eS (scripts[0]), "");
for (var i = 0; i < scripts.length; i++) fileNames.addLast (scripts[i]);
}var nFiles = fileNames.size ();
var newFileNames = new JU.List ();
for (var iFile = 0; iFile < nFiles; iFile++) {
var name = fileNames.get (iFile);
var isLocal = !this.viewer.isJS && J.viewer.FileManager.isLocal (name);
var newName = name;
if (isLocal || includeRemoteFiles) {
var ptSlash = name.lastIndexOf ("/");
newName = (name.indexOf ("?") > 0 && name.indexOf ("|") < 0 ? JU.PT.replaceAllCharacters (name, "/:?\"'=&", "_") : J.viewer.FileManager.stripPath (name));
newName = JU.PT.replaceAllCharacters (newName, "[]", "_");
var isSparDir = (fm.spardirCache != null && fm.spardirCache.containsKey (name));
if (isLocal && name.indexOf ("|") < 0 && !isSparDir) {
v.addLast (name);
v.addLast (newName);
v.addLast (null);
} else {
var ret = (isSparDir ? fm.spardirCache.get (name) : fm.getFileAsBytes (name, null, true));
if (!JU.PT.isAB (ret)) return ret;
newName = this.addPngFileBytes (name, ret, iFile, crcMap, isSparDir, newName, ptSlash, v);
}name = "$SCRIPT_PATH$" + newName;
}crcMap.put (newName, newName);
newFileNames.addLast (name);
}
if (!sceneScriptOnly) {
script = J.util.Txt.replaceQuotedStrings (script, fileNames, newFileNames);
v.addLast ("state.spt");
v.addLast (null);
v.addLast (script.getBytes ());
}if (haveSceneScript) {
if (scripts[0] != null) {
v.addLast ("animate.spt");
v.addLast (null);
v.addLast (scripts[0].getBytes ());
}v.addLast ("scene.spt");
v.addLast (null);
script = J.util.Txt.replaceQuotedStrings (scripts[1], fileNames, newFileNames);
v.addLast (script.getBytes ());
}var sname = (haveSceneScript ? "scene.spt" : "state.spt");
v.addLast ("JmolManifest.txt");
v.addLast (null);
var sinfo = "# Jmol Manifest Zip Format 1.1\n# Created " + ( new java.util.Date ()) + "\n" + "# JmolVersion " + J.viewer.Viewer.getJmolVersion () + "\n" + sname;
v.addLast (sinfo.getBytes ());
v.addLast ("Jmol_version_" + J.viewer.Viewer.getJmolVersion ().$replace (' ', '_').$replace (':', '.'));
v.addLast (null);
v.addLast ( Clazz.newByteArray (0, 0));
if (out.getFileName () != null) {
var bytes = this.viewer.getImageAsBytes ("PNG", 0, 0, -1, null);
if (bytes != null) {
v.addLast ("preview.png");
v.addLast (null);
v.addLast (bytes);
}}return this.writeZipFile (this.privateKey, fm, this.viewer, out, v, "OK JMOL");
}, $fz.isPrivate = true, $fz), "~S,~A,~B,JU.OC");
$_M(c$, "addPngFileBytes",
($fz = function (name, ret, iFile, crcMap, isSparDir, newName, ptSlash, v) {
var crcValue = Integer.$valueOf (J.io.JmolBinary.getCrcValue (ret));
if (crcMap.containsKey (crcValue)) {
newName = crcMap.get (crcValue);
} else {
if (isSparDir) newName = newName.$replace ('.', '_');
if (crcMap.containsKey (newName)) {
var pt = newName.lastIndexOf (".");
if (pt > ptSlash) newName = newName.substring (0, pt) + "[" + iFile + "]" + newName.substring (pt);
else newName = newName + "[" + iFile + "]";
}v.addLast (name);
v.addLast (newName);
v.addLast (ret);
crcMap.put (crcValue, newName);
}return newName;
}, $fz.isPrivate = true, $fz), "~S,~A,~N,java.util.Hashtable,~B,~S,~N,JU.List");
$_M(c$, "writeZipFile",
($fz = function (privateKey, fm, viewer, out, fileNamesAndByteArrays, msg) {
var buf = Clazz.newByteArray (1024, 0);
var nBytesOut = 0;
var nBytes = 0;
var outFileName = out.getFileName ();
J.util.Logger.info ("creating zip file " + (outFileName == null ? "" : outFileName) + "...");
var fileList = "";
try {
var bos;
{
bos = out;
}var zos = J.io.JmolBinary.getZipOutputStream (bos);
for (var i = 0; i < fileNamesAndByteArrays.size (); i += 3) {
var fname = fileNamesAndByteArrays.get (i);
var bytes = null;
var data = fm.cacheGet (fname, false);
if (Clazz.instanceOf (data, java.util.Map)) continue;
if (fname.indexOf ("file:/") == 0) {
fname = fname.substring (5);
if (fname.length > 2 && fname.charAt (2) == ':') fname = fname.substring (1);
} else if (fname.indexOf ("cache://") == 0) {
fname = fname.substring (8);
}var fnameShort = fileNamesAndByteArrays.get (i + 1);
if (fnameShort == null) fnameShort = fname;
if (data != null) bytes = (JU.PT.isAB (data) ? data : (data).getBytes ());
if (bytes == null) bytes = fileNamesAndByteArrays.get (i + 2);
var key = ";" + fnameShort + ";";
if (fileList.indexOf (key) >= 0) {
J.util.Logger.info ("duplicate entry");
continue;
}fileList += key;
J.io.JmolBinary.addZipEntry (zos, fnameShort);
var nOut = 0;
if (bytes == null) {
var $in = viewer.getBufferedInputStream (fname);
var len;
while ((len = $in.read (buf, 0, 1024)) > 0) {
zos.write (buf, 0, len);
nOut += len;
}
$in.close ();
} else {
zos.write (bytes, 0, bytes.length);
nOut += bytes.length;
}nBytesOut += nOut;
J.io.JmolBinary.closeZipEntry (zos);
J.util.Logger.info ("...added " + fname + " (" + nOut + " bytes)");
}
zos.flush ();
zos.close ();
J.util.Logger.info (nBytesOut + " bytes prior to compression");
var ret = out.closeChannel ();
if (ret != null) {
if (ret.indexOf ("Exception") >= 0) return ret;
msg += " " + ret;
}nBytes = out.getByteCount ();
} catch (e) {
if (Clazz.exceptionOf (e, java.io.IOException)) {
J.util.Logger.info (e.toString ());
return e.toString ();
} else {
throw e;
}
}
var fileName = out.getFileName ();
return (fileName == null ? null : msg + " " + nBytes + " " + fileName);
}, $fz.isPrivate = true, $fz), "~N,J.viewer.FileManager,J.viewer.Viewer,JU.OC,JU.List,~S");
$_M(c$, "wrapPathForAllFiles",
function (cmd, strCatch) {
var vname = "v__" + ("" + Math.random ()).substring (3);
return "# Jmol script\n{\n\tVar " + vname + " = pathForAllFiles\n\tpathForAllFiles=\"$SCRIPT_PATH$\"\n\ttry{\n\t\t" + cmd + "\n\t}catch(e){" + strCatch + "}\n\tpathForAllFiles = " + vname + "\n}\n";
}, "~S,~S");
Clazz.defineStatics (c$,
"SCENE_TAG", "###scene.spt###");
});
|
'use strict';
angular.module('profileApp.storageconfig', [ 'ngRoute' ])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/providers/:provider_id/storageconfig', {
templateUrl : 'storageconfig/storageconfig.html',
controller : 'storageconfigCntrl'
}).otherwise({
redirectTo : '/providers'
});
} ])
.controller('storageconfigCntrl', function($scope, $routeParams, $modalInstance, ProviderService) {
$scope.storageTypeStub = storageTypeStub;
$scope.storageConfigStub = storageConfigStub;
$scope.selectedProvider = $routeParams.provider_id;
$scope.selectedStorageOption = 'Default';
// Call to ProviderService to details of provider
ProviderService.getProvider($routeParams.provider_id).then(function(data) {
$scope.provider_name = data[0].name;
});
//Handles closing of storage config modal window
$scope.ok = function () {
$modalInstance.close();
};
});
var storageConfigStub = {
name : 'Storage Config 1',
type : 'S3',
bucket : 'https://s3.amazonaws.com/bucket/object',
accessKeyId : 'test_id',
key : 'test_key'
};
var storageTypeStub = [ {
name : 'S3',
id : '1'
}, {
name : 'WebDav',
id : '2'
}, {
name : 'Netstorage',
id : '3'
}, {
name : 'Azure',
id : '4'
}, {
name : 'SFTP',
id : '5'
} ];
|
const request = require('request');
const parser = require('xml2json');
const helpers = require('./helpers/headerGenerator.js');
const expansion = require('./helpers/expansion.js');
function getCardFromMkm(cardName) {
var url = `https://www.mkmapi.eu/ws/v1.1/products/${encodeURIComponent(cardName)}/1/1/false`;
return new Promise(function(resolve, rej) {
request({
url,
headers: {
Authorization: helpers.generateAuthHeader('GET', url),
}
}, function(err, res, body) {
if(err)
return rej(err);
if(res.statusCode >= 400)
return rej();
var cards = parser.toJson(body, {object: true}).response.product;
resolve(cards);
});
})
.then(res => {
if(!Array.isArray(res))
res = [res];
return res.filter(card => card.rarity !== 'Special' && card.category.categoryName === 'Magic Single')
.map((card, i, res) => {
return {
names: res[i].name.map(el => el.productName),
expansion: expansion.getExpansionCode(card.expansion),
expansionMkm: card.expansion,
number: card.number,
rarity: card.rarity,
prices: {
SELL: card.priceGuide.SELL,
LOW: card.priceGuide.LOW,
LOWEX: card.priceGuide.LOWEX,
LOWFOIL: card.priceGuide.LOWFOIL,
AVG: card.priceGuide.AVG,
TREND: card.priceGuide.TREND,
},
};
});
});
};
module.exports = {
getCardFromMkm,
};
|
var test = require('tape');
var DepTree = require('../dep-tree.js');
test(function(t) {
var tree = new DepTree();
// no generations
t.deepEqual(tree.solve('sdf'), [], '1) No parents');
// one generation
tree.add('grandparent', 'parent1');
tree.add('grandparent', 'parent2');
t.deepEqual(tree.solve('sdf'), [], '2) No parents');
t.deepEqual(tree.solve('parent1'), [ 'grandparent', 'parent1' ], '1) One Generation');
t.deepEqual(tree.solve('parent2'), [ 'grandparent', 'parent2' ], '2) One Generation');
// two generations
tree.add('parent1', 'me');
tree.add('parent2', 'me');
t.deepEqual(tree.solve('sdf'), [], '3) No parents');
t.deepEqual(tree.solve('parent1'), [ 'grandparent', 'parent1' ], '1) One Generation');
t.deepEqual(tree.solve('parent2'), [ 'grandparent', 'parent2' ], '2) One Generation');
t.deepEqual(tree.solve('me'), [ 'grandparent', 'parent1', 'parent2', 'me' ], 'Two Generations');
t.end();
});
|
var React = require('react')
var ReactDOM = require('react-dom')
var App = require('./test/App')
ReactDOM.render(
React.createElement(App),
document.getElementById('root')
)
|
'use strict';
/**
* @ngdoc controller
* @name Merchello.Dashboards.Sales.ListController
* @function
*
* @description
* The controller for the orders list page
*/
angular.module('merchello').controller('Merchello.Backoffice.SalesListController',
['$scope', '$element', '$log', 'angularHelper', 'assetsService', 'notificationsService', 'merchelloTabsFactory', 'settingsResource',
'invoiceResource', 'queryDisplayBuilder', 'queryResultDisplayBuilder', 'invoiceDisplayBuilder', 'settingDisplayBuilder',
function($scope, $element, $log, angularHelper, assetsService, notificationService, merchelloTabsFactory, settingsResource, invoiceResource,
queryDisplayBuilder, queryResultDisplayBuilder, invoiceDisplayBuilder, settingDisplayBuilder)
{
// expose on scope
$scope.loaded = true;
$scope.currentPage = 0;
$scope.tabs = [];
$scope.filterText = '';
$scope.filterStartDate = '';
$scope.filterEndDate = '';
$scope.invoices = [];
$scope.limitAmount = '25';
$scope.maxPages = 0;
$scope.orderIssues = [];
$scope.salesLoaded = true;
$scope.selectAllOrders = false;
$scope.selectedOrderCount = 0;
$scope.settings = {};
$scope.sortOrder = "desc";
$scope.sortProperty = "-invoiceNumber";
$scope.visible = {};
$scope.visible.bulkActionDropdown = false;
$scope.currentFilters = [];
$scope.dateFilterOpen = false;
// exposed methods
$scope.getCurrencySymbol = getCurrencySymbol;
$scope.resetFilters = resetFilters;
$scope.toggleDateFilterOpen = toggleDateFilterOpen;
// for testing
$scope.itemCount = 0;
var allCurrencies = [];
var globalCurrency = '$';
//--------------------------------------------------------------------------------------
// Event Handlers
//--------------------------------------------------------------------------------------
/**
* @ngdoc method
* @name changePage
* @function
*
* @description
* Changes the current page.
*/
$scope.changePage = function (page) {
$scope.preValuesLoaded = false;
$scope.currentPage = page;
var query = $scope.dateFilterOpen ? buildQuery($scope.filterText, $scope.filterStartDate, $scope.filterEndDate) : buildQuery($scope.filterText);
loadInvoices(query);
};
/**
* @ngdoc method
* @name changeSortOrder
* @function
*
* @description
* Helper function to set the current sort on the table and switch the
* direction if the property is already the current sort column.
*/
$scope.changeSortOrder = function (propertyToSort) {
if ($scope.sortProperty == propertyToSort) {
if ($scope.sortOrder == "asc") {
$scope.sortProperty = "-" + propertyToSort;
$scope.sortOrder = "desc";
} else {
$scope.sortProperty = propertyToSort;
$scope.sortOrder = "asc";
}
} else {
$scope.sortProperty = propertyToSort;
$scope.sortOrder = "asc";
}
$scope.currentPage = 0;
var query = $scope.dateFilterOpen ? buildQuery($scope.filterText, $scope.filterStartDate, $scope.filterEndDate) : buildQuery($scope.filterText);
loadInvoices(query);
};
/**
* @ngdoc method
* @name limitChanged
* @function
*
* @description
* Helper function to set the amount of items to show per page for the paging filters and calculations
*/
$scope.limitChanged = function (newVal) {
$scope.preValuesLoaded = false;
$scope.limitAmount = newVal;
$scope.currentPage = 0;
var query = $scope.dateFilterOpen ? buildQuery($scope.filterText, $scope.filterStartDate, $scope.filterEndDate) : buildQuery($scope.filterText);
loadInvoices(query);
};
/**
* @ngdoc method
* @name filterWithDates
* @function
*
* @description
* Fired when the filter button next to the filter text box at the top of the page is clicked.
*/
$scope.filterInvoices = function(filterStartDate, filterEndDate, filterText) {
$scope.preValuesLoaded = false;
var query = buildQuery(filterText, filterStartDate, filterEndDate);
loadInvoices(query);
};
$scope.termFilterInvoices = function(filterText) {
$scope.preValuesLoaded = false;
var query = buildQuery(filterText);
loadInvoices(query);
};
//--------------------------------------------------------------------------------------
// Helper Methods
//--------------------------------------------------------------------------------------
/**
* @ngdoc method
* @name setVariables
* @function
*
* @description
* Returns sort information based off the current $scope.sortProperty.
*/
$scope.sortInfo = function() {
var sortDirection, sortBy;
// If the sortProperty starts with '-', it's representing a descending value.
if ($scope.sortProperty.indexOf('-') > -1) {
// Get the text after the '-' for sortBy
sortBy = $scope.sortProperty.split('-')[1];
sortDirection = 'Descending';
// Otherwise it is ascending.
} else {
sortBy = $scope.sortProperty;
sortDirection = 'Ascending';
}
return {
sortBy: sortBy.toLowerCase(), // We'll want the sortBy all lower case for API purposes.
sortDirection: sortDirection
}
};
/**
* @ngdoc method
* @name numberOfPages
* @function
*
* @description
* Helper function to get the amount of items to show per page for the paging
*/
$scope.numberOfPages = function () {
return $scope.maxPages;
//return Math.ceil($scope.products.length / $scope.limitAmount);
};
// PRIVATE
function init() {
$scope.currencySymbol = '$';
resetFilters();
$scope.tabs = merchelloTabsFactory.createSalesListTabs();
$scope.tabs.setActive('saleslist');
$scope.loaded = true;
$scope.dateFilterOpen = false;
}
function loadInvoices(query) {
$scope.salesLoaded = false;
$scope.salesLoaded = false;
var promise = invoiceResource.searchInvoices(query);
promise.then(function (response) {
var queryResult = queryResultDisplayBuilder.transform(response, invoiceDisplayBuilder);
$scope.invoices = queryResult.items;
$scope.loaded = true;
$scope.preValuesLoaded = true;
$scope.salesLoaded = true;
$scope.maxPages = queryResult.totalPages;
$scope.itemCount = queryResult.totalItems;
loadSettings();
}, function (reason) {
notificationsService.error("Failed To Load Invoices", reason.message);
});
}
/**
* @ngdoc method
* @name resetFilters
* @function
*
* @description
* Fired when the reset filter button is clicked.
*/
function resetFilters() {
var query = buildQuery();
toggleDateFilterOpen();
$scope.currentFilters = [];
$scope.filterText = '';
setDefaultDates(new Date());
loadInvoices(query);
$scope.filterAction = false;
};
/**
* @ngdoc method
* @name resetFilters
* @function
*
* @description
* Fired when the open date filter button is clicked.
*/
function toggleDateFilterOpen() {
$scope.dateFilterOpen = !$scope.dateFilterOpen;
};
/**
* @ngdoc method
* @name loadSettings
* @function
*
* @description - Load the Merchello settings.
*/
function loadSettings() {
// this is needed for the date format
var settingsPromise = settingsResource.getAllSettings();
settingsPromise.then(function(allSettings) {
$scope.settings = settingDisplayBuilder.transform(allSettings);
}, function(reason) {
notificationService.error('Failed to load all settings', reason.message);
});
// currency matching
var currenciesPromise = settingsResource.getAllCurrencies();
currenciesPromise.then(function(currencies) {
allCurrencies = currencies;
}, function(reason) {
notificationService.error('Failed to load all currencies', reason.message);
});
// default currency
var currencySymbolPromise = settingsResource.getCurrencySymbol();
currencySymbolPromise.then(function (currencySymbol) {
globalCurrency = currencySymbol;
}, function (reason) {
notificationService.error('Failed to load the currency symbol', reason.message);
});
};
/**
* @ngdoc method
* @name buildQuery
* @function
*
* @description
* Perpares a new query object for passing to the ApiController
*/
function buildQuery(filterText, startDate, endDate) {
var page = $scope.currentPage;
var perPage = $scope.limitAmount;
var sortBy = $scope.sortInfo().sortBy;
var sortDirection = $scope.sortInfo().sortDirection;
if (filterText === undefined) {
filterText = '';
}
// back to page 0 if filterText or startDate change
if (filterText !== $scope.filterText || (startDate !== $scope.filterStartDate && $scope.dateFilterOpen)) {
page = 0;
$scope.currentPage = 0;
}
var dateSearch = false;
if (startDate !== undefined && endDate !== undefined) {
$scope.filterStartDate = startDate;
$scope.filterEndDate = endDate;
dateSearch = true;
}
$scope.filterText = filterText;
var query = queryDisplayBuilder.createDefault();
query.currentPage = page;
query.itemsPerPage = perPage;
query.sortBy = sortBy;
query.sortDirection = sortDirection;
if(dateSearch) {
query.addInvoiceDateParam(startDate, 'start');
query.addInvoiceDateParam(endDate, 'end');
}
query.addFilterTermParam(filterText);
if (query.parameters.length > 0) {
$scope.currentFilters = query.parameters;
}
return query;
};
/**
* @ngdoc method
* @name getCurrencySymbol
* @function
*
* @description
* Utility method to get the currency symbol for an invoice
*/
function getCurrencySymbol(invoice) {
if (invoice.currency.symbol !== '') {
return invoice.currency.symbol;
}
var currencyCode = invoice.getCurrencyCode();
var currency = _.find(allCurrencies, function(currency) {
return currency.currencyCode === currencyCode;
});
if(currency === null || currency === undefined) {
return globalCurrency;
} else {
return currency.symbol;
}
}
/**
* @ngdoc method
* @name setDefaultDates
* @function
*
* @description
* Sets the default dates
*/
function setDefaultDates(actual) {
var month = actual.getMonth() == 0 ? 11 : actual.getMonth() - 1;
var start = new Date(actual.getFullYear(), month, actual.getDate());
var end = new Date(actual.getFullYear(), actual.getMonth(), actual.getDate());
$scope.filterStartDate = start.toLocaleDateString();
$scope.filterEndDate = end.toLocaleDateString();
}
init();
}]);
|
Rickshaw = {
namespace: function(namespace, obj) {
var parts = namespace.split('.');
// for rudimentary compatibility w/ node
var root = typeof global != 'undefined' ? global : window;
var parent = root.Rickshaw;
for(var i = 1, length = parts.length; i < length; i++) {
currentPart = parts[i];
parent[currentPart] = parent[currentPart] || {};
parent = parent[currentPart];
}
return parent;
},
keys: function(obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
},
extend: function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
};
|
'use strict';
describe('jsonErrors', function(){
var sinon = require('sinon');
var sut = require('../../../lib/middleware/jsonErrors.js');
var res = {
json: sinon.stub()
};
beforeEach(function(){
res.json.reset();
});
it('is middleware', function(){
sut.should.be.type('function');
});
it('sends Error details to the response', function(){
sut(new Error('dogs'), null, res, null);
sinon.assert.calledWith(res.json, 500, sinon.match({
'message':'dogs'
}));
});
it('handles non Errors', function(){
sut('asdf', null, res, null);
sinon.assert.calledWith(res.json, 500, sinon.match({
'message': 'asdf'
}));
});
});
|
angular.module('app').config(function(ScreenProvider) {
ScreenProvider.register('screen-max-index', {
ScreenTitle: 'List Maxes',
controller: function($scope, Restangular) {
$scope.q = {};
$scope.getMaxList = function() {
$scope.q.max = Restangular.all('max').getList({sort:'-date'}).then(function(maxes) {
$scope.maxes = maxes;
});
};
$scope.remove = function(m) {
m.remove();
};
$scope.getMaxList();
}
});
});
|
'use strict';
var url = '/api/v1.0/';
angular.module('auth.services', [])
.factory('authService', [ '$http', '$window', function($http, $window) {
var auth = {};
auth.saveToken = function(token) {
$window.localStorage['beryl-client-token'] = token;
};
auth.getToken = function() {
return $window.localStorage['beryl-client-token'];
};
auth.isLoggedIn = function() {
var token = auth.getToken();
console.log('in auth.isLoggedIn token=' + token);
if (token && token != 'undefined') {
var payload = JSON.parse($window.atob(token.split('.')[1]));
console.log('in auth.isLoggedIn payload={0}', payload);
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
auth.currentUser = function() {
if (auth.isLoggedIn()) {
var token = auth.getToken();
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.username;
}
};
auth.register = function(user) {
return $http.post(url + '/register', user).success(function(data) {
auth.saveToken(data.token);
});
};
auth.logIn = function(user) {
return $http.post(url + '/login', user).success(function(data) {
auth.saveToken(data.token);
});
};
auth.logOut = function() {
$window.localStorage.removeItem('beryl-client-token');
};
return auth;
} ])
.factory('authInterceptor', ['$injector','API',function authInterceptor($injector,API) {
var interceptor = {};
interceptor.request = function(config) {
console.log('testInterceptor request config.url=%s', config.url);
var authService = $injector.get('authService');
var token = authService.getToken();
console.log('testInterceptor request config.url.indexOf(API)=%s, token=%s', config.url.indexOf(API), token);
if (config.url.indexOf(API) === 0 && token) {
console.log('testInterceptor request --send token = ' + token);
config.headers.Authorization = 'Bearer ' + token;
}
return config;
};
interceptor.response = function(res) {
console.log('testInterceptor response res.config.url=%s', res.config.url);
console.log('testInterceptor response: res.config.url.indexOf(API)=%s, res.data.token=%s ',res.config.url.indexOf(API),res.data.token);
//authService.saveToken('aabbcc');
var authService = $injector.get('authService');
if(res.config.url.indexOf(API) === 0 && res.data.token) {
console.log('here');
authService.saveToken(res.data.token);
}
return res;
};
interceptor.responseError= function(res) {
console.log('testInterceptor responseError');
return res;
};
return interceptor;
}]); |
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var ActionSettingsBackupRestore = React.createClass({
displayName: 'ActionSettingsBackupRestore',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: "M14 12c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2zm-2-9c-4.97 0-9 4.03-9 9H0l4 4 4-4H5c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.51 0-2.91-.49-4.06-1.3l-1.42 1.44C8.04 20.3 9.94 21 12 21c4.97 0 9-4.03 9-9s-4.03-9-9-9z" })
);
}
});
module.exports = ActionSettingsBackupRestore; |
'use strict';
angular.module('mean.customer').config(['$stateProvider',
function($stateProvider) {
$stateProvider.state('customer example page', {
url: '/customer/example',
templateUrl: 'customer/views/index.html'
});
}
]);
|
'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.github.cnpmjs.org/imagemin/optipng-bin/v' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'macos/optipng', 'darwin')
.src(url + 'linux/x86/optipng', 'linux', 'x86')
.src(url + 'linux/x64/optipng', 'linux', 'x64')
.src(url + 'freebsd/x86/optipng', 'freebsd', 'x86')
.src(url + 'freebsd/x64/optipng', 'freebsd', 'x64')
.src(url + 'sunos/x86/optipng', 'sunos', 'x86')
.src(url + 'sunos/x64/optipng', 'sunos', 'x64')
.src(url + 'win/optipng.exe', 'win32')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'optipng.exe' : 'optipng');
|
// Backbone.js 0.9.2
// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
(function(){
// Initial Setup
// -------------
// Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create a local reference to splice.
var splice = Array.prototype.splice;
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = root.Backbone = {};
}
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '0.9.2';
// Require Underscore, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
// For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
Backbone.$ = root.jQuery || root.Zepto || root.ender;
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// -----------------
// Regular expression used to split event strings
var eventSplitter = /\s+/;
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback functions
// to an event; trigger`-ing an event fires all callbacks in succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind one or more space separated events, `events`, to a `callback`
// function. Passing `"all"` will bind the callback to all events fired.
on: function(events, callback, context) {
var calls, event, list;
if (!callback) return this;
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
while (event = events.shift()) {
list = calls[event] || (calls[event] = []);
list.push(callback, context);
}
return this;
},
// Remove one or many callbacks. If `context` is null, removes all callbacks
// with that function. If `callback` is null, removes all callbacks for the
// event. If `events` is null, removes all bound callbacks for all events.
off: function(events, callback, context) {
var event, calls, list, i;
// No events, or removing *all* events.
if (!(calls = this._callbacks)) return this;
if (!(events || callback || context)) {
delete this._callbacks;
return this;
}
events = events ? events.split(eventSplitter) : _.keys(calls);
// Loop through the callback list, splicing where appropriate.
while (event = events.shift()) {
if (!(list = calls[event]) || !(callback || context)) {
delete calls[event];
continue;
}
for (i = list.length - 2; i >= 0; i -= 2) {
if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) {
list.splice(i, 2);
}
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(events) {
var event, calls, list, i, length, args, all, rest;
if (!(calls = this._callbacks)) return this;
rest = [];
events = events.split(eventSplitter);
for (i = 1, length = arguments.length; i < length; i++) {
rest[i - 1] = arguments[i];
}
// For each event, walk through the list of callbacks twice, first to
// trigger the event, then to trigger any `"all"` callbacks.
while (event = events.shift()) {
// Copy callback lists to prevent modification.
if (all = calls.all) all = all.slice();
if (list = calls[event]) list = list.slice();
// Execute event callbacks.
if (list) {
for (i = 0, length = list.length; i < length; i += 2) {
list[i].apply(list[i + 1] || this, rest);
}
}
// Execute "all" callbacks.
if (all) {
args = [event].concat(rest);
for (i = 0, length = all.length; i < length; i += 2) {
all[i].apply(all[i + 1] || this, args);
}
}
}
return this;
}
};
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Backbone.Model
// --------------
// Create a new model, with defined attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
if (options && options.parse) attributes = this.parse(attributes);
if (defaults = getValue(this, 'defaults')) {
attributes = _.extend({}, defaults, attributes);
}
if (options && options.collection) this.collection = options.collection;
this.attributes = {};
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.changed = {};
this._silent = {};
this._pending = {};
this.set(attributes, {silent: true});
// Reset change tracking.
this.changed = {};
this._silent = {};
this._pending = {};
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// A hash of attributes that have silently changed since the last time
// `change` was called. Will become pending attributes on the next call.
_silent: null,
// A hash of attributes that have changed since the last `'change'` event
// began.
_pending: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
var html;
if (html = this._escapedAttributes[attr]) return html;
var val = this.get(attr);
return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val);
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"` unless
// you choose to silence it.
set: function(key, value, options) {
var attrs, attr, val;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
// Extract attributes and options.
options || (options = {});
if (!attrs) return this;
if (attrs instanceof Model) attrs = attrs.attributes;
if (options.unset) for (attr in attrs) attrs[attr] = void 0;
// Run validation.
if (!this._validate(attrs, options)) return false;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
var changes = options.changes = {};
var now = this.attributes;
var escaped = this._escapedAttributes;
var prev = this._previousAttributes || {};
// For each `set` attribute...
for (attr in attrs) {
val = attrs[attr];
// If the new and current value differ, record the change.
if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
delete escaped[attr];
(options.silent ? this._silent : changes)[attr] = true;
}
// Update or delete the current value.
options.unset ? delete now[attr] : now[attr] = val;
// If the new and previous value differ, record the change. If not,
// then remove changes for this attribute.
if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) {
this.changed[attr] = val;
if (!options.silent) this._pending[attr] = true;
} else {
delete this.changed[attr];
delete this._pending[attr];
}
}
// Fire the `"change"` events.
if (!options.silent) this.change(options);
return this;
},
// Remove an attribute from the model, firing `"change"` unless you choose
// to silence it. `unset` is a noop if the attribute doesn't exist.
unset: function(attr, options) {
options = _.extend({}, options, {unset: true});
return this.set(attr, null, options);
},
// Clear all attributes on the model, firing `"change"` unless you choose
// to silence it.
clear: function(options) {
options = _.extend({}, options, {unset: true});
return this.set(_.clone(this.attributes), options);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overriden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
if (!model.set(model.parse(resp, xhr), options)) return false;
if (success) success(model, resp);
};
options.error = Backbone.wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, value, options) {
var attrs, current;
// Handle both `("key", value)` and `({key: value})` -style calls.
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
options = options ? _.clone(options) : {};
// If we're "wait"-ing to set changed attributes, validate early.
if (options.wait) {
if (!this._validate(attrs, options)) return false;
current = _.clone(this.attributes);
}
// Regular saves `set` attributes before persisting to the server.
var silentOptions = _.extend({}, options, {silent: true});
if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
return false;
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
var serverAttrs = model.parse(resp, xhr);
if (options.wait) {
delete options.wait;
serverAttrs = _.extend(attrs || {}, serverAttrs);
}
if (!model.set(serverAttrs, options)) return false;
if (success) {
success(model, resp);
} else {
model.trigger('sync', model, resp, options);
}
};
// Finish configuring and sending the Ajax request.
options.error = Backbone.wrapError(options.error, model, options);
var method = this.isNew() ? 'create' : 'update';
var xhr = (this.sync || Backbone.sync).call(this, method, this, options);
if (options.wait) this.clear(silentOptions).set(current, silentOptions);
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var triggerDestroy = function() {
model.trigger('destroy', model, model.collection, options);
};
if (this.isNew()) {
triggerDestroy();
return false;
}
options.success = function(resp) {
if (options.wait) triggerDestroy();
if (success) {
success(model, resp);
} else {
model.trigger('sync', model, resp, options);
}
};
options.error = Backbone.wrapError(options.error, model, options);
var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options);
if (!options.wait) triggerDestroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, xhr) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return this.id == null;
},
// Call this method to manually fire a `"change"` event for this model and
// a `"change:attribute"` event for each changed attribute.
// Calling this will cause all objects observing the model to update.
change: function(options) {
options || (options = {});
var changing = this._changing;
this._changing = true;
// Silent changes become pending changes.
for (var attr in this._silent) this._pending[attr] = true;
// Silent changes are triggered.
var changes = _.extend({}, options.changes, this._silent);
this._silent = {};
for (var attr in changes) {
this.trigger('change:' + attr, this, this.get(attr), options);
}
if (changing) return this;
// Continue firing `"change"` events while there are pending changes.
while (!_.isEmpty(this._pending)) {
this._pending = {};
this.trigger('change', this, options);
// Pending and silent changes still remain.
for (var attr in this.changed) {
if (this._pending[attr] || this._silent[attr]) continue;
delete this.changed[attr];
}
this._previousAttributes = _.clone(this.attributes);
}
this._changing = false;
return this;
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false, old = this._previousAttributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Check if the model is currently in a valid state. It's only possible to
// get into an *invalid* state if you're using silent changes.
isValid: function() {
return !this.validate || !this.validate(this.attributes);
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. If a specific `error` callback has
// been passed, call that instead of firing the general `"error"` event.
_validate: function(attrs, options) {
if (options.silent || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validate(attrs, options);
if (!error) return true;
if (options && options.error) {
options.error(this, error, options);
} else {
this.trigger('error', this, error, options);
}
return false;
}
});
// Backbone.Collection
// -------------------
// Provides a standard collection class for our sets of models, ordered
// or unordered. If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator !== undefined) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, {silent: true, parse: options.parse});
};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Add a model, or list of models to the set. Pass **silent** to avoid
// firing the `add` event for every new model.
add: function(models, options) {
var i, index, length, model, cid, id, cids = {}, ids = {}, dups = [];
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
// Begin by turning bare objects into model references, and preventing
// invalid models or duplicate models from being added.
for (i = 0, length = models.length; i < length; i++) {
if (!(model = models[i] = this._prepareModel(models[i], options))) {
throw new Error("Can't add an invalid model to a collection");
}
cid = model.cid;
id = model.id;
if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
dups.push(i);
continue;
}
cids[cid] = ids[id] = model;
}
// Remove duplicates.
i = dups.length;
while (i--) {
dups[i] = models.splice(dups[i], 1)[0];
}
// Listen to added models' events, and index models for lookup by
// `id` and by `cid`.
for (i = 0, length = models.length; i < length; i++) {
(model = models[i]).on('all', this._onModelEvent, this);
this._byCid[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
// Insert models into the collection, re-sorting if needed, and triggering
// `add` events unless silenced.
this.length += length;
index = options.at != null ? options.at : this.models.length;
splice.apply(this.models, [index, 0].concat(models));
if (this.comparator && options.at == null) this.sort({silent: true});
if (options.silent) return this;
for (i = 0, length = this.models.length; i < length; i++) {
if (!cids[(model = this.models[i]).cid]) continue;
options.index = i;
model.trigger('add', model, this, options);
}
// Merge in duplicate models.
if (options.merge) {
for (i = 0, length = dups.length; i < length; i++) {
if (model = this._byId[dups[i].id]) {
model.set(dups[i], options);
}
}
}
return this;
},
// Remove a model, or a list of models from the set. Pass silent to avoid
// firing the `remove` event for every model removed.
remove: function(models, options) {
var i, l, index, model;
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
for (i = 0, l = models.length; i < l; i++) {
model = this.getByCid(models[i]) || this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byCid[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
},
// Add a model to the end of the collection.
push: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, options);
return model;
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: 0}, options));
return model;
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function(begin, end) {
return this.models.slice(begin, end);
},
// Get a model from the set by id.
get: function(id) {
if (id == null) return void 0;
return this._byId[id.id != null ? id.id : id];
},
// Get a model from the set by client id.
getByCid: function(cid) {
return cid && this._byCid[cid.cid || cid];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of `filter`.
where: function(attrs) {
if (_.isEmpty(attrs)) return [];
return this.filter(function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
options || (options = {});
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
var boundComparator = _.bind(this.comparator, this);
if (this.comparator.length == 1) {
this.models = this.sortBy(boundComparator);
} else {
this.models.sort(boundComparator);
}
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.map(this.models, function(model){ return model.get(attr); });
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any `add` or `remove` events. Fires `reset` when finished.
reset: function(models, options) {
models || (models = []);
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
this._reset();
this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `add: true` is passed, appends the
// models to the collection instead of resetting.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === undefined) options.parse = true;
var collection = this;
var success = options.success;
options.success = function(resp, status, xhr) {
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
if (success) success(collection, resp);
};
options.error = Backbone.wrapError(options.error, collection, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
var coll = this;
options = options ? _.clone(options) : {};
model = this._prepareModel(model, options);
if (!model) return false;
if (!options.wait) coll.add(model, options);
var success = options.success;
options.success = function(nextModel, resp, xhr) {
if (options.wait) coll.add(nextModel, options);
if (success) {
success(nextModel, resp);
} else {
nextModel.trigger('sync', model, resp, options);
}
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, xhr) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Proxy to _'s chain. Can't be proxied the same way the rest of the
// underscore methods are proxied because it relies on the underscore
// constructor.
chain: function() {
return _(this.models).chain();
},
// Reset all internal state. Called when the collection is reset.
_reset: function(options) {
this.length = 0;
this.models = [];
this._byId = {};
this._byCid = {};
},
// Prepare a model or hash of attributes to be added to this collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) {
if (!attrs.collection) attrs.collection = this;
return attrs;
}
options || (options = {});
options.collection = this;
var model = new this.model(attrs, options);
if (!model._validate(model.attributes, options)) return false;
return model;
},
// Internal method to remove a model's ties to a collection.
_removeReference: function(model) {
if (this == model.collection) {
delete model.collection;
}
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event == 'add' || event == 'remove') && collection != this) return;
if (event == 'destroy') {
this.remove(model, options);
}
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find',
'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any',
'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex',
'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf',
'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
};
});
// Backbone.Router
// -------------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var namedParam = /:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
Backbone.history || (Backbone.history = new History);
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
callback && callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
var routes = [];
for (var route in this.routes) {
routes.unshift([route, this.routes[route]]);
}
for (var i = 0, l = routes.length; i < l; i++) {
this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(namedParam, '([^\/]+)')
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted parameters.
_extractParameters: function(route, fragment) {
return route.exec(fragment).slice(1);
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on URL fragments. If the
// browser does not support `onhashchange`, falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
};
// Cached regex for cleaning leading hashes and slashes .
var routeStripper = /^[#\/]/;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(windowOverride) {
var loc = windowOverride ? windowOverride.location : window.location;
var match = loc.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = window.location.pathname;
} else {
fragment = this.getHash();
}
}
if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({}, {root: '/'}, this.options, options);
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
if (oldIE && this._wantsHashChange) {
this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).bind('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).bind('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = window.location;
var atRoot = (loc.pathname == this.options.root) && !loc.search;
// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
window.location.replace(this.options.root + window.location.search + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
}
if (!this.options.silent) {
return this.loadUrl();
}
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Backbone.$(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current == this.fragment && this.iframe) current = this.getFragment(this.getHash(this.iframe));
if (current == this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl() || this.loadUrl(this.getHash());
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: options};
var frag = (fragment || '').replace(routeStripper, '');
if (this.fragment == frag) return;
var fullFrag = (frag.indexOf(this.options.root) != 0 ? this.options.root : '') + frag;
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
this.fragment = fullFrag;
window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, fullFrag);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this.fragment = frag;
this._updateHash(window.location, frag, options.replace);
if (this.iframe && (frag != this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a history entry on hash-tag change.
// When replace is true, we don't want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, frag, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return window.location.assign(fullFrag);
}
if (options.trigger) this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
location.replace(location.toString().replace(/(javascript:|#).*$/, '') + '#' + fragment);
} else {
location.hash = fragment;
}
}
});
// Backbone.View
// -------------
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['el', 'id', 'attributes', 'className', 'tagName'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be prefered to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view from the DOM. Note that the view isn't present in the
// DOM by default, so calling this method may be a no-op.
remove: function() {
this.$el.remove();
return this;
},
// For small amounts of DOM Elements, where a full-blown template isn't
// needed, use **make** to manufacture elements, one at a time.
//
// var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
//
make: function(tagName, attributes, content) {
var el = document.createElement(tagName);
if (attributes) Backbone.$(el).attr(attributes);
if (content != null) Backbone.$(el).html(content);
return el;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save'
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = getValue(this, 'events')))) return;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) throw new Error('Method "' + events[key] + '" does not exist');
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.bind(eventName, method);
} else {
this.$el.delegate(selector, eventName, method);
}
}
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.unbind('.delegateEvents' + this.cid);
},
// Performs the initial configuration of a View with a set of options.
// Keys with special meaning *(model, collection, id, className)*, are
// attached directly to the view.
_configure: function(options) {
if (this.options) options = _.extend({}, this.options, options);
for (attr in options) {
if ((options[attr] instanceof Backbone.Collection) ||
(options[attr] instanceof Backbone.Model) || _.include(viewOptions, attr)) {
this[attr] = options[attr];
};
}
this.options = options;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, getValue(this, 'attributes'));
if (this.id) attrs.id = this.id;
if (this.className) attrs['class'] = this.className;
this.setElement(this.make(getValue(this, 'tagName'), attrs), false);
} else {
this.setElement(this.el, false);
}
}
});
// The self-propagating extend function that Backbone classes use.
var extend = function(protoProps, classProps) {
var child = inherits(this, protoProps, classProps);
child.extend = this.extend;
return child;
};
// Set up inheritance for the model, collection, and view.
Model.extend = Collection.extend = Router.extend = View.extend = extend;
// Backbone.sync
// -------------
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
options || (options = {});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = getValue(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model);
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
// Make the request, allowing the user to override any Ajax options.
return Backbone.ajax(_.extend(params, options));
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Wrap an optional error callback with a fallback error event.
Backbone.wrapError = function(onError, originalModel, options) {
return function(model, resp) {
resp = model === originalModel ? resp : model;
if (onError) {
onError(originalModel, resp, options);
} else {
originalModel.trigger('error', originalModel, resp, options);
}
};
};
// Helpers
// -------
// Shared empty constructor function to aid in prototype-chain creation.
var ctor = function(){};
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var inherits = function(parent, protoProps, staticProps) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ parent.apply(this, arguments); };
}
// Inherit class (static) properties from parent.
_.extend(child, parent);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Add static properties to the constructor function, if supplied.
if (staticProps) _.extend(child, staticProps);
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
};
// Helper function to get a value from a Backbone object as a property
// or as a function.
var getValue = function(object, prop) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
}).call(this);
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['mk_MK'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N",
"country_name": "\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0438\u0458\u0430",
"country_post": "MK",
"country_ab2": "MK",
"country_ab3": "MKD",
"country_num": 807,
"country_car": "MK",
"country_isbn": "9989",
"lang_name": "\u043c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438",
"lang_ab": "mk",
"lang_term": "mkd",
"lang_lib": "mac"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1yY\u0414\u0434dD]",
"noexpr": "^[-0nN\u041d\u043d]",
"yesstr": "\u0434\u0430",
"nostr": "\u043d\u0435"
},
"LC_MONETARY": {
"currency_symbol": "\u0434\u0435\u043d",
"mon_decimal_point": ",",
"mon_thousands_sep": "\u202f",
"mon_grouping": [
3,
3
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 0,
"p_sep_by_space": 1,
"n_cs_precedes": 0,
"n_sep_by_space": 1,
"p_sign_posn": 1,
"n_sign_posn": 1,
"int_curr_symbol": "MKD ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%g%t%f",
"name_gen": "\u043f\u043e\u0447\u0438\u0442\u0443\u0432\u0430\u043d",
"name_mr": "\u0433-\u0434\u0438\u043d",
"name_mrs": "\u0433-\u0453\u0430",
"name_miss": "\u0433-\u0453\u0438\u0446\u0430",
"name_ms": "\u0433-\u0453\u0430"
},
"LC_NUMERIC": {
"decimal_point": ",",
"thousands_sep": "\u202f",
"grouping": [
3,
3
]
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": "+%c %a %l",
"tel_dom_fmt": "%A %l",
"int_select": "00",
"int_prefix": "389"
},
"LC_TIME": {
"date_fmt": "%a, %d %b %H:%M:%S %Z %Y",
"abday": [
"\u043d\u0435\u0434",
"\u043f\u043e\u043d",
"\u0432\u0442\u043e",
"\u0441\u0440\u0435",
"\u0447\u0435\u0442",
"\u043f\u0435\u0442",
"\u0441\u0430\u0431"
],
"day": [
"\u043d\u0435\u0434\u0435\u043b\u0430",
"\u043f\u043e\u043d\u0435\u0434\u0435\u043b\u043d\u0438\u043a",
"\u0432\u0442\u043e\u0440\u043d\u0438\u043a",
"\u0441\u0440\u0435\u0434\u0430",
"\u0447\u0435\u0442\u0432\u0440\u0442\u043e\u043a",
"\u043f\u0435\u0442\u043e\u043a",
"\u0441\u0430\u0431\u043e\u0442\u0430"
],
"week": [
7,
19971130,
1
],
"abmon": [
"\u0458\u0430\u043d",
"\u0444\u0435\u0432",
"\u043c\u0430\u0440",
"\u0430\u043f\u0440",
"\u043c\u0430\u0458",
"\u0458\u0443\u043d",
"\u0458\u0443\u043b",
"\u0430\u0432\u0433",
"\u0441\u0435\u043f",
"\u043e\u043a\u0442",
"\u043d\u043e\u0435",
"\u0434\u0435\u043a"
],
"mon": [
"\u0458\u0430\u043d\u0443\u0430\u0440\u0438",
"\u0444\u0435\u0432\u0440\u0443\u0430\u0440\u0438",
"\u043c\u0430\u0440\u0442",
"\u0430\u043f\u0440\u0438\u043b",
"\u043c\u0430\u0458",
"\u0458\u0443\u043d\u0438",
"\u0458\u0443\u043b\u0438",
"\u0430\u0432\u0433\u0443\u0441\u0442",
"\u0441\u0435\u043f\u0442\u0435\u043c\u0432\u0440\u0438",
"\u043e\u043a\u0442\u043e\u043c\u0432\u0440\u0438",
"\u043d\u043e\u0435\u043c\u0432\u0440\u0438",
"\u0434\u0435\u043a\u0435\u043c\u0432\u0440\u0438"
],
"d_t_fmt": "%a, %d %b %Y %T %Z",
"d_fmt": "%d.%m.%Y",
"t_fmt": "%T",
"am_pm": [
"",
""
],
"t_fmt_ampm": "",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": 2,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
|
import React from 'react';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
export default class FormDialog extends React.Component {
state = {
open: false,
};
handleClickOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
return (
<div>
<Button variant="outlined" color="primary" onClick={this.handleClickOpen}>
Open form dialog
</Button>
<Dialog
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">Subscribe</DialogTitle>
<DialogContent>
<DialogContentText>
To subscribe to this website, please enter your email address here. We will send
updates occasionally.
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="name"
label="Email Address"
type="email"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Cancel
</Button>
<Button onClick={this.handleClose} color="primary">
Subscribe
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
|
var mongoose = require('mongoose');
var Caja = mongoose.model('Caja');
var Proveedor = mongoose.model('Proveedor');
var MontoCategoria = mongoose.model('MontoCategoria');
var Schema = mongoose.Schema;
var detalleSchema = new Schema({
creado: {
type: Date,
default: Date.now
},
valor: {
type: Number,
required: 'Ingrese el valor del Detalle'
},
categoria: {
type: String,
required: 'Elija una Categoria'
},
entregado: {
type: String,
required: 'Llene el campo Entregado'
},
cargado: {
type: String,
required: 'Elija una Sucursal'
},
fecha: {
type: Date,
required: 'Eija una fecha'
},
descripcion: {
type: String,
required: 'Por favor, ingrese una descripción'
},
caja: {
type: Schema.ObjectId,
ref: "Caja"
},
creador: {
type: Schema.ObjectId,
ref: "Usuario",
required: "Se necesita el id del Usuario"
},
administrador:{
type: Schema.ObjectId,
ref: "Usuario"
},
tipo: {
type: String,
enum: ['factura', 'vale']
},
destinadoA: {
type: String
},
anexo: {
proveedor: {
nombre: {
type: String
},
apellido: {
type: String
},
ruc: {
type: String
},
cedula: {
type: String
},
razons: {
type: String
}
},
factura: String,
fac_establecimiento: String,
fac_puntoEmision: String,
fac_secuencia: String,
fac_autorizacion: String,
retencion: {
type: Boolean,
default: false
},
ret_establecimiento: String,
ret_puntoEmision: String,
ret_secuencia: String,
ret_autorizacion: String,
subTotal0: {
type: Number,
default: 0
},
subTotalIva: {
type: Number,
default: 0
},
selectRetencion: String,
retencionIVABienes: Number,//30%
retencionSubTotalBienes: Number,
retencionIVAServicios: Number,//70%
retencionSubTotalServicios: Number,
retencionIVAcien: Number,
retencionSubTotalOcho: Number,
totalRetencion: Number,
iva: Number,
tasasYPropinas: Number,
total: Number
},
estado: {
type: String,
enum: ['Borrador','Pendiente','Aprobado', 'Rechazado'],
default: 'Borrador',
required: true
}
});
mongoose.model('Detalle', detalleSchema);
|
var thinkjs = require('thinkjs');
var path = require('path');
var rootPath = path.dirname(__dirname);
var VIEW_PATH = rootPath + '/view';
require("babel-core/register")(think.extend({
only: VIEW_PATH,
}, {
"presets": [
["es2015", {
"loose": true
}],
"stage-1",
"react"
],
"plugins": [
"transform-runtime",
/*["webpack-alias", {
"config": __dirname + "/webpack.config.js"
}]*/
]
}));
var instance = new thinkjs({
APP_PATH: rootPath + path.sep + 'app',
RUNTIME_PATH: rootPath + path.sep + 'runtime',
ROOT_PATH: rootPath,
RESOURCE_PATH: __dirname,
env: 'development'
});
// Build code from src to app directory.
instance.compile({
log: true,
presets: [],
plugins: []
});
// 监听view变化
var viewReloadInstance = instance.getReloadInstance(VIEW_PATH);
viewReloadInstance.run();
instance.run();
|
// Meteor Shower by Roy Curtis
// Licensed under MIT, 2015
'use strict';
// ## Global references
var fastRandom = goo.MathUtils.fastRandom;
// ## Constants
var MAX_METEORS = 6;
// ## Global state
var world = null;
var master = null;
var meteors = [];
var nextSpawn = 0;
// ## Utility methods
function spawnNewMeteor()
{
var meteor = goo.EntityUtils.clone(world, master,
{
shareMeshData : true,
shareMaterials : true,
shareUniforms : true,
shareTextures : true
});
meteor.setTranslation([10, 10, 10]);
meteor.motion = new goo.Vector3();
meteor.skip = true;
meteor.addToWorld();
meteors.push(meteor);
}
function respawnMeteor(meteor)
{
var position = meteor.getTranslation();
var motion = meteor.motion;
// X range from -1.5 to 8
position.x = (fastRandom() * 9.5) - 1.5;
// Y range from 2.5 to 4
position.y = (fastRandom() * 1.5) + 2.5;
// Z can either be behind, on horizon or in front of planet
var zChance = fastRandom() * 90;
if (zChance < 30) position.z = -1;
else if (zChance < 60) position.z = 0.25;
else position.z = 4;
var scaleMag = (fastRandom() * 0.5) + 0.5;
meteor.setScale( [scaleMag, scaleMag, 0] );
var motionMag = (fastRandom() * 0.1) + 0.1;
meteor.motion.x = -motionMag;
meteor.motion.y = -motionMag;
meteor.skip = false;
}
// ### Goo methods
var setup = function (args, ctx)
{
world = ctx.world;
// Hold reference to master meteor
master = args.entity;
master.removeFromWorld();
// Pregenerate all meteors
for (var i = 0; i < MAX_METEORS; i++)
spawnNewMeteor();
};
var cleanup = function (args, ctx)
{
// Destroy and dereference all meteors
meteors = meteors.filter(function(meteor)
{
meteor.removeFromWorld();
return false;
});
};
var update = function (args, ctx)
{
nextSpawn--;
if (nextSpawn < 0)
{
for (var i = 0; i < MAX_METEORS; i++)
if (meteors[i].skip)
{
respawnMeteor(meteors[i]);
break;
}
// Next spawn range from 10 to 20 ticks
nextSpawn = (fastRandom() * 10) + 10;
}
meteors.forEach(function(meteor)
{
if (meteor.skip) return;
var pos = meteor
.addTranslation(meteor.motion)
.getTranslation();
if (pos.x < -7 || pos.y < -4)
meteor.skip = true;
});
};
// ## Goo parameters
var parameters = [
{
name: "Entity",
key: "entity",
description: "Entity to spawn and shower",
type: "entity"
}
]; |
$(function() {
// Model
// 取得する作品情報
var WorkModel = Backbone.Model.extend({
url : 'work/',
initialize : function initialize() { // インスタンス生成時に実行される
this.url += this.get('id');
/* console.log(this.get('name')); */
}
}),
// Collection
WorkCollection = Backbone.Collection.extend({
model : WorkModel, // このCollectionのBackbone.Modelを指定
url : undefined,// 取得するJSONのURL.httpから始まってもOK
urlRoot : 'api/searchwork?',
//urlRoot : 'data/work.json?'
}),
// viewのテンプレート作成
FormView = Backbone.View
.extend({
events : {
'submit' : 'onSubmit'
},
el : '#searchworkform',
getParam : location.search.substr(1),// GETパラメータを取得.最初の?は元のURLに含まれているので削除
initialize : function(options) {
/* console.log('init Form View'); */
_.bindAll(this, 'render', 'onSubmit', 'sendData');
this.render();
this.sendData();
},
render : function() {
/* console.log('display Form'); */
var hash, hashes = this.getParam.split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash[1] != '') {
this.$el.find('input[name="' + hash[0] + '"]').val(
decodeURI(hash[1]));
}
}
},
onSubmit : function() {
this.getParam = this.$el.serialize();
this.sendData();
return false;
},
sendData : function() {
// GETパラメーターを取得URLに追加
this.collection.url = this.collection.urlRoot
+ this.getParam;
// (collectionのurlにGETリクエストを送信する)
this.collection.fetch({
success : function success(collection, res, options) {
// NOP
},
error : function error() {
$('#work-list').html('<h1 class="page-header">作品検索結果</h1><p class="alert alert-danger">検索内容に合致する結果はありませんでした.</p>');
}
});
}
}), ListView = Backbone.View.extend({
el : '#work-list',
template : undefined,
initialize : function(options) {
/* console.log('initialize List view'); */
this.template = _.template($("#work-list-template").text());
_.bindAll(this, 'render');
this.listenTo(this.collection, 'sync', this.render);// collectionがsyncされたらrenderメソッドを呼び出すよう監視
},
render : function() {
this.$el.find('#work-list-content').hide('slow');
this.$el.find('#work-list-content').html('');
this.collection.each(function(value) {
var data = {
"name" : value.get('name'),
"comment" : value.get('comment'),
"url" : value.url,
"img" : value.get("img"),
"place" : value.get("place"),
};
thisListView.$("#work-list-content").append(
thisListView.template(data));
});
this.$el.find('#work-list-content').show('slow');
/* console.log('display List'); */
}
}), thisWorkCollection = undefined, thisFormView = undefined, thisListView = undefined;
// collectionクラスのインスタンス作成(初期処理)
thisWorkCollection = new WorkCollection();
// viewクラスのインスタンス作成(初期処理)
thisListView = new ListView({
collection : thisWorkCollection
});
thisFormView = new FormView({
collection : thisWorkCollection
});
}); |
/* exported EffectsManager */
function EffectsManager() {
this.effectElements = [];
}
|
/**
* A JavaScript project for accessing the accelerometer and gyro from various devices
*
* @author Tom Gallacher <tom.gallacher23@gmail.com>
* @copyright Tom Gallacher <http://www.tomg.co>
* @version 0.0.1a
* @license MIT License
* @options frequency, callback
*/
(function() {
var measurements = {
x: null,
y: null,
z: null,
alpha: null,
beta: null,
gamma: null
},
calibration = {
x: 0,
y: 0,
z: 0,
alpha: 0,
beta: 0,
gamma: 0
},
interval = null,
features = [];
window.gyro = {};
/**
* @public
*/
gyro.frequency = 500; //ms
gyro.calibrate = function() {
for (var i in measurements) {
calibration[i] = (typeof measurements[i] === 'number') ? measurements[i] : 0;
}
};
gyro.getOrientation = function() {
return measurements;
};
gyro.startTracking = function(callback) {
interval = setInterval(function() {
callback(measurements);
}, gyro.frequency);
};
gyro.stopTracking = function() {
clearInterval(interval);
};
/**
* Current available features are:
* MozOrientation
* devicemotion
* deviceorientation
*/
gyro.hasFeature = function(feature) {
for (var i in features) {
if (feature == features[i]) {
return true;
}
}
return false;
};
gyro.getFeatures = function() {
return features;
};
/**
* @private
*/
function setupListeners() {
window.addEventListener('MozOrientation', function(e) {
features.push('MozOrientation');
measurements.x = e.x - calibration.x;
measurements.y = e.y - calibration.y;
measurements.z = e.z - calibration.z;
}, true);
window.addEventListener('devicemotion', function(e) {
features.push('devicemotion');
measurements.x = e.accelerationIncludingGravity.x - calibration.x;
measurements.y = e.accelerationIncludingGravity.y - calibration.y;
measurements.z = e.accelerationIncludingGravity.z - calibration.z;
}, true);
window.addEventListener('deviceorientation', function(e) {
features.push('deviceorientation');
measurements.alpha = e.alpha - calibration.alpha;
measurements.beta = e.beta - calibration.beta;
measurements.gamma = e.gamma - calibration.gamma;
}, true);
}
setupListeners();
})(window); |
$(document).ready(function() {
var id_select;
$.ajax({
url: "/api/list_dives"
}).then(function(data) {
//console.log(data);
localStorage.setItem("dives", JSON.stringify(data));
data.rows.forEach(function(doc) {
//console.log(doc.id);
var date = doc.doc.StartTime + '';
var date2 = date.split("T")[0];
$(".list").append('<li class="nav-item" id="'+doc.id+'"><a href="#"> '+date2+'</a></li>');
});
});
$(document).on("click", ".nav-item", function () {
$("#curve_chart").show();;
var val1 = jQuery(this).attr("id");
var details = JSON.parse(localStorage.getItem("dives"))
console.log(details);
details.rows.forEach(function(doc) {
var val2 = doc.id;
//console.log (val1 + " " + val2);
if (val1 == val2)
{
id_select = val2;
//console.log("OK");
//console.log(doc.doc.club);
var duration = doc.doc.Duration/60;
$('.display-dive-time').html(duration.toFixed(2) + "min");
$('.display-max-depth').html(doc.doc.MaxDepth + "m");
$('.display-avg-depth').html(doc.doc.AvgDepth + "m");
$('.club').html(doc.doc.club);
$('.display-latitude').html(doc.doc.latitude );
$('.display-longitude').html(doc.doc.longitude );
var dive_detail = doc.doc.samples[0]["Dive.Sample"];
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data_dives = new google.visualization.DataTable();
data_dives.addColumn('number', 'Time');
data_dives.addColumn('number', 'Depth');
//data_dives.addColumn('number', 'Temperature');
data_dives.addColumn('number', 'Pressure');
for(var i in dive_detail)
{
var Temperature = dive_detail[i].Temperature;
var Pressure = dive_detail[i].Pressure;
var Depth = - dive_detail[i].Depth; // to put the chart in the right way
var Time = dive_detail[i].Time;
myTemp = parseFloat($.trim(Temperature));
myDepth = parseFloat($.trim(Depth));
myPressure = parseFloat($.trim(Pressure)) / 1000;
myTime = parseFloat($.trim(Time)) / 60;
//data_dives.addRow([{v: myDepth, f: myDepth.toFixed(2)},{v: myTemp, f: myTemp.toFixed(2)},{v: myPressure, f: myPressure.toFixed(2)}]);
data_dives.addRow([{v: myTime, f: myTime.toFixed(2)},{v: myDepth, f: myDepth.toFixed(2)},{v: myPressure, f: myPressure.toFixed(2)}]);
//data_dives.addRow([myTime,{v: myDepth, f: myDepth.toFixed(2)}]);
}
var options = {
title: 'Dive Details',
curveType: 'function',
legend: { position: 'bottom' },
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {axis: 'Depth'},
1: {axis: 'Pressure'}
},
axes: {
x: {
0: {side: 'top'}},
y: {
Depth: {label: 'Depth (meter)'},
Pressure: {label: 'Tank Pressure (bars)'}
}
}
};
var chart = new google.charts.Line(document.getElementById('curve_chart'));
chart.draw(data_dives, options);
}
}
});
});
document.getElementById('container').onclick = function(event) {
var span, input, text;
// Get the event (handle MS difference)
event = event || window.event;
// Get the root element of the event (handle MS difference)
span = event.target || event.srcElement;
// If it's a span...
if (span && span.tagName.toUpperCase() === "SPAN") {
// Hide it
span.style.display = "none";
// Get its text
text = span.innerHTML;
// Create an input
input = document.createElement("input");
input.type = "text";
input.size = Math.max(text.length / 4 * 3, 4);
span.parentNode.insertBefore(input, span);
// Focus it, hook blur to undo
input.focus();
input.onblur = function() {
// Remove the input
span.parentNode.removeChild(input);
// Update the span
span.innerHTML = input.value;
var arr;
if(span.className.indexOf("display-latitude")!=-1) arr = "{\"name\":\""+id_select+"\",\"club\":\"NULL\",\"latitude\":\""+input.value+"\",\"longitude\":\"NULL\",\"divesite\":\"NULL\"}";
if(span.className.indexOf("display-longitude")!=-1) arr = "{\"name\":\""+id_select+"\",\"club\":\"NULL\",\"latitude\":\"12.345\",\"longitude\":\""+input.value+"\",\"divesite\":\"NULL\"}";
if(span.className.indexOf("club")!=-1) arr = "{\"name\":\""+id_select+"\",\"club\":\""+input.value+"\",\"latitude\":\"NULL\",\"longitude\":\"NULL\",\"divesite\":\"NULL\"}";
if(span.className.indexOf("dive-site")!=-1) arr = "{\"name\":\""+id_select+"\",\"club\":\"NULL\",\"latitude\":\"NULL\",\"longitude\":\"NULL\",\"divesite\":\""+input.value+"\"}";
/// AJAX callback
var test = JSON.parse(arr);
var settings = {
url: '/update/dive',
method: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(test)
}
console.log(arr);
$.ajax(settings).done(function (response) {
console.log(response);
});
// Show the span again
span.style.display = "";
};
}
};
});
var refresh_cache = function()
{
console.log("REFRESH");
$.ajax({
url: "/api/list_dives"
}).then(function(data) {
console.log(data);
localStorage.setItem("dives", JSON.stringify(data));
});
}
/*
console.log(doc.doc.AvgDepth);
console.log(doc.doc.Duration);
console.log(doc.doc.MaxDepth);
var duration = doc.doc.Duration/60;
$('.display-dive-time').html(duration.toFixed(2) + "min");
$('.display-max-depth').html(doc.doc.MaxDepth + "m");
$('.display-avg-depth').html(doc.doc.AvgDepth + "m");
*/
|
/*
* Wegas
* http://wegas.albasim.ch
*
* Copyright (c) 2013-2021 School of Management and Engineering Vaud, Comem, MEI
* Licensed under the MIT License
*/
/* global I18n */
/**
* @fileOverview
* @author Cyril Junod <cyril.junod at gmail.com>
*/
YUI.add('wegas-template', function(Y) {
'use strict';
var Micro = Y.Template.Micro, Wegas = Y.Wegas, AbstractTemplate;
/**
* @name Y.Wegas.AbstractTemplate
* @extends Y.Widget
* @borrows Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable
* @class
* @constructor
* @description Display Wegas variables instance (or/and descriptor) under
* specific templates : text, title, box, fraction and valuebox.
* It is also possible to create a custom template.
*/
AbstractTemplate = Y.Base.create(
'wegas-template',
Y.Widget,
[Y.WidgetChild, Wegas.Widget, Wegas.Editable],
{
/*@lends Y.Wegas.AbstractTemplate#*/
syncUI: function() {
Y.log('syncUI()', 'log', 'Wegas.AbstractTemplate');
var template = this.getTemplate(), data = this.computeData();
try {
this.get('contentBox').setHTML(template(data));
} catch (e) {
Y.log(
'Error rendering template: ' + template,
'error',
'Wegas.AbstractTemplate'
);
}
},
bindUI: function() {
this.after(['dataChange', 'variableChange'], this.syncUI);
if (this.get('custom')) {
this.vdUpdateHandler = Wegas.Facade.Instance.after(
'update',
this.syncUI,
this
);
} else {
var instance = this.get("variable.evaluated").getInstance();
if (instance) {
this.vdUpdateHandler = Wegas.Facade.Instance.after(
//'*:updatedInstance',
instance.get("id") + ':updatedInstance',
this.syncUI,
this
);
}
}
},
syncTemplate: function(payload) {
var template = this.get('variable.evaluated');
/*
** Call syncUI() anyway if this is a custom template, i.e. a script with potentially undetectable
** dependencies on the variable being updated.
** Otherwise simply call syncUI() if the IDs of the variables match.
*/
if (
template &&
template.getInstance().get('id') ===
payload.entity.get('id')
) {
this.syncUI();
}
},
getTemplate: function() {
return this.TEMPLATE;
},
computeData: function() {
var data = {},
initialData = Y.merge(this.get('data')),
desc = this.get('variable.evaluated');
if (desc) {
if (desc instanceof Y.Wegas.persistence.VariableInstance) {
if (desc.get("trValue")) {
data.value = this.undefinedToEmpty(I18n.t(desc.get('trValue')));
} else {
data.value = this.undefinedToEmpty(desc.get('value'));
}
desc = Y.Wegas.Facade.Variable.cache.findById(desc.get('parentId'));
} else {
data.value = undefined;
}
/*This behaviour is not even possible since years...
* if (desc instanceof Wegas.persistence.ListDescriptor && desc.get("currentItem")) { // If the widget is a list,
desc = desc.get("currentItem"); // display it with the current list and the current element
}*/
// data.label = this.undefinedToEmpty(desc.getLabel());
if (initialData.label) {
initialData.label = Y.Template.Micro.compile(
initialData.label || ''
)();
}
if (data.value === undefined) {
if (desc.getInstance().get("trValue")) {
data.value = this.undefinedToEmpty(I18n.t(desc.getInstance().get('trValue')));
} else {
data.value = this.undefinedToEmpty(
desc.getInstance().get('value')
);
}
}
data.maxValue = this.undefinedToEmpty(desc.get('maxValue'));
data.minValue = this.undefinedToEmpty(desc.get('minValue'));
data.variable = desc;
}
return Y.mix(initialData, data, false, null, 0, true);
},
getEditorLabel: function() {
var variable;
if (this.get('data.label')) {
return this.get('data.label');
}
variable = this.get('variable.evaluated');
if (variable) {
return variable.getEditorLabel();
}
return null;
},
destructor: function() {
Y.log("DestroyTemplate");
this.vdUpdateHandler && this.vdUpdateHandler.detach();
},
undefinedToEmpty: function(value) {
return Y.Lang.isUndefined(value) ? '' : '' + value;
}
},
{
/*@lends Y.Wegas.AbstractTemplate*/
EDITORNAME: 'Variable template',
ATTRS: {
/**
* The target variable, returned either based on the variableName attribute,
* and if absent by evaluating the expr attribute.
*/
variable: {
type: "object",
getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
view: {
type: 'variableselect',
label: 'Variable'
//classFilter: ["NumberDescriptor"]
}
},
data: {
type: 'object',
properties: {
label: {type: "string"}
},
additionalProperties: {
type: 'string'
},
view: {
type: 'hashlist',
label: 'Options',
required: false,
keyLabel: 'Property'
}
}
}
}
);
Wegas.Template = Y.Base.create(
'wegas-template',
AbstractTemplate,
[],
{
/*@lends Y.Wegas.Template#*/
TEMPLATES: {},
getTemplate: function() {
var template = this.get('custom'),
hashCode = '' + Wegas.Helper.hashCode(template);
if (Y.Lang.isUndefined(this.TEMPLATES[hashCode])) {
this.TEMPLATES[hashCode] = Micro.compile(template || '');
}
return this.TEMPLATES[hashCode];
}
},
{
/*@lends Y.Wegas.Template*/
EDITORNAME: 'Custom template',
ATTRS: {
custom: {
type: 'string',
value: "<%= this.variable.getValue() || 'Undefined' %>",
view: {
label: 'Template',
rows: 3
}
}
}
}
);
Wegas.ValueboxTemplate = Y.Base.create(
'wegas-template',
AbstractTemplate,
[],
{
TEMPLATE: Micro.compile(
"<div class='wegas-template-valuebox'>" +
" <% if(this.label){ %>" +
" <label><%= this.label %></label>" +
" <% } %>" +
" <div class='wegas-template-valuebox-units'>" +
" <% for(var i=+this.minValue; i < +this.maxValue + 1; i+=1){%>" +
" <div data-value=\"<%= i %>\" class='wegas-template-valuebox-unit <%= +i < +this.value ? ' wegas-template-valuebox-previous' : '' %><%= +i === 0 ? ' wegas-template-valuebox-zero' : '' %><%= +i === +this.value ? ' wegas-template-valuebox-selected' : '' %>'>" +
" <span><%= I18n.formatNumber(i) %></span>" +
" </div>" +
" <% } %>" +
" </div>" +
"</div>"
)
},
{
EDITORNAME: "Serie",
ATTRS: {
variable: {
type: "object",
getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
view: {
type: 'variableselect',
label: 'Variable',
classFilter: ["NumberDescriptor"]
}
},
data: {
type: 'object',
properties: {
label: {type: "string", view: {label: "Label"}},
minValue: {
type: "number",
view: {
label: "Minimum value",
description: "Override number's minimum value",
layout: "shortInline"
}
},
maxValue: {
type: "number",
view: {
label: "Maximum value",
description: "Override number's maximum value",
layout: "shortInline"
}
}
},
view: {}
}
}
}
);
Wegas.BoxTemplate = Y.Base.create('wegas-template', AbstractTemplate, [],
{
TEMPLATE: Micro.compile(
"<div class='wegas-template-box'><% if(this.label){ %><label><%= this.label %></label><br/><% } %>"+
"<div class='wegas-template-box-units'>" +
" <% var i;%>" +
"<% var max = (+this.maxValue) || 100;%>" +
"<% var value = (+this.value); %>" +
"<% for(i=0; i < value && i < max - 1; i+=1){ %>" +
" <div class='wegas-template-box-unit <%= 1+i == value ? ' wegas-template-box-selected' : (2+i == value ? ' wegas-template-box-pred' : '') %>' value='<%= 1+i %>'></div>"+
"<% } %></div>" +
" <span class='wegas-template-box-value'>" +
"(<%= I18n.formatNumber(value || '{value}') %>" +
')</span></div>'
)
},
{
EDITORNAME: "Boxes",
ATTRS: {
variable: {
type: "object",
getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
view: {
type: 'variableselect',
label: 'Variable',
classFilter: ["NumberDescriptor"]
}
},
data: {
type: 'object',
properties: {
label: {type: "string", view: {label: "Label"}},
maxValue: {
type: "number",
errored: function(val) {
var errors = [];
if (Y.Lang.isNumber(val) && val < 3) {
errors.push("should be empty or greater than 2");
}
return errors.join(",");
},
view: {
label: "max number of boxes displayed",
description: "",
layout: "shortInline",
placeholder: "100"
}
}
},
view: {}
}
}
});
Wegas.NumberTemplate = Y.Base.create(
'wegas-template',
AbstractTemplate,
[],
{
TEMPLATE: Micro.compile(
"<div class='wegas-template-text'><% if(this.label){ %><span><%= this.label %></span><br/><% } %><span><%= I18n.formatNumber(this.value || '{value}') %></span></div>"
)
},
{
EDITORNAME: "Number Template",
ATTRS: {
variable: {
type: "object",
getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
view: {
type: 'variableselect',
label: 'Variable',
classFilter: ["NumberDescriptor"]
}
},
data: {
type: 'object',
properties: {
label: {type: "string", view: {label: "Label"}}
},
view: {}
}
}
}
);
Wegas.TitleTemplate = Y.Base.create(
'wegas-template',
AbstractTemplate,
[],
{
TEMPLATE: Micro.compile(
"<div class='wegas-template-title'><%= this.label || '{label}'%></div>"
)
},
{
EDITORNAME: "Title Teamplate",
ATTRS: {
data: {
type: 'object',
properties: {
label: {type: "string", view: {label: "Label"}}
},
view: {}
}
}
}
);
Wegas.FractionTemplate = Y.Base.create(
'wegas-template',
AbstractTemplate,
[],
{
TEMPLATE: Micro.compile(
"<div class='wegas-template-fraction'>" +
'<% if(this.label){ %><label><%= this.label %> </label><% } %>' +
//+ "<%= (this.minValue || '{minValue}')%> /"
"<%= I18n.formatNumber(this.value || '{label}') + '/' + I18n.formatNumber(this.maxValue || '{maxValue}') %></div>"
)
},
{
EDITORNAME: "Fraction",
ATTRS: {
variable: {
type: "object",
getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
view: {
type: 'variableselect',
label: 'Variable',
classFilter: ["NumberDescriptor"]
}
},
data: {
type: 'object',
properties: {
label: {type: "string", view: {label: "Label"}},
maxValue: {type: "number", view: {label: "Maximum value", description: "Override number's maximum value"}}
},
view: {}
}
}
}
);
Wegas.TextTemplate = Y.Base.create('wegas-template', AbstractTemplate, [], {
TEMPLATE: Micro.compile('<div><%== I18n.tVar(this.variable) %></div>')
}, {
ATTRS: {
/**
* The target variable, returned either based on the variableName attribute,
* and if absent by evaluating the expr attribute.
*/
variable: {
type: 'object',
getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
view: {
type: 'variableselect',
label: 'Variable',
classFilter: ['TextDescriptor', 'StringDescriptor',
'ListDescriptor', 'StaticTextDescriptor']
}
},
data: {
type: 'object',
properties: {},
view: {}
}
}
});
});
|
/**
* Created by Mitchell Corish on 2015-01-24.
*/
var oldVelocity = 0, acceleration = 0;
// Connect to localhost and start getting frames
Leap.loop({enableGestures: true},
function(frame) {
if (frame.valid) {
if (frame.gestures.length > 0) {
frame.gestures.forEach(function (gesture) {
/*
switch (gesture.type) {
case "circle":
console.log("Circle Gesture");
break;
case "keyTap":
console.log("Key Tap Gesture");
break;
case "screenTap":
console.log("Screen Tap Gesture");
break;
case "swipe":
console.log("Swipe Gesture");
break;
}
*/
});
}
//if (frame.hands.length > 0) {
// var oldVelocity = 0;
// var acceleration = 0;
// var hand = frame.hands[0];
// var nameMap = ["thumb", "index", "middle", "ring", "pinky"];
// frame.pointables.forEach(function (pointable) {
// if (nameMap[pointable.type] === "index" || nameMap[pointable.type] === "thumb") {
// var newVelocity = pointable.tipVelocity;
// console.log(newVelocity);
// acceleration = (oldVelocity - newVelocity)/10;
// oldVelocity = newVelocity;
// console.log(acceleration);
// }
// });
//}
if (frame.tools.length > 0) {
//var tool = frame.tools[0];
frame.tools.forEach(function(tool, i) {
console.log('tool id: ' + i);
var newVelocity = tool.tipVelocity;
//console.log(newVelocity);
acceleration = {
x: (newVelocity.x - oldVelocity.x) / 10,
y: (newVelocity.y - oldVelocity.y) / 10,
z: (newVelocity.z - oldVelocity.z) / 10
};
//acceleration = (newVelocity - oldVelocity) / 10;
oldVelocity = newVelocity;
console.log('acceleration:');
console.log(acceleration);
var dir = tool.direction;
console.log('direction: ');
console.log(dir);
});
}
}
}
);
// Docs: http://leapmotion.github.io/leapjs-plugins/main/transform/
Leap.loopController.use('transform', {
// This matrix flips the x, y, and z axis, scales to meters, and offsets the hands by -8cm.
vr: true,
// This causes the camera's matrix transforms (position, rotation, scale) to be applied to the hands themselves
// The parent of the bones remain the scene, allowing the data to remain in easy-to-work-with world space.
// (As the hands will usually interact with multiple objects in the scene.)
effectiveParent: window.THREE_CAMERA
});
// Docs: http://leapmotion.github.io/leapjs-plugins/main/bone-hand/
Leap.loopController.use('boneHand', {
// If you already have a scene or want to create it yourself, you can pass it in here
// Alternatively, you can pass it in whenever you want by doing
// Leap.loopController.plugins.boneHand.scene = myScene.
scene: window.THREE_SCENE,
// Display the arm
arm: true
});
|
import React from 'react';
import { Bar } from '@vx/shape';
import { Group } from '@vx/group';
import { GradientTealBlue } from '@vx/gradient';
import { letterFrequency } from '@vx/mock-data';
import { scaleBand, scaleLinear } from '@vx/scale';
import { extent, max } from 'd3-array';
const data = letterFrequency.slice(5);
function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
// accessors
const x = d => d.letter;
const y = d => +d.frequency * 100;
export default ({ width, height, events = false }) => {
if (width < 10) return null;
// bounds
const xMax = width;
const yMax = height - 120;
// scales
const xScale = scaleBand({
rangeRound: [0, xMax],
domain: data.map(x),
padding: 0.4,
});
const yScale = scaleLinear({
rangeRound: [yMax, 0],
domain: [0, max(data, y)],
});
return (
<svg width={width} height={height}>
<GradientTealBlue id="teal" />
<rect
x={0}
y={0}
width={width}
height={height}
fill={`url(#teal)`}
rx={14}
/>
<Group top={40}>
{data.map((d, i) => {
const barHeight = yMax - yScale(y(d));
return (
<Group key={`bar-${x(d)}`}>
<Bar
width={xScale.bandwidth()}
height={barHeight}
x={xScale(x(d))}
y={yMax - barHeight}
fill="rgba(23, 233, 217, .5)"
data={{ x: x(d), y: y(d) }}
onClick={data => event => {
if (!events) return;
alert(`clicked: ${JSON.stringify(data)}`);
}}
/>
</Group>
);
})}
</Group>
</svg>
);
};
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//Provides: nproc const
function nproc() {
return 1;
}
|
// Copyright 2002-2015, University of Colorado Boulder
/**
* Main entry point for the sim.
*
* @author Sam Reid
*/
define( function( require ) {
'use strict';
// modules
var MrchompyScreen = require( 'MRCHOMPY/mrchompy/MrchompyScreen' );
var Sim = require( 'JOIST/Sim' );
var SimLauncher = require( 'JOIST/SimLauncher' );
// strings
var simTitle = require( 'string!MRCHOMPY/mrchompy.name' );
var simOptions = {
credits: {
//TODO fill in proper credits, all of these fields are optional, see joist.AboutDialog
leadDesign: '',
softwareDevelopment: '',
team: '',
qualityAssurance: '',
graphicArts: '',
thanks: ''
}
};
// Appending '?dev' to the URL will enable developer-only features.
if ( phet.chipper.getQueryParameter( 'dev' ) ) {
simOptions = _.extend( {
// add dev-specific options here
}, simOptions );
}
SimLauncher.launch( function() {
var sim = new Sim( simTitle, [ new MrchompyScreen() ], simOptions );
sim.start();
} );
} ); |
var shorthandExpand = require('css-shorthand-expand')
module.exports = function (properties) {
properties = properties || this.properties
if (!properties) {
return 0
}
var families = properties['font-family'] || []
if (properties.font) {
families = families.concat(properties.font
.map(function (value) {
try {
return shorthandExpand('font', value)['font-family']
} catch (e) {}
})
.filter(function (value) {
return value
})
)
}
return families
}
|
/*!
* trek - Parsers
* Copyright(c) 2015 Fangdun Cai
* MIT Licensed
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _module2 = require('module');
var _module3 = _interopRequireDefault(_module2);
var _toml = require('toml');
var _toml2 = _interopRequireDefault(_toml);
var _jsYaml = require('js-yaml');
var _jsYaml2 = _interopRequireDefault(_jsYaml);
var _hjson = require('hjson');
var _hjson2 = _interopRequireDefault(_hjson);
var _babel = require('babel');
var babel = _interopRequireWildcard(_babel);
const js = {
parse: function parse() {
var content = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var filename = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
var o = babel.transform(content);
var m = new _module3['default'](filename);
m._compile(o.code, filename);
return m.exports;
}
};
const yml = {
parse: function parse() {
var content = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var filename = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
return _jsYaml2['default'].safeLoad(content);
}
};
/**
* Includes `toml`, `yml`, `json`, `js` Parsers
* @namespace Parsers
*/
exports['default'] = {
toml: _toml2['default'],
yml: yml,
json: _hjson2['default'],
js: js
};
module.exports = exports['default']; |
/**
* <%= description %>
*
* @version 0.0.0
* @requires jQuery
* @author <%= pkg.author && pkg.author.name || pkg.author || '' %>
* @copyright <%= (new Date).getFullYear() %> <%= pkg.author && pkg.author.name || pkg.author || '' %>
* @license MIT
*/
(function(factory) {
if ( typeof define === 'function' && define.amd ) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function($) {
'use strict';
$.fn.<%= method %> = function(opts) {
return this.each(function() {
new <%= className %>(this, opts);
});
}
function <%= className %>(element, opts) {
$.extend(this, {
// Default options
}, opts || {});
}
<%= className %>.prototype = {
// Methods
};
})); |
/**
* @external {Project} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Project
*/
/**
* @external {Schema} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Schema
*/
/**
* @external {Column} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Column
*/
/**
* @external {Changes} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Changes
*/
/**
* @external {Change} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Change
*/
/**
* @external {DataInfo} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-DataInfo
*/
/**
* @external {Item} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-Item
*/
/**
* @external {ValidationResult} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ValidationResult
*/
/**
* @external {ProjectCreateChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ProjectCreateChange
*/
/**
* @external {ProjectTagChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ProjectTagChange
*/
/**
* @external {SchemaCreateChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-SchemaCreateChange
*/
/**
* @external {SchemaRemoveChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-SchemaRemoveChange
*/
/**
* @external {SchemaRenameChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-SchemaRenameChange
*/
/**
* @external {ColumnCreateChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnCreateChange
*/
/**
* @external {ColumnRemoveChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnRemoveChange
*/
/**
* @external {ColumnRenameChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnRenameChange
*/
/**
* @external {ColumnTypechangeChange} https://doc.esdoc.org/github.com/schema-mapper/spec/typedef/index.html#static-typedef-ColumnTypechangeChange
*/
|
// TODO: use https://developer.chrome.com/extensions/tabs#method-executeScript
// chrome.runtime.onMessage.addListener(function(req, sender, sendResponse) {
// sendResponse({
// message: "hello from content script"
// }));
// return true;
// }
// $(".playButton").click();
console.log("This is the content script in soundcloud.com");
$(document).ready(function() {
console.log("done loading");
var firstSongButton = $(".playButton");
console.log(firstSongButton);
});
|
'use strict';
module.exports = {
db: 'mongodb://localhost/surveyapp14-test',
port: 3001,
app: {
title: 'SurveyApp1.4 - Test Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
require('./base-css.js');
require('../css/props-editor.css');
var React = require('react');
var ReactDOM = require('react-dom');
var Dialog = require('./dialog');
var util = require('./util');
var message = require('./message');
var win = require('./win');
var MAX_FILE_SIZE = 1024 * 1024 * 20;
var MAX_NAME_LEN = 128;
var MAX_VALUE_LEN = 64 * 1024;
var MAX_COUNT = 160;
var index = MAX_COUNT;
var W2_HEADER_RE = /^x-whistle-/;
var highlight = function (name) {
return name === 'x-forwarded-for' || W2_HEADER_RE.test(name);
};
var PropsEditor = React.createClass({
getInitialState: function () {
return {};
},
getValue: function (name, field) {
var isHeader = this.props.isHeader;
var allowUploadFile = this.props.allowUploadFile;
var decode = isHeader ? util.decodeURIComponentSafe : util.noop;
var shortName = decode(name.substring(0, MAX_NAME_LEN), isHeader);
var result = { name: shortName };
if (allowUploadFile && field && field.value != null) {
result.value = decode(
util.toString(field.value).substring(0, MAX_VALUE_LEN),
isHeader
);
result.data = field.data;
result.size = field.data && field.data.length;
result.type = field.type;
} else {
result.value = decode(
util.toString(field).substring(0, MAX_VALUE_LEN),
isHeader
);
}
return result;
},
update: function (data) {
var modal = {};
var overflow;
if (data) {
var self = this;
var keys = Object.keys(data);
overflow = keys.length >= MAX_COUNT;
if (overflow) {
keys = keys.slice(0, MAX_COUNT);
}
keys.forEach(function (name) {
var value = data[name];
if (!Array.isArray(value)) {
modal[name + '_0'] = self.getValue(name, value);
return;
}
value.forEach(function (val, i) {
modal[name + '_' + i] = self.getValue(name, val);
});
});
}
this.setState({ modal: modal });
return overflow;
},
onAdd: function () {
if (this.props.disabled) {
return;
}
if (Object.keys(this.state.modal || '').length >= MAX_COUNT) {
return message.error('The number cannot exceed ' + MAX_COUNT + '.');
}
this.setState({ data: '' });
this.showDialog();
},
onEdit: function (e) {
if (this.props.disabled) {
return;
}
var name = e.target.getAttribute('data-name');
var data = this.state.modal[name];
this.setState({ data: data });
this.showDialog(data);
},
edit: function () {
var nameInput = ReactDOM.findDOMNode(this.refs.name);
var name = nameInput.value.trim();
if (!name) {
nameInput.focus();
return message.error('The name cannot be empty.');
}
var valueInput = ReactDOM.findDOMNode(this.refs.valueInput);
var value = valueInput.value.trim();
var state = this.state;
var data = state.data;
var origName = data.name;
data.name = name;
data.data = state.fileData;
if (state.fileData) {
data.size = state.fileSize;
data.value = state.filename;
data.type = state.fileType;
} else {
data.value = value;
}
this.props.onChange(origName, name);
this.setState({
fileData: null,
fileSize: null,
filename: null,
fileType: null
});
this.hideDialog();
nameInput.value = valueInput.value = '';
},
add: function () {
var nameInput = ReactDOM.findDOMNode(this.refs.name);
var name = nameInput.value.trim();
if (!name) {
nameInput.focus();
return message.error('The name cannot be empty.');
}
var valueInput = ReactDOM.findDOMNode(this.refs.valueInput);
var value = valueInput.value.trim();
var modal = this.state.modal;
var state = this.state;
modal[name + '_' + ++index] = state.fileData
? {
name: name,
value: state.filename,
size: state.fileSize,
data: state.fileData,
type: state.fileType
}
: {
name: name,
value: value
};
this.props.onChange(name);
this.setState({
fileData: null,
fileSize: null,
filename: null,
fileType: null
});
this.hideDialog();
nameInput.value = valueInput.value = '';
},
hideDialog: function () {
this.refs.composerDialog.hide();
},
showDialog: function (data) {
this.refs.composerDialog.show();
var nameInput = ReactDOM.findDOMNode(this.refs.name);
if (data) {
nameInput.value = data.name || '';
if (data.data) {
this.setState({
filename: data.value,
fileSize: data.size,
fileData: data.data,
fileType: data.type
});
} else {
ReactDOM.findDOMNode(this.refs.valueInput).value = data.value || '';
}
}
setTimeout(function () {
nameInput.select();
nameInput.focus();
}, 600);
},
onRemove: function (e) {
var self = this;
if (self.props.disabled) {
return;
}
var name = e.target.getAttribute('data-name');
var opName = self.props.isHeader ? 'header' : 'field';
var item = self.state.modal[name];
win.confirm(
'Are you sure to delete this ' + opName + ' \'' + item.name + '\'.',
function (sure) {
if (sure) {
delete self.state.modal[name];
self.props.onChange(item.name);
self.setState({});
}
}
);
},
getFields: function () {
var modal = this.state.modal || '';
return Object.keys(modal).map(function (key) {
return modal[key];
});
},
toString: function () {
var modal = this.state.modal || '';
var keys = Object.keys(modal);
if (this.props.isHeader) {
return keys
.map(function (key) {
var obj = modal[key];
return obj.name + ': ' + util.encodeNonLatin1Char(obj.value);
})
.join('\r\n');
}
return keys
.map(function (key) {
var obj = modal[key];
return (
util.encodeURIComponent(obj.name) +
'=' +
util.encodeURIComponent(obj.value)
);
})
.join('&');
},
onUpload: function () {
if (!this.reading) {
ReactDOM.findDOMNode(this.refs.readLocalFile).click();
}
},
readLocalFile: function () {
var form = new FormData(ReactDOM.findDOMNode(this.refs.readLocalFileForm));
var file = form.get('localFile');
if (file.size > MAX_FILE_SIZE) {
return win.alert('The size of all files cannot exceed 20m.');
}
var modal = this.state.modal || '';
var size = file.size;
Object.keys(modal).forEach(function (key) {
size += modal[key].size;
});
if (size > MAX_FILE_SIZE) {
return win.alert('The size of all files cannot exceed 20m.');
}
var self = this;
self.reading = true;
util.readFile(file, function (data) {
self.reading = false;
self.localFileData = data;
self.setState({
filename: file.name || 'unknown',
fileData: data,
fileSize: file.size,
fileType: file.type
});
});
ReactDOM.findDOMNode(this.refs.readLocalFile).value = '';
},
removeLocalFile: function (e) {
var self = this;
self.setState(
{
filename: null,
fileData: null
},
function () {
var valueInput = ReactDOM.findDOMNode(self.refs.valueInput);
valueInput.select();
valueInput.focus();
}
);
e.stopPropagation();
},
render: function () {
var self = this;
var modal = this.state.modal || '';
var filename = this.state.filename;
var fileSize = this.state.fileSize;
var keys = Object.keys(modal);
var isHeader = this.props.isHeader;
var allowUploadFile = this.props.allowUploadFile;
var data = this.state.data || '';
var btnText = (data ? 'Modify' : 'Add') + (isHeader ? ' header' : ' field');
return (
<div
className={
'fill orient-vertical-box w-props-editor' +
(this.props.hide ? ' hide' : '')
}
title={this.props.title}
onDoubleClick={this.props.onDoubleClick}
>
{keys.length ? (
<table className="table">
<tbody>
{keys.map(function (name) {
var item = modal[name];
return (
<tr key={name}>
<th
className={
isHeader && highlight(item.name) ? 'w-bold' : undefined
}
>
{item.name}
</th>
<td>
<pre>
{item.data ? (
<span className="glyphicon glyphicon-file"></span>
) : undefined}
{item.data
? ' [' + util.getSize(item.size) + '] '
: undefined}
{item.value}
</pre>
</td>
<td className="w-props-ops">
<a
data-name={name}
onClick={self.onEdit}
className="glyphicon glyphicon-edit"
title="Edit"
></a>
<a
data-name={name}
onClick={self.onRemove}
className="glyphicon glyphicon-remove"
title="Delete"
></a>
</td>
</tr>
);
})}
</tbody>
</table>
) : (
<button
onClick={this.onAdd}
className={
'btn btn-primary btn-sm w-add-field' +
(this.props.isHeader ? ' w-add-header' : '')
}
>
{this.props.isHeader ? 'Add header' : 'Add field'}
</button>
)}
<Dialog ref="composerDialog" wstyle="w-composer-dialog">
<div className="modal-body">
<button type="button" className="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
<label>
Name:
<input
ref="name"
placeholder="Input the name"
className="form-control"
maxLength="128"
/>
</label>
<div>
Value:
<div
className={
allowUploadFile
? 'w-props-editor-upload'
: 'w-props-editor-form'
}
>
<div
onClick={this.onUpload}
className={'w-props-editor-file' + (filename ? '' : ' hide')}
title={filename}
>
<button
onClick={this.removeLocalFile}
type="button"
className="close"
title="Remove file"
>
<span aria-hidden="true">×</span>
</button>
<span className="glyphicon glyphicon-file"></span>
{' [' + util.getSize(fileSize) + '] '}
{filename}
</div>
<textarea
ref="valueInput"
maxLength={MAX_VALUE_LEN}
placeholder="Input the value"
className={'form-control' + (filename ? ' hide' : '')}
/>
<button
onClick={this.onUpload}
className={'btn btn-primary' + (filename ? ' hide' : '')}
>
Upload file
</button>
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-primary"
onClick={data ? self.edit : self.add}
>
{btnText}
</button>
<button
type="button"
className="btn btn-default"
data-dismiss="modal"
>
Cancel
</button>
</div>
</Dialog>
<form
ref="readLocalFileForm"
encType="multipart/form-data"
style={{ display: 'none' }}
>
<input
ref="readLocalFile"
onChange={this.readLocalFile}
type="file"
name="localFile"
/>
</form>
</div>
);
}
});
module.exports = PropsEditor;
|
function WebGLExtensions(gl) {
var extensions = {};
return {
get: function (name) {
if (extensions[name] !== undefined) {
return extensions[name];
}
var extension;
switch (name) {
case 'WEBGL_depth_texture':
extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
break;
case 'EXT_texture_filter_anisotropic':
extension = gl.getExtension( 'EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
break;
case 'WEBGL_compressed_texture_s3tc':
extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
break;
case 'WEBGL_compressed_texture_pvrtc':
extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
break;
case 'WEBGL_compressed_texture_etc1':
extension = gl.getExtension('WEBGL_compressed_texture_etc1');
break;
default:
extension = gl.getExtension(name);
}
if (extension === null) {
console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
}
extensions[name] = extension;
return extension;
}
};
}
export { WebGLExtensions };
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../coverage/webfrontauth-ngx'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
var rave = require('./rave');
module.exports = rave; |
import { withRouter } from 'react-router-dom';
import { compose } from 'recompose';
import { connect } from 'react-redux';
export default compose(
withRouter,
connect(state => ({
...state.routing,
})),
);
|
import React , { Component } from 'react';
import {
Navigator ,
View ,
Text,
StyleSheet,
Dimensions,
Image,
TouchableOpacity,
Platform,
Switch
} from 'react-native';
import TabShow from '../components/TabShow';
import Camera from 'react-native-camera';
import moment from 'moment';
import Icon from 'react-native-vector-icons/Ionicons';
import { randomBg } from '../utils';
import connectComponent from '../utils/connectComponent';
import * as QrCodeComponent from './QrCode';
import About from './About';
const QrCode = connectComponent(QrCodeComponent);
class Login extends Component {
constructor (props){
super(props);
this.toAbout = this.toAbout.bind(this);
this.clearCache = this.clearCache.bind(this);
this.logout = this.logout.bind(this);
}
toAbout (){
const { navigator } = this.props;
navigator && navigator.push({
component : About,
sceneConfig : Navigator.SceneConfigs.VerticalUpSwipeJump
})
}
clearCache (){
const { actions } = this.props;
actions.toast('清除成功')
}
logout(){
const { actions } = this.props;
actions.logout();
actions.toast('退出成功')
}
login (){
const { navigator } = this.props;
if(Platform.OS == 'ios'){
Camera.checkDeviceAuthorizationStatus().then( (isAuth) =>{
if(isAuth){
navigator.push({
component : QrCode
})
}else{
actions.toast('请在设置中开启Noder对相机的访问')
}
}).catch( (err) =>{
actions.toast('获取相机访问权错误');
})
}else{
navigator.push({
component : QrCode
})
}
}
renderHeader (){
const {isLogin , User} = this.props;
return (
<View style={[styles.userHeader,{backgroundColor:randomBg()}]}>
<View style={styles.userImgWrap}>
<View style={styles.userImgBox}>
{
User && User.success ?
<Image
style={[styles.userImg]}
source={{uri : User.data.avatar_url}}
defaultSource={require('../public/defaultImg.png')}
/> :
<Image
style={[styles.userImg]}
source={require('../public/defaultImg.png')}
/>
}
</View>
<View style={styles.userName}>
{
User && User.success ?
<Text style={{textAlign:'center',color:textColor,fontSize:16}}>{User.data.loginname}</Text> :
<TouchableOpacity onPress={this.login.bind(this)}>
<Text style={{textAlign:'center',color:textColor,fontSize:16}}>登陆</Text>
</TouchableOpacity>
}
</View>
</View>
{
User && User.success ?
<View style={styles.userInfo}>
<Text style={{textAlign:'center',color:textColor}}>积分:{User.data.score || 0}</Text>
<Text style={{textAlign:'center',color:textColor}}>注册时间:{moment(User.data.create_at).format('l')}</Text>
</View>
:null
}
</View>
)
}
renderOptions (){
const { User } = this.props;
return (
<View>
<TouchableOpacity onPress={this.clearCache.bind(this)}>
<View style={styles.itemOptions}>
<Icon
name='md-trash'
size={ 20 }
color='#333'
/>
<Text style={styles.optionsText}>清除缓存</Text>
</View>
</TouchableOpacity>
<TouchableOpacity>
<View style={styles.itemOptions}>
<Icon
name='md-sync'
size={ 20 }
color='#333'
/>
<Text style={styles.optionsText}>检查更新</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.toAbout}>
<View style={styles.itemOptions}>
<Icon
name='md-key'
size={ 20 }
color='#333'
/>
<Text style={styles.optionsText}>关于</Text>
</View>
</TouchableOpacity>
{
User && User.data ?
<TouchableOpacity
onPress={this.logout}
>
<View style={styles.itemOptions}>
<Icon
name='md-power'
size={ 20 }
color='#333'
/>
<Text style={styles.optionsText}
onPress={this.logout}
>
注销
</Text>
</View>
</TouchableOpacity>
: null
}
</View>
)
}
render (){
const pointContent = (()=>{
return (
<Icon
name='md-arrow-back'
size={ 30 }
color='rgba(255,255,255,1)'
/>
)
})();
return (
<View style={[styles.container]}>
<View>
{this.renderHeader()}
{this.renderOptions()}
</View>
<TabShow {...this.props}
content={pointContent}
wrapStyle={styles.wrapStyle}
/>
</View>
)
}
}
const { width , height } = Dimensions.get('window');
const userImgWidth = 80;
const textColor = '#fff'
const styles = StyleSheet.create({
container : {
flex : 1,
backgroundColor:'#f0f0f0'
},
itemOptions : {
flexDirection : 'row',
height : 50,
borderBottomWidth : 1,
borderTopWidth : 1,
borderColor : '#eee',
alignItems : 'center',
paddingHorizontal : 8,
// paddingVertical : 10
marginTop : 10,
backgroundColor : '#fff'
},
optionsText : {
// lineHeight :40,
fontSize : 15,
paddingHorizontal : 3,
color :'#333',
marginLeft : 5
},
userImgWrap : {
flex : 8,
flexDirection : 'column',
// alignItems : 'center',
justifyContent : 'center'
},
userImgBox :{
paddingTop:20,
flexDirection : 'row',
alignItems : 'center',
justifyContent : 'center'
},
userName : {
flex : 1,
flexDirection : 'row',
justifyContent : 'center',
alignItems : 'center',
},
userInfo : {
flex : 2,
flexDirection : 'row',
alignItems : 'center',
paddingHorizontal : 10,
justifyContent : 'space-between'
},
userHeader : {
height :height/4
},
userImg : {
width : userImgWidth,
height : userImgWidth,
borderRadius : userImgWidth/2
},
wrapStyle : {
flex : 1,
position:'absolute',
left : 20,
bottom : Platform.OS == 'ios' ? 25 : 50,
},
})
export const LayoutComponent = Login;
export function mapStateToProps(state){
return {
User : state && state.User
}
}
|
const AWS = require('aws-sdk');
const getQueue = (sqs, queueUrl) => new Promise((resolve, reject) => {
const queueSettings = {
QueueUrl: queueUrl,
AttributeNames: ['ApproximateNumberOfMessages', 'ApproximateNumberOfMessagesNotVisible']
};
const response = (err, res) => {
if (err) {
reject(err);
}
const queue = {
name: queueUrl,
waiting: res.Attributes.ApproximateNumberOfMessages,
processing: res.Attributes.ApproximateNumberOfMessagesNotVisible
};
resolve(queue);
};
sqs.getQueueAttributes(queueSettings, response);
});
const start = (config, queueUrl) => {
const sqsConfig = Object.assign({}, config);
const sqs = new AWS.SQS(sqsConfig);
return getQueue(sqs, queueUrl);
};
module.exports = (config, queueUrl, cb) => {
start(config, queueUrl).then(res => {
cb(null, res);
}).catch(e => {
cb(e);
});
}; |
JSM.GetArrayBufferFromURL = function (url, callbacks)
{
var request = new XMLHttpRequest ();
request.open ('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function () {
var arrayBuffer = request.response;
if (arrayBuffer && callbacks.onReady) {
callbacks.onReady (arrayBuffer);
}
};
request.onerror = function () {
if (callbacks.onError) {
callbacks.onError ();
}
};
request.send (null);
};
JSM.GetArrayBufferFromFile = function (file, callbacks)
{
var reader = new FileReader ();
reader.onloadend = function (event) {
if (event.target.readyState == FileReader.DONE && callbacks.onReady) {
callbacks.onReady (event.target.result);
}
};
reader.onerror = function () {
if (callbacks.onError) {
callbacks.onError ();
}
};
reader.readAsArrayBuffer (file);
};
JSM.GetStringBufferFromURL = function (url, callbacks)
{
var request = new XMLHttpRequest ();
request.open ('GET', url, true);
request.responseType = 'text';
request.onload = function () {
var stringBuffer = request.response;
if (stringBuffer && callbacks.onReady) {
callbacks.onReady (stringBuffer);
}
};
request.onerror = function () {
if (callbacks.onError) {
callbacks.onError ();
}
};
request.send (null);
};
JSM.GetStringBufferFromFile = function (file, callbacks)
{
var reader = new FileReader ();
reader.onloadend = function (event) {
if (event.target.readyState == FileReader.DONE && callbacks.onReady) {
callbacks.onReady (event.target.result);
}
};
reader.onerror = function () {
if (callbacks.onError) {
callbacks.onError ();
}
};
reader.readAsText (file);
};
JSM.LoadMultipleBuffers = function (inputList, onReady)
{
function LoadMultipleBuffersInternal (inputList, index, result, onReady)
{
if (index >= inputList.length) {
onReady (result);
return;
}
var currentInput = inputList[index];
var loaderFunction = null;
if (currentInput.isFile) {
if (currentInput.isArrayBuffer) {
loaderFunction = JSM.GetArrayBufferFromFile;
} else {
loaderFunction = JSM.GetStringBufferFromFile;
}
} else {
if (currentInput.isArrayBuffer) {
loaderFunction = JSM.GetArrayBufferFromURL;
} else {
loaderFunction = JSM.GetStringBufferFromURL;
}
}
loaderFunction (currentInput.originalObject, {
onReady : function (resultBuffer) {
result.push (resultBuffer);
LoadMultipleBuffersInternal (inputList, index + 1, result, onReady);
},
onError : function () {
result.push (null);
LoadMultipleBuffersInternal (inputList, index + 1, result, onReady);
}
});
}
var result = [];
LoadMultipleBuffersInternal (inputList, 0, result, function (result) {
onReady (result);
});
};
|
// Global variable declarations
var defaultCode;
// Create app
app = require('./index.js');
// ROUTES //
// Derby routes are rendered on the client and the server
// Base '/' route
app.get('/code/:room?', function(page, model, params, next) {
var $code, room = params.room;
if (!(room && /^[a-zA-Z0-9_-]+$/.test(room))) {
return page.redirect('/code/lobby');
}
$code = model.at('code.' + room);
// Subscribe to the code-room model
$code.subscribe(function(err) {
if(err) return next(err);
// Refer to the text as _page.code
model.ref('_page.code', 'code.' + room);
return page.render('code');
});
});
// CONTROLLER FUNCTIONS // |
"use strict";
exports.__esModule = true;
exports.default = void 0;
var Binding = function () {
function Binding(_ref) {
var identifier = _ref.identifier,
scope = _ref.scope,
path = _ref.path,
kind = _ref.kind;
this.identifier = identifier;
this.scope = scope;
this.path = path;
this.kind = kind;
this.constantViolations = [];
this.constant = true;
this.referencePaths = [];
this.referenced = false;
this.references = 0;
this.clearValue();
}
var _proto = Binding.prototype;
_proto.deoptValue = function deoptValue() {
this.clearValue();
this.hasDeoptedValue = true;
};
_proto.setValue = function setValue(value) {
if (this.hasDeoptedValue) return;
this.hasValue = true;
this.value = value;
};
_proto.clearValue = function clearValue() {
this.hasDeoptedValue = false;
this.hasValue = false;
this.value = null;
};
_proto.reassign = function reassign(path) {
this.constant = false;
if (this.constantViolations.indexOf(path) !== -1) {
return;
}
this.constantViolations.push(path);
};
_proto.reference = function reference(path) {
if (this.referencePaths.indexOf(path) !== -1) {
return;
}
this.referenced = true;
this.references++;
this.referencePaths.push(path);
};
_proto.dereference = function dereference() {
this.references--;
this.referenced = !!this.references;
};
return Binding;
}();
exports.default = Binding; |
// file: bwipp/rationalizedCodabar.js
//
// This code was automatically generated from:
// Barcode Writer in Pure PostScript - Version 2015-08-10
//
// Copyright (c) 2011-2015 Mark Warren
// Copyright (c) 2004-2014 Terry Burton
//
// See the LICENSE file in the bwip-js root directory
// for the extended copyright notice.
// BEGIN rationalizedCodabar
if (!BWIPJS.bwipp["raiseerror"] && BWIPJS.increfs("rationalizedCodabar", "raiseerror")) {
BWIPJS.load("bwipp/raiseerror.js");
}
if (!BWIPJS.bwipp["renlinear"] && BWIPJS.increfs("rationalizedCodabar", "renlinear")) {
BWIPJS.load("bwipp/renlinear.js");
}
BWIPJS.bwipp["rationalizedCodabar"]=function() {
function $f0(){
return -1;
}
function $f1(){
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f2(){
this.stk[this.ptr++]=true;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f3(){
var a=/^\s*([^\s]+)(\s+.*)?$/.exec(this.stk[this.ptr-1]);
if (a) {
this.stk[this.ptr-1]=BWIPJS.psstring(a[2]===undefined?"":a[2]);
this.stk[this.ptr++]=BWIPJS.psstring(a[1]);
this.stk[this.ptr++]=true;
} else {
this.stk[this.ptr-1]=false;
}
this.stk[this.ptr++]=false;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f0;
var t0=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t0.call(this)==-1) return -1;
}
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr-1]=BWIPJS.psstring(this.stk[this.ptr-1]);
var t=this.stk[this.ptr-2].toString();
this.stk[this.ptr-1].assign(0,t);
this.stk[this.ptr-2]=this.stk[this.ptr-1].subset(0,t.length);
this.ptr--;
this.stk[this.ptr++]=BWIPJS.psstring("=");
var h=this.stk[this.ptr-2];
var t=h.indexOf(this.stk[this.ptr-1]);
if (t==-1) {
this.stk[this.ptr-1]=false;
} else {
this.stk[this.ptr-2]=h.subset(t+this.stk[this.ptr-1].length);
this.stk[this.ptr-1]=h.subset(t,this.stk[this.ptr-1].length);
this.stk[this.ptr++]=h.subset(0,t);
this.stk[this.ptr++]=true;
}
this.stk[this.ptr++]=true;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f1;
this.stk[this.ptr++]=$f2;
var t1=this.stk[--this.ptr];
var t2=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t2.call(this)==-1) return -1;
} else {
if (t1.call(this)==-1) return -1;
}
}
function $f4(){
this.stk[this.ptr++]=1;
this.stk[this.ptr-1]={};
this.dict=this.stk[--this.ptr]; this.dstk.push(this.dict);
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f3;
var t3=this.stk[--this.ptr];
while (true) {
if (t3.call(this)==-1) break;
}
this.stk[this.ptr++]=this.dict;
this.dstk.pop(); this.dict=this.dstk[this.dstk.length-1];
this.stk[this.ptr++]="options";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f5(){
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f6(){
this.stk[this.ptr++]="barchars";
this.stk[this.ptr++]=BWIPJS.psstring("0123456789-$:/.+TN*E");
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f7(){
this.stk[this.ptr++]="barchars";
this.stk[this.ptr++]=BWIPJS.psstring("0123456789-$:/.+ABCD");
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f8(){
var t=this.dstk.get("charvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("barchars");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f9(){
var t=this.dstk.get("bodyvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("barchars");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f10(){
var t=this.dstk.get("ssvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("barchars");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f11(){
this.stk[this.ptr++]="bwipp.rationalizedCodabarBadAltStartStop";
this.stk[this.ptr++]=BWIPJS.psstring("Codabar start and stop characters must be one of E N T or *");
var t=this.dstk.get("raiseerror");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
}
function $f12(){
this.stk[this.ptr++]="bwipp.rationalizedCodabarBadStartStop";
this.stk[this.ptr++]=BWIPJS.psstring("Codabar start and stop characters must be one of A B C or D");
var t=this.dstk.get("raiseerror");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
}
function $f13(){
var t=this.dstk.get("altstartstop");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f11;
this.stk[this.ptr++]=$f12;
var t25=this.stk[--this.ptr];
var t26=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t26.call(this)==-1) return -1;
} else {
if (t25.call(this)==-1) return -1;
}
}
function $f14(){
this.stk[this.ptr++]="bwipp.rationalizedCodabarBadCharacter";
this.stk[this.ptr++]=BWIPJS.psstring("Codabar body must contain only digits and symbols - $ : / . +");
var t=this.dstk.get("raiseerror");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
}
function $f15(){
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("bodyvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1]]!==undefined; this.ptr--;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-1]=!this.stk[this.ptr-1];
else this.stk[this.ptr-1]=~this.stk[this.ptr-1];
this.stk[this.ptr++]=$f14;
var t28=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t28.call(this)==-1) return -1;
}
}
function $f16(){
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
}
function $f17(){
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("charvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.dstk.get("checksum");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]="checksum";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f18(){
this.stk[this.ptr++]="bwipp.rationalizedCodabarBadCheckDigit";
this.stk[this.ptr++]=BWIPJS.psstring("Incorrect Codabar check digit provided");
var t=this.dstk.get("raiseerror");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
}
function $f19(){
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.dstk.get("barchars");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("checksum");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()!=this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]!=this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f18;
var t40=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t40.call(this)==-1) return -1;
}
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=BWIPJS.psstring(this.stk[this.ptr-1]);
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr++]=0;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=0;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
this.stk[this.ptr++]="barcode";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="includecheck";
this.stk[this.ptr++]=true;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f20(){
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
}
function $f21(){
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
}
function $f22(){
this.stk[this.ptr++]="xpos";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("enc");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=48;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("xpos");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f23(){
this.stk[this.ptr++]="i";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="indx";
var t=this.dstk.get("charvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="enc";
var t=this.dstk.get("encs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("indx");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=8;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("enc");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("xpos");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textyoffset");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textfont");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textsize");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=7;
this.stk[this.ptr++]=$f22;
var t48=this.stk[--this.ptr];
var t46=this.stk[--this.ptr];
var t45=this.stk[--this.ptr];
var t44=this.stk[--this.ptr];
for (var t47=t44; t45<0 ? t47>=t46 : t47<=t46; t47+=t45) {
this.stk[this.ptr++]=t47;
if (t48.call(this)==-1) break;
}
}
function $f24(){
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("barchars");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("checksum");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("xpos");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textyoffset");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textfont");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textsize");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f25(){
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=Infinity;
this.stk[this.ptr++]=BWIPJS.psstring(" ");
var t=this.dstk.get("xpos");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textyoffset");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textfont");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textsize");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f26(){
this.stk[this.ptr++]="xpos";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("encs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("checksum");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=48;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("xpos");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f27(){
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=8;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=8;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("encs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("checksum");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
var t=this.dstk.get("includecheckintext");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f24;
this.stk[this.ptr++]=$f25;
var t54=this.stk[--this.ptr];
var t55=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t55.call(this)==-1) return -1;
} else {
if (t54.call(this)==-1) return -1;
}
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=7;
this.stk[this.ptr++]=$f26;
var t60=this.stk[--this.ptr];
var t58=this.stk[--this.ptr];
var t57=this.stk[--this.ptr];
var t56=this.stk[--this.ptr];
for (var t59=t56; t57<0 ? t59>=t58 : t59<=t58; t59+=t57) {
this.stk[this.ptr++]=t59;
if (t60.call(this)==-1) break;
}
this.stk[this.ptr++]="indx";
var t=this.dstk.get("charvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="enc";
var t=this.dstk.get("encs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("indx");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=8;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("enc");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("xpos");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textyoffset");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textfont");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textsize");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f28(){
this.stk[this.ptr++]="indx";
var t=this.dstk.get("charvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="enc";
var t=this.dstk.get("encs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("indx");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=8;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=8;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("enc");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("xpos");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textyoffset");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textfont");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("textsize");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f29(){
this.stk[this.ptr++]=48;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
}
function $f30(){
var t=this.dstk.get("height");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
}
function $f31(){
this.stk[this.ptr++]=0;
}
function $f32(){
this.stk[this.ptr++]="txt";
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
}
this.stk[this.ptr++]=20;
this.stk[this.ptr-1]={};
this.dict=this.stk[--this.ptr]; this.dstk.push(this.dict);
this.stk[this.ptr++]="options";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="barcode";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="dontdraw";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="altstartstop";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="includecheck";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="validatecheck";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="includetext";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="includecheckintext";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="textfont";
this.stk[this.ptr++]="Courier";
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="textsize";
this.stk[this.ptr++]=10;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="textyoffset";
this.stk[this.ptr++]=-8.5;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="height";
this.stk[this.ptr++]=1;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr++]="stringtype";
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f4;
var t4=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t4.call(this)==-1) return -1;
}
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f5;
var t7=this.stk[--this.ptr];
var t6=this.stk[--this.ptr];
for (t5 in t6) {
if (t6 instanceof BWIPJS.psstring || t6 instanceof BWIPJS.psarray) {
if (t5.charCodeAt(0) > 57) continue;
this.stk[this.ptr++]=t6.get(t5);
} else {
this.stk[this.ptr++]=t5;
this.stk[this.ptr++]=t6[t5];
}
if (t7.call(this)==-1) break;
}
this.stk[this.ptr++]="textfont";
var t=this.dstk.get("textfont");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="textsize";
var t=this.dstk.get("textsize");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=parseFloat(this.stk[this.ptr-1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="textyoffset";
var t=this.dstk.get("textyoffset");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=parseFloat(this.stk[this.ptr-1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="height";
var t=this.dstk.get("height");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=parseFloat(this.stk[this.ptr-1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="encs";
this.stk[this.ptr++]=BWIPJS.psarray([BWIPJS.psstring("11111331"),BWIPJS.psstring("11113311"),BWIPJS.psstring("11131131"),BWIPJS.psstring("33111111"),BWIPJS.psstring("11311311"),BWIPJS.psstring("31111311"),BWIPJS.psstring("13111131"),BWIPJS.psstring("13113111"),BWIPJS.psstring("13311111"),BWIPJS.psstring("31131111"),BWIPJS.psstring("11133111"),BWIPJS.psstring("11331111"),BWIPJS.psstring("31113131"),BWIPJS.psstring("31311131"),BWIPJS.psstring("31313111"),BWIPJS.psstring("11313131"),BWIPJS.psstring("11331311"),BWIPJS.psstring("13131131"),BWIPJS.psstring("11131331"),BWIPJS.psstring("11133311")]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("altstartstop");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f6;
this.stk[this.ptr++]=$f7;
var t8=this.stk[--this.ptr];
var t9=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t9.call(this)==-1) return -1;
} else {
if (t8.call(this)==-1) return -1;
}
this.stk[this.ptr++]="charvals";
this.stk[this.ptr++]=20;
this.stk[this.ptr-1]={};
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=19;
this.stk[this.ptr++]=$f8;
var t14=this.stk[--this.ptr];
var t12=this.stk[--this.ptr];
var t11=this.stk[--this.ptr];
var t10=this.stk[--this.ptr];
for (var t13=t10; t11<0 ? t13>=t12 : t13<=t12; t13+=t11) {
this.stk[this.ptr++]=t13;
if (t14.call(this)==-1) break;
}
this.stk[this.ptr++]="bodyvals";
this.stk[this.ptr++]=16;
this.stk[this.ptr-1]={};
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=15;
this.stk[this.ptr++]=$f9;
var t19=this.stk[--this.ptr];
var t17=this.stk[--this.ptr];
var t16=this.stk[--this.ptr];
var t15=this.stk[--this.ptr];
for (var t18=t15; t16<0 ? t18>=t17 : t18<=t17; t18+=t16) {
this.stk[this.ptr++]=t18;
if (t19.call(this)==-1) break;
}
this.stk[this.ptr++]="ssvals";
this.stk[this.ptr++]=4;
this.stk[this.ptr-1]={};
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=16;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=19;
this.stk[this.ptr++]=$f10;
var t24=this.stk[--this.ptr];
var t22=this.stk[--this.ptr];
var t21=this.stk[--this.ptr];
var t20=this.stk[--this.ptr];
for (var t23=t20; t21<0 ? t23>=t22 : t23<=t22; t23+=t21) {
this.stk[this.ptr++]=t23;
if (t24.call(this)==-1) break;
}
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("ssvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1]]!==undefined; this.ptr--;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-1]=!this.stk[this.ptr-1];
else this.stk[this.ptr-1]=~this.stk[this.ptr-1];
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("ssvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1]]!==undefined; this.ptr--;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-1]=!this.stk[this.ptr-1];
else this.stk[this.ptr-1]=~this.stk[this.ptr-1];
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-2]=this.stk[this.ptr-2]||this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]|this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f13;
var t27=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t27.call(this)==-1) return -1;
}
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=1;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f15;
var t33=this.stk[--this.ptr];
var t31=this.stk[--this.ptr];
var t30=this.stk[--this.ptr];
var t29=this.stk[--this.ptr];
for (var t32=t29; t30<0 ? t32>=t31 : t32<=t31; t32+=t30) {
this.stk[this.ptr++]=t32;
if (t33.call(this)==-1) break;
}
this.stk[this.ptr++]="barlen";
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
var t=this.dstk.get("validatecheck");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f16;
var t34=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t34.call(this)==-1) return -1;
}
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="checksum";
this.stk[this.ptr++]=0;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f17;
var t39=this.stk[--this.ptr];
var t37=this.stk[--this.ptr];
var t36=this.stk[--this.ptr];
var t35=this.stk[--this.ptr];
for (var t38=t35; t36<0 ? t38>=t37 : t38<=t37; t38+=t36) {
this.stk[this.ptr++]=t38;
if (t39.call(this)==-1) break;
}
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
var t=this.dstk.get("charvals");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.dstk.get("checksum");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]="checksum";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="checksum";
this.stk[this.ptr++]=16;
var t=this.dstk.get("checksum");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=16;
this.stk[this.ptr-2]=this.stk[this.ptr-2]%this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=16;
this.stk[this.ptr-2]=this.stk[this.ptr-2]%this.stk[this.ptr-1]; this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("validatecheck");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f19;
var t41=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t41.call(this)==-1) return -1;
}
this.stk[this.ptr++]="sbs";
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("includecheck");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f20;
var t42=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t42.call(this)==-1) return -1;
}
this.stk[this.ptr++]=8;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-1]=BWIPJS.psstring(this.stk[this.ptr-1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="txt";
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("includecheck");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f21;
var t43=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t43.call(this)==-1) return -1;
}
this.stk[this.ptr-1]=BWIPJS.psarray(this.stk[this.ptr-1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="xpos";
this.stk[this.ptr++]=0;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f23;
var t53=this.stk[--this.ptr];
var t51=this.stk[--this.ptr];
var t50=this.stk[--this.ptr];
var t49=this.stk[--this.ptr];
for (var t52=t49; t50<0 ? t52>=t51 : t52<=t51; t52+=t50) {
this.stk[this.ptr++]=t52;
if (t53.call(this)==-1) break;
}
var t=this.dstk.get("includecheck");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f27;
this.stk[this.ptr++]=$f28;
var t61=this.stk[--this.ptr];
var t62=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t62.call(this)==-1) return -1;
} else {
if (t61.call(this)==-1) return -1;
}
this.stk[this.ptr++]=Infinity;
this.stk[this.ptr++]="ren";
var t=this.dstk.get("renlinear");
this.stk[this.ptr++]=t;
this.stk[this.ptr++]="sbs";
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f29;
var t65=this.stk[--this.ptr];
var t64=this.stk[--this.ptr];
for (t63 in t64) {
if (t64 instanceof BWIPJS.psstring || t64 instanceof BWIPJS.psarray) {
if (t63.charCodeAt(0) > 57) continue;
this.stk[this.ptr++]=t64.get(t63);
} else {
this.stk[this.ptr++]=t63;
this.stk[this.ptr++]=t64[t63];
}
if (t65.call(this)==-1) break;
}
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
this.stk[this.ptr++]="bhs";
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=Math.floor(this.stk[this.ptr-2]/this.stk[this.ptr-1]); this.ptr--;
this.stk[this.ptr++]=$f30;
var t68=this.stk[--this.ptr];
var t66=this.stk[--this.ptr];
for (var t67=0; t67<t66; t67++) {
if (t68.call(this)==-1) break;
}
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
this.stk[this.ptr++]="bbs";
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=Math.floor(this.stk[this.ptr-2]/this.stk[this.ptr-1]); this.ptr--;
this.stk[this.ptr++]=$f31;
var t71=this.stk[--this.ptr];
var t69=this.stk[--this.ptr];
for (var t70=0; t70<t69; t70++) {
if (t71.call(this)==-1) break;
}
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
var t=this.dstk.get("includetext");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f32;
var t72=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t72.call(this)==-1) return -1;
}
this.stk[this.ptr++]="opt";
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t = {};
for (var i = this.ptr-1; i >= 1 && this.stk[i] !== Infinity; i-=2) {
if (this.stk[i-1] === Infinity) throw "dict: malformed stack";
t[this.stk[i-1]]=this.stk[i];
}
if (i < 0 || this.stk[i]!==Infinity) throw "dict: underflow";
this.ptr = i;
this.stk[this.ptr++]=t;
var t=this.dstk.get("dontdraw");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-1]=!this.stk[this.ptr-1];
else this.stk[this.ptr-1]=~this.stk[this.ptr-1];
var t=this.dstk.get("renlinear");
this.stk[this.ptr++]=t;
var t73=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t73.call(this)==-1) return -1;
}
this.dstk.pop(); this.dict=this.dstk[this.dstk.length-1];
psstptr = this.ptr;
}
BWIPJS.decrefs("rationalizedCodabar");
// END OF rationalizedCodabar
|
import { combineReducers } from 'redux'
import counterReducer, { getValue as counterGetValue } from '../counter/reducer'
import buttonReducer, {
getEnabledState as buttonGetEnabledState
} from '../button/reducer'
import relocatableGif from '../relocatableGif/reducer'
import randomGifPair from '../randomGifPair/reducer'
import randomGifPairOfPair from '../randomGifPairOfPair/reducer'
import mountPoints from './mountPoints'
const randomGif = relocatableGif(mountPoints.randomGif, 1)
const randomGifPairReducer = randomGifPair(mountPoints.randomGifPair)
const randomGifPairOfPairReducer = randomGifPairOfPair(
mountPoints.randomGifPairOfPair
)
const rootReducer = combineReducers({
[mountPoints.counter]: counterReducer,
[mountPoints.button]: buttonReducer,
[mountPoints.randomGif]: randomGif.reducer,
[mountPoints.randomGifPair]: randomGifPairReducer.reducer,
[mountPoints.randomGifPairOfPair]: randomGifPairOfPairReducer.reducer
})
const getCounterValue = state => counterGetValue(state.counter)
const getButtonEnabledState = state => buttonGetEnabledState(state.button)
export default rootReducer
export { getCounterValue, getButtonEnabledState }
|
(function() {
// 配置
var envir = 'online';
var configMap = {
test: {
appkey: 'af1edc0739d6187cecffd39b751d284f',
url:'https://apptest.netease.im'
},
pre:{
appkey: 'af1edc0739d6187cecffd39b751d284f',
url:'http://preapp.netease.im:8184'
},
online: {
appkey: 'af1edc0739d6187cecffd39b751d284f',
url:'https://app.netease.im'
}
};
window.CONFIG = configMap[envir];
}()) |
/**
* Список пользователей
*/
angular
.module('zakaz-xd.manage-users.users-list', [
'zakaz-xd.dialogs',
'zakaz-xd.directives.pagination',
'zakaz-xd.resources.users-resource',
'zakaz-xd.auth'
])
.controller('UsersListCtrl', ['$scope', '$stateParams', '$state', 'UsersResource',
'ErrorDialog', 'InfoDialog',
function ($scope, $stateParams, $state, UsersResource,
ErrorDialog, InfoDialog) {
$scope.userList = [];
$scope.pageConfig = {
page: 1,
itemsPerPage: 10,
pageChanged: function(page, itemsPerPage) {
refreshUsersTable({page: page, itemsPerPage: itemsPerPage});
}
};
function refreshUsersTable(page) {
UsersResource.getAllUsers(page).then(
function(response) {
$scope.userList = response.data.items;
$scope.pageConfig.count = response.data.count;
},
function(err) {
ErrorDialog.open(err.data);
}
);
}
refreshUsersTable({page: $scope.pageConfig.page, itemsPerPage: $scope.pageConfig.itemsPerPage});
}
])
;
|
import collections from '../lib/collections';
import permissions from './permissions';
import publications from './publications';
import methods from './methods';
import configs from '../lib/configs';
import privateConfigs from 'server/configs/posts';
import seeds from './seed.js';
import { addInstancesCount } from 'lib/helpers/instancesHelper';
export default {
configs,
privateConfigs,
collections,
permissions,
publications,
methods,
init(context) {
const { Collections } = context;
if (!Collections.Packages.findOne({ name: 'posts' })) {
Collections.Packages.insert({
name: 'posts',
moduleName: '文章模块',
display: true,
configs: context.configs.posts || {}
});
}
if (Collections.Posts.find().count() < seeds.data.length) {
for (let i = 0; i < seeds.data.length; i++) {
Collections.Posts.insert(seeds.data[i]);
addInstancesCount('post');
}
}
}
};
|
import {expect} from 'chai';
import jedi from '../../src';
describe('Module runnable registration', function () {
describe('a module .run() method', function () {
let jediModule;
beforeEach(function () {
jediModule = jedi.module();
});
it('should register a given method into the module\'s runnableMethod field', function () {
// Given
function runnable() {
};
// When
jediModule.run(runnable);
// Then
expect(jediModule.runnableMethod).to.equal(runnable);
});
it('should return the module', function () {
// Given
const runnable = 'foo';
// When
const result = jediModule.run(runnable);
// Then
expect(result).to.equal(jediModule);
});
});
});
|
(function($) {
window.Simplecheckout = function(params) {
this.params = params;
this.callback = params.javascriptCallback || function() {};
this.selectors = {
paymentForm: "#simplecheckout_payment_form",
paymentButtons: "#simplecheckout_payment_form div.buttons:last",
step: ".simplecheckout-step",
buttons: "#buttons",
buttonPrev: "#simplecheckout_button_prev",
buttonNext: "#simplecheckout_button_next",
buttonCreate: "#simplecheckout_button_confirm",
buttonBack: "#simplecheckout_button_back",
stepsMenu: "#simplecheckout_step_menu",
stepsMenuItem: ".simple-step",
stepsMenuDelimiter: ".simple-step-delimiter",
proceedText: "#simplecheckout_proceed_payment",
agreementCheckBox: "#agreement_checkbox",
agreementWarning: "#agreement_warning",
block: ".simplecheckout-block",
overlay: ".simplecheckout_overlay"
};
this.classes = {
stepsMenuCompleted: "simple-step-completed",
stepsMenuCurrent: "simple-step-current"
};
this.blocks = [];
this.$steps = [];
this.requestTimerId = 0;
this.currentStep = 1;
this.saveStepNumber = this.currentStep;
this.stepReseted = false;
this.formSubmitted = false;
this.backCount = -1;
this.$paymentForm = false;
var checkIsInContainer = function($element, selector) {
if ($element.parents(selector).length) {
return true;
}
return false;
};
this.callFunc = function(func, $target) {
var self = this;
if (func && typeof self[func] === "function") {
self[func]($target);
} else if (func) {
//console.log(func + " is not registered");
}
};
this.registerBlock = function(object) {
var self = this;
object.setParent(self);
self.blocks.push(object);
};
this.initBlocks = function() {
var self = this;
for (var i in self.blocks) {
if (!self.blocks.hasOwnProperty(i)) continue;
self.blocks[i].init();
}
};
this.init = function(disableScroll) {
var self = this;
if (typeof disableScroll === "undefined") {
disableScroll = false;
}
var callbackForComplexField = function($target) {
var func = $target.attr("data-onchange");
if (!func) {
func = $target.attr("data-onchange-delayed");
}
if (func && typeof self[func] === "function") {
self[func]($target);
} else if (func) {
//console.log(func + " is not registered");
}
self.setDirty();
};
self.requestTimerId = 0;
if (!self.isPaymentFormEmpty()) {
if (self.$paymentForm) {
self.restorePaymentForm(self.$paymentForm);
}
} else {
self.$paymentForm = false;
}
if (self.params.useGoogleApi) {
self.initGoogleApi(callbackForComplexField);
}
if (self.params.useAutocomplete) {
self.initAutocomplete(callbackForComplexField);
}
self.checkIsHuman();
self.addObserver();
self.initPopups();
self.initMasks();
self.initTooltips();
self.initDatepickers(callbackForComplexField);
self.initTimepickers(callbackForComplexField);
self.initFileUploader(function() {
self.overlayAll();
}, function() {
self.removeOverlays();
self.setDirty();
});
self.initHandlers();
self.initBlocks();
self.initSteps();
if (!disableScroll) {
self.scroll();
}
self.initValidationRules();
if (!self.isPaymentFormEmpty()) {
self.initReloadingOfPaymentForm();
}
if (typeof self.callback === "function") {
self.callback();
}
};
this.initHandlers = function() {
var self = this;
$(self.params.mainContainer).find("*[data-onchange], *[data-onclick]").each(function() {
var bind = true,
$element = $(this);
for (var i in self.blocks) {
if (!self.blocks.hasOwnProperty(i)) continue;
if (checkIsInContainer($element, self.blocks[i].currentContainer)) {
bind = false;
break;
}
}
if (bind) {
var funcOnChange = $element.attr("data-onchange");
if (funcOnChange) {
$element.on("change", function() {
self.setDirty($(this));
self.callFunc(funcOnChange, $element);
});
}
var funcOnClick = $element.attr("data-onclick");
if (funcOnClick) {
$element.on("click", function() {
if ($element.attr("data-onclick-stopped")) {
return;
}
self.setDirty();
self.callFunc(funcOnClick, $element);
});
}
}
});
};
this.skipKey = function(keyCode) {
if ($.inArray(keyCode,[9,13,16,17,18,19,20,27,35,36,37,38,39,40,91,93,224]) > -1) {
return true;
}
return false;
};
this.addObserver = function() {
var self = this;
$(self.params.mainContainer).find("input[type=radio], input[type=checkbox], select").on("change", function() {
if (!checkIsInContainer($(this), self.selectors.paymentForm)) {
self.setDirty($(this));
}
});
$(self.params.mainContainer).find("input, textarea").on("keydown", function(e) {
if (self.skipKey(e.keyCode)) {
return;
}
if (!checkIsInContainer($(this), self.selectors.paymentForm)) {
self.setDirty($(this));
}
});
};
this.initReloadingOfPaymentForm = function() {
var self = this;
var reload = function(disableScroll) {
var $field = $(this);
if (typeof disableScroll === "undefined") {
disableScroll = false;
}
if (!checkIsInContainer($field, self.selectors.paymentForm)) {
self.validate(true).then(function(result) {
if (result) {
self.reloadAll(undefined, disableScroll);
}
});
}
};
$(self.params.mainContainer).find("input[data-mask][data-reload-payment-form], input[type=radio][data-reload-payment-form], input[type=checkbox][data-reload-payment-form], select[data-reload-payment-form], input[type=date][data-reload-payment-form], input[type=time][data-reload-payment-form]").on("change", reload);
var timeoutId = 0;
$(self.params.mainContainer).find("input[type=text][data-reload-payment-form]:not([data-mask]), input[type=email][data-reload-payment-form]:not([data-mask]), input[type=tel][data-reload-payment-form]:not([data-mask]), textarea[data-reload-payment-form]").on("keydown", function(e) {
if (self.skipKey(e.keyCode)) {
return;
}
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function() {
clearTimeout(timeoutId);
reload(true);
}, 500);
});
};
this.savePaymentForm = function() {
var self = this;
if (!self.isPaymentFormEmpty()) {
self.$paymentForm = $(self.params.mainContainer).find(self.selectors.paymentForm).find("input[type=text],select,textarea,input[type=radio]:checked,input[type=checkbox]:checked");
} else {
self.$paymentForm = false;
}
};
this.restorePaymentForm = function($oldForm) {
var self = this;
var $paymentForm = $(self.params.mainContainer).find(self.selectors.paymentForm);
$oldForm.each(function() {
var $field = $(this);
var name = $field.attr("name");
var id = $field.attr("id");
var value = $field.val();
if ($field.is("input[type=text]") || $field.is("select") || $field.is("textarea")) {
if (name) {
$paymentForm.find("[name='" + name + "']").val(value);
} else if (id) {
$paymentForm.find("#" + id).val(value);
}
}
if ($field.is("input[type=radio]") || $field.is("input[type=checkbox]")) {
if (name) {
$paymentForm.find("[name='" + name + "'][value='" + value + "']").attr("checked", "checked");
} else if (id) {
$paymentForm.find("#" + id + "[value='" + value + "']").attr("checked", "checked");
}
}
});
delete $oldForm;
};
this.setDirty = function($element) {
var self = this;
var $mainContainer = $(self.params.mainContainer);
self.savePaymentForm();
if ($element && ($element.attr("data-reload-payment-form") || ($element.attr("data-onchange") && $element.attr("data-onchange") == "reloadAll"))) {
$mainContainer.find(self.selectors.paymentForm).attr("data-invalid", "true").find("input,select,textarea").attr("disabled", "disabled");
} else {
$mainContainer.find(self.selectors.paymentForm).attr("data-invalid", "true").empty();
}
$mainContainer.find("*[data-payment-button=true]").remove();
$mainContainer.find(self.selectors.proceedText).hide();
self.formSubmitted = false;
if (self.currentStep == self.stepsCount) {
$mainContainer.find(self.selectors.buttons).show();
$mainContainer.find(self.selectors.buttonCreate).show();
}
};
this.preventOrderDeleting = function(callback) {
var self = this;
$.get("index.php?" + self.params.additionalParams + "route=" + self.params.mainRoute + "/prevent_delete", function() {
if (typeof callback === "function") {
callback();
}
});
};
this.clickOnConfirmButton = function() {
var self = this;
var $mainContainer = $(self.params.mainContainer);
var $paymentForm = $mainContainer.find(self.selectors.paymentForm);
if (self.isPaymentFormEmpty()) {
return;
}
var gatewayLink = $paymentForm.find("div.buttons a:last").attr("href");
var $submitButton = $paymentForm.find("div.buttons input[type=button]:last,div.buttons input[type=submit]:last,div.buttons button:last,div.buttons a.button:last:not([href]),div.buttons a.btn:last:not([href])");
var $lastButton = $paymentForm.find("input[type=button]:last,input[type=submit]:last,button:last");
var lastLink = $paymentForm.find("a:last").attr("href");
var overlayButton = function() {
$mainContainer.find(self.selectors.buttonCreate).attr("disabled", "disabled");
if (!$mainContainer.find(".wait").length) {
$mainContainer.find(self.selectors.buttonCreate).after("<span class='wait'> <img src='" + self.params.additionalPath + self.resources.loadingSmall + "' alt='' /></span>");
}
};
var removeOverlay = function() {
$mainContainer.find(self.selectors.buttonCreate).removeAttr("disabled");
$mainContainer.find(".wait").remove();
};
if (typeof gatewayLink !== "undefined" && gatewayLink !== "" && gatewayLink !== "#") {
overlayButton();
self.preventOrderDeleting(function() {
removeOverlay();
window.location = gatewayLink;
self.blockFieldsDuringPayment();
self.proceed();
});
} else if ($submitButton.length) {
overlayButton();
self.preventOrderDeleting(function() {
removeOverlay();
if (!$submitButton.attr("disabled")) {
$submitButton.mousedown().click();
self.blockFieldsDuringPayment($submitButton);
self.proceed();
}
});
} else if ($lastButton.length) {
overlayButton();
self.preventOrderDeleting(function() {
removeOverlay();
if (!$lastButton.attr("disabled")) {
$lastButton.mousedown().click();
self.blockFieldsDuringPayment($lastButton);
self.proceed();
}
});
} else if (typeof lastLink !== "undefined" && lastLink !== "" && lastLink !== "#") {
overlayButton();
self.preventOrderDeleting(function() {
removeOverlay();
window.location = lastLink;
self.blockFieldsDuringPayment();
self.proceed();
});
}
};
this.isPaymentFormValid = function() {
var self = this;
return !self.isPaymentFormEmpty() && !$(self.params.mainContainer).find(self.selectors.paymentForm).attr("data-invalid") ? true : false;
};
this.isPaymentFormVisible = function() {
var self = this;
return !self.isPaymentFormEmpty() && $(self.params.mainContainer).find(self.selectors.paymentForm).find(":visible:not(form)").length > 0 ? true : false;
};
this.isPaymentFormEmpty = function() {
var self = this;
var $paymentForm = $(self.params.mainContainer).find(self.selectors.paymentForm);
return $paymentForm.length && $paymentForm.find("*").length > 0 ? false : true;
};
this.replaceCreateButtonWithConfirm = function() {
var self = this;
var $mainContainer = $(self.params.mainContainer);
var $paymentForm = $(self.params.mainContainer).find(self.selectors.paymentForm);
if (self.isPaymentFormEmpty()) {
return;
}
var $gatewayLink = $paymentForm.find("div.buttons a:last");
var $submitButton = $paymentForm.find("div.buttons input[type=button]:last,div.buttons input[type=submit]:last,div.buttons button:last,div.buttons a.button:last:not([href]),div.buttons a.btn:last:not([href])");
var $lastButton = $paymentForm.find("input[type=button]:last,input[type=submit]:last,button:last");
var $lastLink = $paymentForm.find("a:last");
var $obj = false;
if ($gatewayLink.length) {
$obj = $gatewayLink;
} else if ($submitButton.length) {
$obj = $submitButton;
} else if ($lastButton.length) {
$obj = $lastButton;
} else if ($lastLink.length) {
$obj = $lastLink;
}
if ($obj) {
var $clone = $obj.clone(false).removeAttr("onclick");
$mainContainer.find(self.selectors.buttonCreate).hide().before($clone);
$clone.attr("data-payment-button", "true").bind("mousedown", function() {
if ($obj.attr("disabled")) {
return;
}
$obj.mousedown();
}).bind("click", function() {
if ($obj.attr("disabled")) {
return;
}
self.preventOrderDeleting(function() {
self.proceed();
$obj.click();
self.blockFieldsDuringPayment($obj);
});
});
} else {
$mainContainer.find(self.selectors.buttons).hide();
self.preventOrderDeleting();
}
};
this.blockFieldsDuringPayment = function($button) {
var self = this;
self.disableAllFieldsBeforePayment();
if (typeof $button !== "undefined") {
var timerId = setInterval(function() {
if (!$button.attr("disabled")) {
self.enableAllFieldsAfterPayment();
clearInterval(timerId);
}
}, 250);
}
};
this.disableAllFieldsBeforePayment = function() {
var self = this;
$(self.params.mainContainer).find(self.selectors.block).each(function() {
if ($(this).attr("id") == "simplecheckout_payment_form") {
return;
}
$(this).find("input,select,textarea").attr("disabled", "disabled");
$(this).find("[data-onclick]").attr("data-onclick-stopped", "true");
});
};
this.enableAllFieldsAfterPayment = function() {
var self = this;
$(self.params.mainContainer).find(self.selectors.block).each(function() {
if ($(this).attr("id") == "simplecheckout_payment_form") {
return;
}
$(this).find("input:not([data-dummy]),select,textarea").removeAttr("disabled");
$(this).find("[data-onclick]").removeAttr("data-onclick-stopped");
});
};
this.proceed = function() {
var self = this;
if (self.params.displayProceedText && !self.isPaymentFormVisible()) {
$(self.params.mainContainer).find(self.selectors.proceedText).show();
}
};
this.gotoStep = function($target) {
var self = this;
var step = $target.attr("data-step");
if (step < self.currentStep) {
self.currentStep = step;
self.setDirty();
self.displayCurrentStep();
} else {
self.nextStep();
}
};
this.previousStep = function($target) {
var self = this;
if (self.currentStep > 1) {
self.currentStep--;
self.setDirty();
self.displayCurrentStep();
}
};
this.nextStep = function($target) {
var self = this;
if ($target.data("clicked")) {
return;
}
$target.data("clicked", true);
self.validate(false).then(function(result) {
if (result) {
if (self.currentStep < self.$steps.length) {
self.currentStep++;
}
self.submitForm();
} else {
$target.data("clicked", false);
self.scroll();
}
});
};
this.saveStep = function() {
var self = this;
if (self.currentStep) {
$(self.params.mainContainer).append($("<input/>").attr("type", "hidden").attr("name", "next_step").val(self.currentStep));
}
};
this.ignorePost = function() {
var self = this;
$(self.params.mainContainer).append($("<input/>").attr("type", "hidden").attr("name", "ignore_post").val(1));
};
this.addSystemFieldsInForm = function() {
var self = this;
if (self.formSubmitted) {
$(self.params.mainContainer).append($("<input/>").attr("type", "hidden").attr("name", "create_order").val(1));
}
if (self.currentStep) {
$(self.params.mainContainer).append($("<input/>").attr("type", "hidden").attr("name", "next_step").val(self.currentStep));
}
};
this.getAgreementCheckboxStep = function() {
var step = typeof this.params.agreementCheckboxStep !== "undefined" && this.params.agreementCheckboxStep !== "" ? (this.params.agreementCheckboxStep + 1) : this.stepsCount - 1;
if (step > this.stepsCount - 1) {
step = this.stepsCount - 1;
}
return step;
}
this.setLocationHash = function(hash) {
window.location.hash = hash;
this.backCount--;
};
this.initSteps = function() {
var self = this;
var i = 1;
var $mainContainer = $(self.params.mainContainer);
var $steps = $mainContainer.find(self.selectors.step);
self.stepReseted = false;
self.$steps = [];
self.stepsCount = $steps.length || 1;
$steps.each(function() {
var $step = $(this);
self.$steps.push($step);
// check steps before current for errors and set step with error as current
var $errorBlocks = $step.find(self.selectors.block + "[data-error=true]");
if (i < self.currentStep && $errorBlocks.length) {
self.currentStep = i;
self.stepReseted = true;
}
i++;
});
if (self.stepsCount > 1 && !self.stepReseted && (self.currentStep == self.stepsCount || self.currentStep > self.getAgreementCheckboxStep()) && $mainContainer.attr("data-error") == "true") {
self.currentStep--;
self.stepReseted = true;
}
//a fix for case when some steps are suddenly hidden after ajax request
if (self.stepsCount > 1 && !self.stepReseted && self.currentStep > self.stepsCount) {
self.currentStep = self.stepsCount;
}
$mainContainer.find(self.selectors.paymentButtons).hide();
if (!self.isPaymentFormVisible()) {
$mainContainer.find(self.selectors.paymentForm).css({
"margin": "0",
"padding": "0"
});
}
self.displayCurrentStep();
};
this.displayCurrentStep = function() {
var self = this;
var $mainContainer = $(self.params.mainContainer);
var initButtons = function() {
if (self.stepsCount > 1) {
if (self.currentStep == 1) {
$mainContainer.find(self.selectors.buttonPrev).hide();
} else {
$mainContainer.find(self.selectors.buttonBack).hide();
}
if (self.currentStep < self.stepsCount) {
$mainContainer.find(self.selectors.buttonNext).show();
$mainContainer.find(self.selectors.buttonCreate).hide();
}
$mainContainer.find(self.selectors.agreementCheckBox).hide();
if (self.currentStep == self.getAgreementCheckboxStep()) {
$mainContainer.find(self.selectors.agreementCheckBox).show();
}
}
if (self.currentStep == self.stepsCount) {
$mainContainer.find(self.selectors.buttonNext).hide();
self.replaceCreateButtonWithConfirm();
}
};
var initStepsMenu = function() {
$mainContainer.find(self.selectors.stepsMenu + " " + self.selectors.stepsMenuItem).removeClass(self.classes.stepsMenuCompleted).removeClass(self.classes.stepsMenuCurrent);
$mainContainer.find(self.selectors.stepsMenu + " " + self.selectors.stepsMenuDelimiter + " img").attr("src", self.params.additionalPath + self.resources.next);
for (var i = 1; i < self.currentStep; i++) {
$mainContainer.find(self.selectors.stepsMenu + " " + self.selectors.stepsMenuItem + "[data-step=" + i + "]").addClass(self.classes.stepsMenuCompleted);
$mainContainer.find(self.selectors.stepsMenu + " " + self.selectors.stepsMenuDelimiter + "[data-step=" + (i + 1) + "] img").attr("src", self.params.additionalPath + self.resources.nextCompleted);
}
$mainContainer.find(self.selectors.stepsMenu + " " + self.selectors.stepsMenuItem + "[data-step=" + self.currentStep + "]").addClass(self.classes.stepsMenuCurrent);
};
var hideSteps = function() {
$mainContainer.find(self.selectors.step).hide();
};
var isLastStepHasOnlyPaymentForm = function() {
var $lastStep = $mainContainer.find(self.selectors.step + ":last");
return $lastStep.find(self.selectors.block).length == 1 && $lastStep.find(self.selectors.paymentForm).length == 1 ? true : false;
};
if (self.currentStep == self.stepsCount && !self.isPaymentFormVisible() && self.isPaymentFormValid() && (isLastStepHasOnlyPaymentForm() || self.formSubmitted)) {
self.clickOnConfirmButton();
if (isLastStepHasOnlyPaymentForm()) {
self.currentStep--;
}
}
hideSteps();
if (typeof self.$steps[self.currentStep - 1] !== "undefined") {
self.$steps[self.currentStep - 1].show();
}
if (self.stepsCount > 1) {
self.setLocationHash("step_" + self.currentStep);
}
initStepsMenu();
initButtons();
};
this.scroll = function() {
var self = this,
error = false,
top = 10000,
bottom = 0;
var $mainContainer = $(self.params.mainContainer);
var isOutsideOfVisibleArea = function(y) {
if (y < $(window).scrollTop() || y > ($(window).scrollTop() + $(window).height())) {
return true;
}
return false;
};
if (self.params.popup) {
return;
}
if (self.params.scrollToError) {
$($mainContainer.find("[data-error=true]:visible")).each(function() {
var offset = $(this).offset();
if (offset.top < top) {
top = offset.top;
}
if (offset.bottom > bottom) {
bottom = offset.bottom;
}
});
$($mainContainer.find(".simplecheckout-warning-block:visible")).each(function() {
var offset = $(this).offset();
if (offset.top < top) {
top = offset.top;
}
if (offset.bottom > bottom) {
bottom = offset.bottom;
}
});
$($mainContainer.find(".simplecheckout-rule:visible")).each(function() {
if ($(this).parents(".simplecheckout-block").length) {
var offset = $(this).parents(".simplecheckout-block").offset();
if (offset.top < top) {
top = offset.top;
}
if (offset.bottom > bottom) {
bottom = offset.bottom;
}
}
});
if (top < 10000 && isOutsideOfVisibleArea(top)) {
$("html, body").animate({
scrollTop: top
}, "slow");
error = true;
} else if (bottom && isOutsideOfVisibleArea(bottom)) {
$("html, body").animate({
scrollTop: bottom
}, "slow");
error = true;
}
}
if (self.params.scrollToPaymentForm && !error) {
if (self.isPaymentFormVisible()) {
top = $mainContainer.find(self.selectors.paymentForm).offset().top + $mainContainer.find(self.selectors.paymentForm).outerHeight();
if (top && isOutsideOfVisibleArea(top)) {
$("html, body").animate({
scrollTop: top
}, "slow");
}
}
}
if ($mainContainer.find(self.selectors.stepsMenu).length && self.currentStep != self.saveStepNumber) {
top = $mainContainer.find(self.selectors.stepsMenu).offset().top;
if (top && isOutsideOfVisibleArea(top)) {
$("html, body").animate({
scrollTop: top
}, "slow");
}
}
self.saveStepNumber = self.currentStep;
};
this.validate = function(silent) {
var self = this;
var result = true;
var promises = [];
if (typeof silent === "undefined") {
silent = false;
}
var $agreementCheckbox = $(self.params.mainContainer).find(self.selectors.agreementCheckBox).find("input[type=checkbox]");
var $agreementWarning = $(self.params.mainContainer).find(self.selectors.agreementWarning);
if ($agreementCheckbox.length && $agreementCheckbox.is(":visible") && !$agreementCheckbox.is(":checked")) {
if ($agreementWarning.length && !silent) {
$agreementWarning.show().attr("data-error", "true");
result = false;
}
} else {
$agreementWarning.hide().removeAttr("data-error");
}
for (var i in self.blocks) {
if (!self.blocks.hasOwnProperty(i)) continue;
var promise = self.blocks[i].validate(silent).then(function(validatorResult) {
if (!validatorResult) {
result = false;
}
});
promises.push(promise);
}
var deferred = $.Deferred();
$.when.apply($, promises).then(function() {
deferred.resolve(result);
});
return deferred.promise();
};
this.backHistory = function() {
var self = this;
history.go(self.backCount);
};
this.createOrder = function() {
var self = this;
self.validate(false).then(function(result) {
if (result) {
self.formSubmitted = true;
self.submitForm();
} else {
self.scroll();
}
});
};
this.submitForm = function() {
var self = this;
self.requestReloadAll();
};
/**
* Adds delay for reload execution on 150 ms, it allows to check sequence of events and to execute only the last request to handle of more events in one reloading
* @param {Function} callback
*/
this.requestReloadAll = function(callback) {
var self = this;
if (self.requestTimerId) {
clearTimeout(self.requestTimerId);
self.requestTimerId = 0;
}
self.requestTimerId = setTimeout(function() {
self.reloadAll(callback);
}, 150);
};
this.overlayAll = function() {
var self = this;
for (var i in self.blocks) {
if (!self.blocks.hasOwnProperty(i)) continue;
self.blocks[i].overlay();
}
$(self.params.mainContainer).find(self.selectors.block).each(function() {
if (!$(this).data("initialized")) {
SimplecheckoutBlock.prototype.overlay.apply(self, [$(this)]);
}
});
};
this.removeOverlays = function() {
var self = this;
$(self.params.mainContainer).find(self.selectors.overlay).remove();
$(self.params.mainContainer).find("input:not([data-dummy]),select,textarea").removeAttr("disabled");
};
this.createPostData = function() {
var self = this;
var visibleFields = $(self.params.mainContainer + " .simplecheckout-step:visible .simplecheckout-block:not(#simplecheckout_payment_form)").find("input,select,textarea").serializeArray();
var otherFields = $(self.params.mainContainer + " *:not(#simplecheckout_payment_form)").find("input,select,textarea").serializeArray();
var allFields = $(self.params.mainContainer + " > input,select,textarea").serializeArray();
var usedFields = [];
var fields = [];
for (var i in visibleFields) {
if (!visibleFields.hasOwnProperty(i)) continue;
var info = visibleFields[i];
usedFields.push(info.name);
fields.push(encodeURIComponent(info.name)+"="+encodeURIComponent(info.value));
}
for (var i in otherFields) {
if (!otherFields.hasOwnProperty(i)) continue;
var info = otherFields[i];
if ($.inArray(info.name, usedFields) == -1) {
usedFields.push(info.name)
fields.push(encodeURIComponent(info.name)+"="+encodeURIComponent(info.value));
}
}
for (var i in allFields) {
if (!allFields.hasOwnProperty(i)) continue;
var info = allFields[i];
if ($.inArray(info.name, usedFields) == -1) {
usedFields.push(info.name)
fields.push(encodeURIComponent(info.name)+"="+encodeURIComponent(info.value));
}
}
return fields.join("&");
}
/**
* Reload all blocks via main controller which includes all registered blocks as childs
* @param {Function} callback
*/
this.reloadAll = function(callback, disableScroll) {
var self = this;
if (self.isReloading) {
return;
}
if (typeof disableScroll === "undefined") {
disableScroll = false;
}
self.addSystemFieldsInForm();
self.isReloading = true;
var postData = self.createPostData();
var overlayTimeoutId = 0;
$.ajax({
url: self.params.mainUrl,
data: postData + "&simple_ajax=1",
type: "POST",
dataType: "text",
beforeSend: function() {
overlayTimeoutId = setTimeout(function() {
if (overlayTimeoutId) {
self.overlayAll();
}
}, 250);
},
success: function(data) {
clearTimeout(overlayTimeoutId);
overlayTimeoutId = 0;
var newData = $(self.params.mainContainer, $(data)).get(0);
if (!newData && data) {
newData = data;
}
$(self.params.mainContainer).replaceWith(newData);
self.init(disableScroll);
if (typeof callback === "function") {
callback.call(self);
}
self.removeOverlays();
self.isReloading = false;
},
error: function(xhr, ajaxOptions, thrownError) {
clearTimeout(overlayTimeoutId);
overlayTimeoutId = 0;
self.removeOverlays();
self.isReloading = false;
}
});
};
this.reloadBlock = function(container, callback) {
var self = this;
if (self.isReloading) {
return;
}
self.isReloading = true;
var postData = $(self.params.mainContainer).find("input,select,textarea").serialize();
$.ajax({
url: self.params.mainUrl,
data: postData + "&simple_ajax=1",
type: "POST",
dataType: "text",
beforeSend: function() {},
success: function(data) {
var newData = $(container, $(data)).get(0);
if (!newData && data) {
newData = data;
}
$(container).replaceWith(newData);
self.init();
if (typeof callback === "function") {
callback.call(self);
}
self.isReloading = false;
},
error: function(xhr, ajaxOptions, thrownError) {
self.isReloading = false;
}
});
};
this.registerBlock(new SimplecheckoutCart("#simplecheckout_cart", "checkout/simplecheckout_cart"));
this.registerBlock(new SimplecheckoutShipping("#simplecheckout_shipping", "checkout/simplecheckout_shipping"));
this.registerBlock(new SimplecheckoutPayment("#simplecheckout_payment", "checkout/simplecheckout_payment"));
this.registerBlock(new SimplecheckoutForm("#simplecheckout_customer", "checkout/simplecheckout_customer"));
this.registerBlock(new SimplecheckoutForm("#simplecheckout_payment_address", "checkout/simplecheckout_payment_address"));
this.registerBlock(new SimplecheckoutForm("#simplecheckout_shipping_address", "checkout/simplecheckout_shipping_address"));
this.registerBlock(new SimplecheckoutComment("#simplecheckout_comment", "checkout/simplecheckout_comment"));
var login = new SimplecheckoutLogin("#simplecheckout_login", "checkout/simplecheckout_login");
login.setParent(this);
login.init();
login.shareMethod("open", "openLoginBox");
this.instances.push(this);
};
Simplecheckout.prototype = inherit(window.Simple.prototype);
/**
* It is parent of all blocks
*/
function SimplecheckoutBlock(container, route) {
this.currentContainer = container;
this.currentRoute = route;
}
SimplecheckoutBlock.prototype.setParent = function(object) {
this.simplecheckout = object;
this.params = object.params;
this.resources = object.resources;
};
SimplecheckoutBlock.prototype.reloadAll = function(callback) {
if (this.simplecheckout) {
this.simplecheckout.requestReloadAll(callback);
} else {
this.reload();
}
};
SimplecheckoutBlock.prototype.reload = function(callback) {
var self = this;
if (self.isReloading) {
return;
}
self.isReloading = true;
var postData = $(self.params.mainContainer).find(self.currentContainer).find("input,select,textarea").serialize();
$.ajax({
url: "index.php?" + self.params.additionalParams + "route=" + self.currentRoute,
data: postData + "&simple_ajax=1",
type: "POST",
dataType: "text",
beforeSend: function() {
self.overlay();
},
success: function(data) {
var newData = $(self.currentContainer, $(data)).get(0);
if (!newData && data) {
newData = data;
}
$(self.params.mainContainer).find(self.currentContainer).replaceWith(newData);
self.init();
if (typeof callback === "function") {
callback.call(self);
}
self.removeOverlay();
self.isReloading = false;
},
error: function(xhr, ajaxOptions, thrownError) {
self.removeOverlay();
self.isReloading = false;
}
});
};
SimplecheckoutBlock.prototype.load = function(callback, container) {
var self = this;
if (self.isLoading) {
return;
}
if (typeof callback !== "function") {
container = callback;
callback = null;
}
self.isLoading = true;
$.ajax({
url: "index.php?" + self.params.additionalParams + "route=" + self.currentRoute,
type: "GET",
dataType: "text",
beforeSend: function() {
self.overlay();
},
success: function(data) {
var newData = $(self.currentContainer, $(data)).get(0);
if (!newData && data) {
newData = data;
}
if (newData) {
if (container) {
$(container).html(newData);
} else {
$(self.currentContainer).replaceWith(newData);
}
self.init();
}
if (typeof callback === "function") {
callback();
}
self.removeOverlay();
self.isLoading = false;
},
error: function(xhr, ajaxOptions, thrownError) {
self.removeOverlay();
self.isLoading = false;
}
});
};
SimplecheckoutBlock.prototype.overlay = function(useBlock) {
var self = this;
var $block = (useBlock && $(useBlock)) || $(self.params.mainContainer).find(self.currentContainer);
if ($block.length) {
if (~~$block.height() < 50) {
return;
}
$block.find("input,select,textarea").attr("disabled", "disabled");
$block.append("<div class='simplecheckout_overlay' id='" + $block.attr("id") + "_overlay'></div>");
$block.find(".simplecheckout_overlay")
.css({
"background": "url(" + self.params.additionalParams + self.resources.loading + ") no-repeat center center",
"opacity": 0.4,
"position": "absolute",
"width": $block.width(),
"height": $block.height(),
"z-index": 5000
})
.offset({
top: $block.offset().top,
left: $block.offset().left
});
}
};
SimplecheckoutBlock.prototype.removeOverlay = function() {
var self = this;
var $mainContainer = $(self.params.mainContainer);
if (typeof self.currentContainer !== "undefined") {
$mainContainer.find(self.currentContainer).find("input:not([data-dummy]),select,textarea").removeAttr("disabled");
$mainContainer.find(self.currentContainer + "_overlay").remove();
}
};
SimplecheckoutBlock.prototype.hasError = function() {
return $(this.params.mainContainer).find(this.currentContainer).attr("data-error") ? true : false;
};
SimplecheckoutBlock.prototype.init = function(useContainer) {
var self = this;
var $mainContainer = $(self.params.mainContainer);
var $currentContainer = $mainContainer.find(self.currentContainer);
if (!$currentContainer.length) {
return;
}
var callFunc = function(func, $target) {
if (func && typeof self[func] === "function") {
self[func]($target);
} else if (func) {
//console.log(func + " is not registered");
}
};
$currentContainer.find("*[data-onchange]").on("change", function() {
if (typeof self.simplecheckout !== "undefined") {
self.simplecheckout.setDirty($(this));
}
callFunc($(this).attr("data-onchange"), $(this));
});
$currentContainer.find("*[data-onclick]").on("click", function() {
if ($(this).attr("data-onclick-stopped")) {
return;
}
if (typeof self.simplecheckout !== "undefined") {
self.simplecheckout.setDirty();
}
callFunc($(this).attr("data-onclick"), $(this));
});
if (self.isEmpty()) {
////console.log(self.currentContainer + " is empty");
}
if (!self.hasError() && $currentContainer.attr("data-hide")) {
$currentContainer.hide();
}
self.addFocusHandler();
self.restoreFocus();
$currentContainer.data("initialized", true);
};
SimplecheckoutBlock.prototype.validate = function(silent) {
var self = this;
if (typeof silent === "undefined") {
silent = false;
}
return self.simplecheckout.checkRules(self.currentContainer, silent);
};
SimplecheckoutBlock.prototype.isEmpty = function() {
if ($(this.params.mainContainer).find(this.currentContainer).find("*").length) {
return false;
}
return true;
};
SimplecheckoutBlock.prototype.shareMethod = function(name, asName) {
SimplecheckoutBlock.prototype[asName] = bind(this[name], this);
};
SimplecheckoutBlock.prototype.displayWarning = function() {
$(this.params.mainContainer).find(this.currentContainer).find(".simplecheckout-warning-block").show();
};
SimplecheckoutBlock.prototype.hideWarning = function() {
$(this.params.mainContainer).find(this.currentContainer).find(".simplecheckout-warning-block").hide();
};
SimplecheckoutBlock.prototype.focusedFieldId = "";
SimplecheckoutBlock.prototype.addFocusHandler = function() {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
$currentContainer.find("input,textarea,select").focus(function() {
self.simplecheckout.focusedFieldId = $(this).attr("id");
});
$currentContainer.find("input,textarea").blur(function() {
//self.simplecheckout.focusedFieldId = "";
});
};
SimplecheckoutBlock.prototype.restoreFocus = function() {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
var focusedFieldId = self.simplecheckout.focusedFieldId;
var focusedField = $currentContainer.find("#" + focusedFieldId);
if (focusedField.length && focusedField.is(":visible") && ((focusedField.attr("type") && focusedField.attr("type") == "text") || focusedField.is("textarea"))) {
var $field = $currentContainer.find("#" + focusedFieldId);
var value = $field.val();
$field.val("").focus().val(value);
}
};
function SimplecheckoutCart(container, route) {
this.currentContainer = container;
this.currentRoute = route;
this.init = function() {
var self = this;
SimplecheckoutBlock.prototype.init.apply(self, arguments);
self.initMiniCart();
};
this.initMiniCart = function() {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
var total = $currentContainer.find("#simplecheckout_cart_total").html();
var weight = $currentContainer.find("#simplecheckout_cart_weight").text();
if (total) {
$("#cart_total").html(total);
$("#cart-total").html(total);
$("#cart_menu .s_grand_total").html(total);
$("#cart .tb_items").html(total);
$("#weight").text(weight);
if (self.params.currentTheme == "shoppica2") {
$("#cart_menu div.s_cart_holder").html("");
$.getJSON("index.php?" + self.params.additionalParams + "route=tb/cartCallback", function(json) {
if (json["html"]) {
$("#cart_menu span.s_grand_total").html(json["total_sum"]);
$("#cart_menu div.s_cart_holder").html(json["html"]);
}
});
}
if (self.params.currentTheme == "shoppica") {
$("#cart_menu div.s_cart_holder").html("");
$.getJSON("index.php?" + self.params.additionalParams + "route=module/shoppica/cartCallback", function(json) {
if (json["output"]) {
$("#cart_menu span.s_grand_total").html(json["total_sum"]);
$("#cart_menu div.s_cart_holder").html(json["output"]);
}
});
}
}
};
this.increaseProductQuantity = function($target) {
var self = this;
var $quantity = $target.parent().find("input");
var quantity = parseFloat($quantity.val());
if (!isNaN(quantity)) {
$quantity.val(quantity + 1);
self.reloadAll();
}
};
this.decreaseProductQuantity = function($target) {
var self = this;
var $quantity = $target.parent().find("input");
var quantity = parseFloat($quantity.val());
if (!isNaN(quantity) && quantity > 1) {
$quantity.val(quantity - 1);
self.reloadAll();
}
};
this.changeProductQuantity = function($target) {
var self = this;
if (typeof $target[0] !== "undefined" && typeof $target[0].tagName !== "undefined" && $target[0].tagName !== "INPUT") {
$target = $target.parents("td").find("input");
}
var quantity = parseFloat($target.val());
if (!isNaN(quantity)) {
self.reloadAll();
}
};
this.removeProduct = function($target) {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
var productKey = $target.attr("data-product-key");
$currentContainer.find("#simplecheckout_remove").val(productKey);
self.reloadAll();
};
this.removeGift = function($target) {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
var giftKey = $target.attr("data-gift-key");
$currentContainer.find("#simplecheckout_remove").val(giftKey);
self.reloadAll();
};
this.removeCoupon = function($target) {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
$currentContainer.find("input[name='coupon']").val("");
self.reloadAll();
};
this.removeReward = function($target) {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
$currentContainer.find("input[name='reward']").val("");
self.reloadAll();
};
this.removeVoucher = function($target) {
var self = this;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
$currentContainer.find("input[name='voucher']").val("");
self.reloadAll();
};
}
SimplecheckoutCart.prototype = inherit(SimplecheckoutBlock.prototype);
function SimplecheckoutLogin(container, route) {
this.currentContainer = container;
this.currentRoute = route;
this.init = function() {
var self = this;
SimplecheckoutBlock.prototype.init.apply(self, arguments);
};
this.initPopupLayer = function() {
var self = this;
var position = $("#simple_login_layer").parent().css("position");
if (!$("#simple_login_layer").length || position == "fixed" || position == "relative" || position == "absolute") {
$("#simple_login_layer").remove();
$("#simple_login").remove();
$(self.params.mainContainer).append("<div id='simple_login_layer'></div><div id='simple_login'><div id='temp_popup_container'></div></div>");
$("#simple_login_layer").on("click", function() {
self.close();
});
}
$("#simple_login_layer")
.css("position", "fixed")
.css("top", "0")
.css("left", "0")
.css("right", "0")
.css("bottom", "0");
$("#simple_login_layer").fadeTo(500, 0.8);
};
this.openPopup = function() {
var self = this;
self.initPopupLayer();
if (!$(self.currentContainer).html()) {
self.load(function() {
if ($(self.currentContainer).html()) {
self.resizePopup();
} else {
self.closePopup();
}
}, "#temp_popup_container");
} else {
self.hideWarning();
self.resizePopup();
}
};
this.resizePopup = function() {
$("#simple_login").show();
$("#simple_login").css("height", $(this.currentContainer).outerHeight() + 20);
$("#simple_login").css("top", $(window).height() / 2 - ($("#simple_login").outerHeight() ? $("#simple_login").outerHeight() : $("#simple_login").height()) / 2);
$("#simple_login").css("left", $(window).width() / 2 - ($("#simple_login").outerWidth() ? $("#simple_login").outerWidth() : $("#simple_login").width()) / 2);
};
this.closePopup = function() {
var self = this;
$("#simple_login_layer").fadeOut(500, function() {
$(this).hide().css("opacity", "1");
});
$("#simple_login").fadeOut(500, function() {
$(this).hide();
});
};
this.openFlat = function() {
var self = this;
if (!$(self.currentContainer).length) {
$("<div id='temp_flat_container'><img src='" + self.params.additionalPath + self.resources.loading + "'></div>").insertBefore(self.params.loginBoxBefore);
self.load("#temp_flat_container");
}
self.hideWarning();
$(self.currentContainer).show();
};
this.closeFlat = function() {
$(this.currentContainer).hide();
};
this.isOpened = function() {
return $("#temp_flat_container *:visible").length ? true : false;
};
this.open = function() {
var self = this;
/*if (self.getParam("logged")) {
return;
}*/
if (self.params.loginBoxBefore) {
self.openFlat();
} else {
self.openPopup();
}
};
this.close = function() {
var self = this;
if (self.params.loginBoxBefore) {
self.closeFlat();
} else {
self.closePopup();
}
};
this.login = function() {
var self = this;
this.reload(function() {
if (!self.hasError()) {
self.closePopup();
self.closeFlat();
if (self.simplecheckout) {
self.simplecheckout.saveStep();
self.simplecheckout.ignorePost();
self.simplecheckout.reloadAll();
} else {
window.location.reload();
}
} else {
self.resizePopup();
}
});
};
}
SimplecheckoutLogin.prototype = inherit(SimplecheckoutBlock.prototype);
function SimplecheckoutComment(container, route) {
this.currentContainer = container;
this.currentRoute = route;
this.init = function() {
var self = this;
SimplecheckoutBlock.prototype.init.apply(self, arguments);
};
}
SimplecheckoutComment.prototype = inherit(SimplecheckoutBlock.prototype);
function SimplecheckoutShipping(container, route) {
this.currentContainer = container;
this.currentRoute = route;
this.init = function() {
var self = this;
SimplecheckoutBlock.prototype.init.apply(self, arguments);
};
this.validate = function(silent) {
var self = this;
var result = true;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
var deferred = $.Deferred();
if (typeof silent === "undefined") {
silent = false;
}
if ($currentContainer.is(":visible") && !$currentContainer.find("input:checked").length && !$currentContainer.find("option:selected").length) {
if (!silent) {
self.displayWarning();
}
result = false;
}
SimplecheckoutBlock.prototype.validate.apply(self, arguments).then(function(validatorResult) {
deferred.resolve(result && validatorResult);
});
return deferred.promise();
};
}
SimplecheckoutShipping.prototype = inherit(SimplecheckoutBlock.prototype);
function SimplecheckoutPayment(container, route) {
this.currentContainer = container;
this.currentRoute = route;
this.init = function() {
var self = this;
SimplecheckoutBlock.prototype.init.apply(self, arguments);
};
this.validate = function(silent) {
var self = this;
var result = true;
var $currentContainer = $(self.params.mainContainer).find(self.currentContainer);
var deferred = $.Deferred();
if (typeof silent === "undefined") {
silent = false;
}
if ($currentContainer.is(":visible") && !$currentContainer.find("input:checked").length && !$currentContainer.find("option:selected").length) {
if (!silent) {
self.displayWarning();
}
result = false;
}
SimplecheckoutBlock.prototype.validate.apply(self, arguments).then(function(validatorResult) {
deferred.resolve(result && validatorResult);
});
return deferred.promise();
};
}
SimplecheckoutPayment.prototype = inherit(SimplecheckoutBlock.prototype);
function SimplecheckoutForm(container, route) {
this.currentContainer = container;
this.currentRoute = route;
this.init = function() {
var self = this;
SimplecheckoutBlock.prototype.init.apply(self, arguments);
};
this.validate = function(silent) {
var self = this;
var result = true;
var deferred = $.Deferred();
if (typeof silent === "undefined") {
silent = false;
}
SimplecheckoutBlock.prototype.validate.apply(self, arguments).then(function(validatorResult) {
deferred.resolve(result && validatorResult);
});
return deferred.promise();
};
this.reloadAll = function($element) {
var self = this;
setTimeout(function() {
if (!$element.attr("data-valid") || $element.attr("data-valid") == "true") {
SimplecheckoutBlock.prototype.reloadAll.apply(self, arguments);
}
}, 0);
};
}
SimplecheckoutForm.prototype = inherit(SimplecheckoutBlock.prototype);
})(jQuery || $); |
/*
* node-klass
* https://github.com/ayecue/node-klass
*
* Copyright (c) 2015 "AyeCue" Sören Wehmeier, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = (function(
forEach,
extend,
printf,
CONSTANTS,
colors
){
function KlassLogger(){
}
extend(KlassLogger.prototype,{
self: KlassLogger,
analyze: function(context){
var info = {};
Error.captureStackTrace(info);
var splittedInfo = info.stack.split('\n'),
indexOfLine = forEach(splittedInfo,function(index,str){
if (CONSTANTS.LOGGER.SEARCH_PATTERN.test(str)) {
this.result = index + 1;
this.skip = true;
}
},-1),
greppedLine = splittedInfo[indexOfLine];
if (!greppedLine) {
return;
}
// 1. link - 2. name
var matches = greppedLine.match(CONSTANTS.LOGGER.TRACE_PATTERN);
if (!matches) {
return;
}
return printf(CONSTANTS.LOGGER.TRACE_TPL,{
link : matches.pop(),
name : matches.pop()
});
},
/**
* Generating console message templates
*/
toMessages: function(args){
return forEach(args,function(_,item){
var messages = this.result,
type = typeof item;
if (type == 'string') {
messages.push('%s');
} else if (type == 'number') {
messages.push('%d');
} else if (type == 'boolean') {
messages.push('%s');
} else {
messages.push('%O');
}
},[]);
},
/**
* Default print function to show context messages
*/
$print: function(context,args,error,color){
var me = this,
base = context.getCalledKlass(),
contextName = base ? base.getName() : CONSTANTS.LOGGER.UNKNOWN_NAME,
methodName = context.getCalledName() || CONSTANTS.LOGGER.ANONYMOUS_NAME,
messages = me.toMessages(args);
color = color || (error ? CONSTANTS.LOGGER.EXCEPTION_COLOR : CONSTANTS.LOGGER.SUCCESS_COLOR);
if (context) {
if (context.deepLoggingLevel || methodName == CONSTANTS.LOGGER.ANONYMOUS_NAME) {
var deepTrace = me.analyze(context);
console.groupCollapsed.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args));
console.log(('[node-klass-logger] ' + deepTrace)[color]);
console.groupEnd();
} else {
console.log.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args));
}
} else {
console.log.apply(console,[('[node-klass-logger]' + messages.join(' '))[color]].concat(args));
}
},
print: function(context,args,error){
this.$print(context,[].concat(':',args),error,CONSTANTS.LOGGER.USER_COLOR);
}
});
return new KlassLogger();
})(
require('../common/forEach'),
require('../common/extend'),
require('../common/printf'),
require('../Constants'),
require('colors')
); |
function each(values, fn, cb) {
var n = 0;
doStep();
function doStep() {
if (n >= values.length)
return cb(null, null);
try {
fn(values[n++], function (err, data) {
if (err)
return cb(err, null);
setImmediate(doStep);
});
}
catch (err) {
cb(err, null);
}
}
}
module.exports = each
|
var ARTICLES_URL = '/api/articles/all';
var ARTICLE_AUTHOR_URL = '/api/articles/author/';
var Article = React.createClass({displayName: "Article",
getMeta: function () {
if (this.state.author == {}) {
return 'Loading ...';
}
if (null != this.state.author.first_name && null != this.state.author.last_name) {
var name = this.state.author.first_name + ' ' + this.state.author.last_name;
} else {
var name = this.state.author.username;
}
return 'by <a href="/profiles/' + this.state.author.username + '">' + name + '</a> : ' + moment(this.props.article.pub_date).format('MMMM Do YYYY, h:mm a');
},
getTruncatedContent: function () {
var n = 150;
var string = this.props.article.content;
var toLong = string.length > n, s_ = toLong ? string.substr(0, n-1) : string;
s_ = toLong ? s_.substr(0, s_.lastIndexOf(' ')) : s_;
return toLong ? s_ + ' ...' : s_;
},
getInitialState: function () {
return {author: {}};
},
componentDidMount: function () {
$.ajax({
url: ARTICLE_AUTHOR_URL + this.props.article.author,
dataType: 'json',
success: function (author) {
this.setState({author: author});
}.bind(this),
error: function (xhr, status, err) {
console.error(ARTICLE_AUTHOR_URL + this.props.article.author, status, err.toString())
}.bind(this)
});
},
render: function () {
var article_link = '/articles/' + this.props.article.id;
return (
React.createElement("div", null,
React.createElement("hr", null),
React.createElement("h3", {className: "article-title"}, React.createElement("a", {href: article_link}, this.props.article.title)),
React.createElement("p", {className: "article-meta", dangerouslySetInnerHTML: {__html: this.getMeta()}}),
React.createElement("p", {className: "article-content-preview"}, React.createElement("a", {href: article_link}, this.getTruncatedContent()))
)
);
}
});
var EmptyArticlesView = React.createClass({displayName: "EmptyArticlesView",
render: function () {
return (
React.createElement("div", null,
React.createElement("h3", null, "There’s nothing here."),
React.createElement("a", {className: "with-space", href: "/articles/write"}, "Write an article!")
)
);
}
});
var ArticleList = React.createClass({displayName: "ArticleList",
loadArticlesFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (articles) {
this.setState({articles: articles})
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function () {
return {
articles: []
};
},
componentDidMount: function () {
this.loadArticlesFromServer();
setInterval(this.loadArticlesFromServer, 2000);
},
render: function () {
var articles = [];
var filterText = this.props.filterText.toLowerCase();
this.state.articles.forEach(function (article) {
if (article.title.toLowerCase().indexOf(filterText) === -1 && article.content.toLowerCase().indexOf(filterText) === -1) {
return;
}
articles.push(React.createElement(Article, {article: article}));
}.bind(this));
if (articles.length) {
return (
React.createElement("div", {className: "col-xs-10 col-xs-offset-1 col-md-6 col-md-offset-1 card"},
React.createElement("h1", {className: "left"}, "Latest Articles"),
articles
)
);
} else {
return (
React.createElement("div", {className: "col-xs-10 col-xs-offset-1 col-md-6 col-md-offset-1 card"},
React.createElement("h1", {className: "left"}, "Latest Articles"),
React.createElement("hr", null),
React.createElement(EmptyArticlesView, null)
)
);
}
}
});
var SearchCard = React.createClass({displayName: "SearchCard",
handleChange: function () {
this.props.onSearch(this.refs.filterTextInput.getDOMNode().value);
},
render: function () {
return (
React.createElement("div", {className: "col-xs-10 col-xs-offset-1 col-md-3 col-md-offset-1 card"},
React.createElement("h3", {className: "left"}, "Search"),
React.createElement("div", {className: "input-group with-space padding-bottom-20"},
React.createElement("input", {type: "text", value: this.props.filterText, ref: "filterTextInput", className: "form-control", placeholder: "Search ...", onChange: this.handleChange}),
React.createElement("span", {className: "input-group-btn"},
React.createElement("button", {className: "btn btn-default", type: "button"},
React.createElement("span", {className: "glyphicon glyphicon-search"})
)
)
)
)
);
}
});
var CategoriesCard = React.createClass({displayName: "CategoriesCard",
render: function () {
var categories = this.props.categories.map(function (category) {
return (React.createElement("li", null, category));
});
return (
React.createElement("div", {className: "col-xs-10 col-xs-offset-1 col-md-3 col-md-offset-1 card"},
React.createElement("h3", {className: "left"}, "Categories"),
React.createElement("ul", null, categories)
)
);
}
});
var ArticlesSection = React.createClass({displayName: "ArticlesSection",
getInitialState: function () {
return {
filterText: '',
category: 'any'
};
},
handleSearch: function (filterText) {
this.setState({
filterText: filterText
});
},
handleCategoryChange: function (category) {
this.setState({
category: category
})
},
render: function () {
return (
React.createElement("div", {class: "row"},
React.createElement(ArticleList, {
category: this.state.category,
filterText: this.state.filterText,
url: this.props.url}),
React.createElement(SearchCard, {
onSearch: this.handleSearch,
filterText: this.state.filterText}),
React.createElement(CategoriesCard, {
onCategoryChange: this.handleCategoryChange,
categories: this.props.categories})
)
);
}
});
var CATEGORIES = [
'Education', 'Science & Technology', 'News & Politics'
];
React.render(React.createElement(ArticlesSection, {url: ARTICLES_URL, categories: CATEGORIES}), document.getElementById('content')); |
/*jslint browser: true, sloppy: true */
var UNIVERSE = UNIVERSE || {};
UNIVERSE.LLACoordinates = function (lat, lon, alt) {
// define variables as <var name>: <value>
this.latitude = lat || 0.0; //deg
this.longitude = lon || 0.0; //deg
this.altitude = alt || 0.0; //km
/**
* Returns the altitude value.
*/
this.getAltitude = function () {
return this.altitude;
};
/**
* Sets a new altitude value.
*/
this.setAltitude = function (newAltitude) {
this.altitude = newAltitude;
};
/**
* Returns the latitude value.
*/
this.getLatitude = function () {
return this.latitude;
};
/**
* Sets a new latitude value.
*/
this.setLatitude = function (newLatitude) {
this.latitude = newLatitude;
};
/**
* Returns the longitude value.
*/
this.getLongitude = function () {
return this.longitude;
};
/**
* Sets a new longitude value.
*/
this.setLongitude = function (setLongitude) {
this.longitude = setLongitude;
};
}; |
function LogoutCtrl ($rootScope, $state) {
// console.log('Entering LogoutCtrl....');
$rootScope.session = {};
$rootScope.session.apiReload = true;
$rootScope.session.apiOffset = 0;
$state.go('login');
}
angular.module('pfApp.controllers')
.controller('LogoutCtrl', LogoutCtrl);
|
import React from 'react';
import loadScript from 'load-script2';
import CircularProgress from '@material-ui/core/CircularProgress';
import InternalCaptcha from './ReCaptcha';
const GRECAPTCHA_API = 'https://www.google.com/recaptcha/api.js';
const onloadCallbackName = 'grecaptchaOnload__$';
const onloadCallbacks = [];
function loadReCaptcha(cb) {
loadScript(`${GRECAPTCHA_API}?onload=${onloadCallbackName}&render=explicit`);
onloadCallbacks.push(cb);
}
function onload() {
onloadCallbacks.forEach(fn => fn(window.grecaptcha));
}
export default class ReCaptcha extends React.Component {
state = {
grecaptcha: window.grecaptcha,
};
componentDidMount() {
const { grecaptcha } = this.state;
if (!grecaptcha) {
this.load();
}
}
load() {
if (typeof window[onloadCallbackName] !== 'function') {
window[onloadCallbackName] = onload;
}
loadReCaptcha((grecaptcha) => {
this.setState({ grecaptcha });
});
}
render() {
const { grecaptcha } = this.state;
if (!grecaptcha) {
return <CircularProgress className="ReCaptcha-spinner" />;
}
return (
<InternalCaptcha
{...this.props}
grecaptcha={grecaptcha}
/>
);
}
}
|
window.onload = function(){
var randNum = parseInt(10*Math.random());
var gameContainer = document.getElementById('game');
while (guess !== randNum) {
var guess = prompt("Guess a number from 1 to 10!");
if (guess == randNum){
gameContainer.innerHTML = 'you are correct!';
break
}
else if (guess > randNum){
gameContainer.innerHTML = 'too high';
}
else {
gameContainer.innerHTML = 'too low';
}
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:db04eefcbca2fe2bd4778544880dc438773bcabf75737213900e56dee0772412
size 21916
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.