code stringlengths 2 1.05M |
|---|
/* eslint no-console: ["error", { allow: ["log"] }] */
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config';
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
contentBase: __dirname,
stats: {
colors: true,
},
}).listen(3000, 'localhost', (err) => {
if (err) console.log(err);
console.log('Listening at localhost:3000');
});
|
import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import ScrollResponder from '../mixins/ScrollResponder';
import TimerMixin from 'react-timer-mixin';
import ScrollView from './ScrollView';
import ListViewDataSource from '../api/ListViewDataSource';
const SCROLLVIEW_REF = 'listviewscroll';
const ListView = createReactClass({
displayName: 'ListView',
propTypes: {
...ScrollView.propTypes,
dataSource: PropTypes.instanceOf(ListViewDataSource).isRequired,
/**
* (sectionID, rowID, adjacentRowHighlighted) => renderable
*
* If provided, a renderable component to be rendered as the separator
* below each row but not the last row if there is a section header below.
* Take a sectionID and rowID of the row above and whether its adjacent row
* is highlighted.
*/
renderSeparator: PropTypes.func,
/**
* (rowData, sectionID, rowID, highlightRow) => renderable
*
* Takes a data entry from the data source and its ids and should return
* a renderable component to be rendered as the row. By default the data
* is exactly what was put into the data source, but it's also possible to
* provide custom extractors. ListView can be notified when a row is
* being highlighted by calling highlightRow function. The separators above and
* below will be hidden when a row is highlighted. The highlighted state of
* a row can be reset by calling highlightRow(null).
*/
renderRow: PropTypes.func.isRequired,
/**
* How many rows to render on initial component mount. Use this to make
* it so that the first screen worth of data appears at one time instead of
* over the course of multiple frames.
*/
initialListSize: PropTypes.number,
/**
* Called when all rows have been rendered and the list has been scrolled
* to within onEndReachedThreshold of the bottom. The native scroll
* event is provided.
*/
onEndReached: PropTypes.func,
/**
* Threshold in pixels for onEndReached.
*/
onEndReachedThreshold: PropTypes.number,
/**
* Number of rows to render per event loop.
*/
pageSize: PropTypes.number,
/**
* () => renderable
*
* The header and footer are always rendered (if these props are provided)
* on every render pass. If they are expensive to re-render, wrap them
* in StaticContainer or other mechanism as appropriate. Footer is always
* at the bottom of the list, and header at the top, on every render pass.
*/
renderFooter: PropTypes.func,
renderHeader: PropTypes.func,
/**
* (sectionData, sectionID) => renderable
*
* If provided, a sticky header is rendered for this section. The sticky
* behavior means that it will scroll with the content at the top of the
* section until it reaches the top of the screen, at which point it will
* stick to the top until it is pushed off the screen by the next section
* header.
*/
renderSectionHeader: PropTypes.func,
/**
* (props) => renderable
*
* A function that returns the scrollable component in which the list rows
* are rendered. Defaults to returning a ScrollView with the given props.
*/
renderScrollComponent: PropTypes.func.isRequired,
/**
* How early to start rendering rows before they come on screen, in
* pixels.
*/
scrollRenderAheadDistance: PropTypes.number,
/**
* (visibleRows, changedRows) => void
*
* Called when the set of visible rows changes. `visibleRows` maps
* { sectionID: { rowID: true }} for all the visible rows, and
* `changedRows` maps { sectionID: { rowID: true | false }} for the rows
* that have changed their visibility, with true indicating visible, and
* false indicating the view has moved out of view.
*/
onChangeVisibleRows: PropTypes.func,
/**
* A performance optimization for improving scroll perf of
* large lists, used in conjunction with overflow: 'hidden' on the row
* containers. This is enabled by default.
*/
removeClippedSubviews: PropTypes.bool,
/**
* An array of child indices determining which children get docked to the
* top of the screen when scrolling. For example, passing
* `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the
* top of the scroll view. This property is not supported in conjunction
* with `horizontal={true}`.
* @platform ios
*/
stickyHeaderIndices: PropTypes.arrayOf(PropTypes.number),
},
mixins: [ScrollResponder.Mixin, TimerMixin],
statics: {
DataSource: ListViewDataSource,
},
/**
* Exports some data, e.g. for perf investigations or analytics.
*/
getMetrics() { // eslint-disable-line react/sort-comp
// It's fixed, but the linter doesnt want to recognise it...
return {
contentLength: this.scrollProperties.contentLength,
totalRows: this.props.dataSource.getRowCount(),
renderedRows: this.state.curRenderedRowsCount,
visibleRows: Object.keys(this._visibleRows).length,
};
},
scrollTo(destY, destX) {
this.getScrollResponder().scrollResponderScrollTo(destX || 0, destY || 0);
},
/**
* Provides a handle to the underlying scroll responder to support operations
* such as scrollTo.
*/
getScrollResponder() {
return this.refs[SCROLLVIEW_REF] &&
this.refs[SCROLLVIEW_REF].getScrollResponder &&
this.refs[SCROLLVIEW_REF].getScrollResponder();
},
setNativeProps(props) {
this.refs[SCROLLVIEW_REF].setNativeProps(props);
},
getDefaultProps() {
return {
renderScrollComponent: (props) => <ScrollView {...props} />
};
},
getInnerViewNode() {
return this.refs[SCROLLVIEW_REF].getInnerViewNode();
},
render() {
return React.createElement('react-native-mock', null, this.props.children);
},
});
module.exports = ListView;
|
const express = require('express');
const api = require('./api/api');
const app = express();
app.get('/', async function (req, res) {
//aqui deveria imprimir por exemplo {'nome':'brl', valor: 1}
let cot = await api.getmoeda('brl');
//só pro exemplo
res.send(cot);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
|
var express = require('express');
var Url = require('../models/Url');
var router = express.Router();
var urls = require('./api/urls');
var shortens = require('./api/shortens');
// This allow anyone to contact the API
router.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
router.get('/', function(req, res) {
var token;
var authorization = req.get('Authorization');
if(authorization) {
token = /\s*token\s+(.*)$/.exec(authorization);
} else {
token = req.params.access_token;
}
//TODO: handle the authentication to the API
// https://developer.github.com/v3/#authentication
// https://stormpath.com/blog/the-problem-with-api-authentication-in-express/
});
// TODO : Adding tokens for external user to use API
router.get('/hello', function(req, res) {
res.json({'hello' : 'world !'});
});
router.use('/urls', urls);
router.use('/shortens', shortens);
module.exports = router;
|
angular.module('conapps').directive('merakiProductCard', function(){
return {
restrict: 'E',
replace: true,
templateUrl: 'meraki-estimates/client/views/meraki-product-card.template.ng.html',
scope: {
product: '=',
},
controller: ['merakiProductService', 'showModal', function(merakiProductService, showModal){
var deleteBootboxDialog = {
message: '¿Esta seguro que desea eliminar este producto?',
title: 'Eliminar Producto',
buttons: {
confirm: {
label: 'Aceptar',
className: 'btn-primary',
callback: function() {
merakiProductService.deleteProduct(this.product._id)
.then(function(){ toastr.success('Producto eliminado', 'Exito!'); })
.catch(function(){ toastr.error('Ha ocurrido un error inesperado', 'Error!') });
}.bind(this)
},
cancel: {
label: 'Cancelar',
className: 'btn-default',
}
}
};
this.editProduct = function(){
merakiProductService.setProduct(this.product);
showModal('#productListModalForm');
}
this.deleteProduct = function(){
bootbox.dialog(deleteBootboxDialog);
}
this.isAdmin = App.auth.isAdmin;
}],
controllerAs: 'vm',
bindToController: true,
}
});
|
define(function(){
var Utils = {
randBetween: function(min, max) {
return Math.floor(Math.random() * max) + min;
},
doOperation: function(firstValue, operator, secondValue, reverse){
if(reverse) {
switch(operator){
case '+':
return firstValue - secondValue;
case '*':
return Math.round(firstValue / secondValue);
case '-':
return firstValue + secondValue;
case '/':
return Math.round(firstValue * secondValue);
case '=':
console.log('= cannot be reversed');
return firstValue;
default:
console.log(operator+' is an unknown operator');
return firstValue;
}
} else {
switch(operator){
case '+':
return firstValue + secondValue;
case '*':
return Math.round(firstValue * secondValue);
case '-':
return firstValue - secondValue;
case '/':
return Math.round(firstValue / secondValue);
case '=':
return secondValue;
default:
return operator+' is an unknown operation';
}
}
},
modifyProperty: function(object, propertyName, changes, reverse) {
var property = object.get(propertyName);
function getNewValue(startingValue, change){
if($.isArray(change)){
return Utils.doOperation(startingValue, change[0], change[1], reverse);
} else {
return change;
}
}
function getNewNestedValue(property, changes){
var returnObject = {};
if(!property){
returnObject = getNewValue(0, changes);
} else if($.isPlainObject(changes)){
_.each(changes, function(value, name){
returnObject[name] = getNewNestedValue(property[name], value);
});
} else {
returnObject = getNewValue(property, changes);
}
return returnObject;
}
if (property) {
if($.isPlainObject(changes)){
object.set(propertyName, getNewNestedValue(property, changes));
} else {
object.set(propertyName, getNewValue(property, changes));
}
} else {
object.set(propertyName, getNewValue(0, changes));
}
},
reversePropertyModification: function(object, propertyName, changes){
this.modifyProperty(object, propertyName, changes, reverse);
},
shouldObjectBeUnlocked: function(object, type){
if(_.isEmpty(object.get('prereqs')[type])) {
delete object.get('prereqs')[type];
if(_.isEmpty(object.get('prereqs'))) {
return true;
}
}
object.save();
return false;
},
shouldObjectBeRelocked: function(object, type) {
if(_.isEmpty(object.get('postreqs')[type])) {
delete object.get('postreqs')[type];
if(_.isEmpty(object.get('postreqs'))) {
return true;
}
}
object.save();
return false;
}
};
return Utils;
}); |
const util = require('util');
function Person(name) {
this.name = name;
}
Person.prototype.eat = function () {
console.log(this.name,'吃');
}
function Teacher(name) {
this.name = name;
}
// 原型继承,只继承prototype上的方法,不继承私有属性
util.inherits(Teacher , Person);
// Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
// setPrototypeOf方法原理
/*function setPrototypeOf(cPrototype , superPrototype) {
function Temp() {}
Temp.prototype = new superPrototype();
cPrototype = new Temp();
}*/
var t = new Teacher('hello');
t.eat();
|
/**
* steel file for cli-version
* author: @Lonefy
*/
var path = require('path');
var steel = require('steel-commander');
steel.config({
port: 80,
pathnamePrefix: '/t6/apps/weibo_sell/',
cssPostfix_option: ["pages/*.*"],
front_base: 'server_front',
front_hostname: 'js.t.sinajs.cn img.t.sinajs.cn',
back_base: 'server_back', //模拟后端的文件放置目录
back_hostname: 'shop.sc.weibo.com shop1.sc.weibo.com', //后端的HOST,目的是真实模拟后端的页面路由请求,提供出前端可仿真的功能,比如 /index 对应 /html/index.html
jsFilter_of_lib: ['js/lib/zepto.js'],
cssBase: "css/",
jsBase: "js/",
version: '0.1.1'
})
steel.task("hw", function(){
console.log("hello world, Steel v0.1.1");
})
|
'use strict'
describe('routes', () => {
describe('article route', () => {
const test = require('./routes/article')
it('returns a set of popular topics based on the number of articles flagged', test['failFirst'])
it('returns 204 (no data) when no id is given', test['204'])
it('returns 204 (no data) when a bad id given', test['badRequest'])
it('returns JSON object', test['json'])
it('JSON object is a article object', test['hasProperties'])
it('returns the 20 most recent articles on a request to recent', test['recent'])
})
})
|
angular.module('database', []); |
// create a namespace we will use for everything we do
let αω = {};
let ΑΩ = αω;
|
#!/usr/bin/env node
const STD_PORT = 3000;
var path = require('path'),
cmdline = require('commander'),
pkg = require(path.join(__dirname, '/package.json')),
express = require('express'),
app = express();
cmdline.version(pkg.version)
.option(`-p, --port <port number>', 'The server port (optional, default: ${STD_PORT})`)
.option('-d, --debug', 'Starts the server in debug mode (optional')
.parse(process.argv);
if (cmdline.debug === true) {
console.log('server mode: debug');
}
app.use(express.static(path.join(__dirname, '/public')));
app.use('/node_modules', express.static(path.join(__dirname, '/node_modules')));
app.listen((cmdline.port || STD_PORT), function() {
console.log(`Server listening on port ${cmdline.port || STD_PORT}`);
}); |
import Multiselect from 'vue-multiselect';
import { library, dom } from '@fortawesome/fontawesome-svg-core';
import {
faFacebookSquare,
faGithub,
faHtml5,
faLaravel,
faOrcid,
faVuejs
} from '@fortawesome/free-brands-svg-icons';
import {
faClipboard,
faQuestionCircle
} from '@fortawesome/free-regular-svg-icons';
import {
faAdjust,
faAngleDoubleLeft,
faAngleDoubleRight,
faAngleDown,
faAngleLeft,
faAngleRight,
faAngleUp,
faBan,
faBell,
faBinoculars,
faBolt,
faBook,
faBookmark,
faCalculator,
faCalendarAlt,
faCamera,
faCaretDown,
faCaretUp,
faChartBar,
faChartPie,
faCheck,
faCheckCircle,
faCircle,
faClock,
faClone,
faCog,
faCogs,
faComment,
faComments,
faCopy,
faCopyright,
faCubes,
faDotCircle,
faDownload,
faDrawPolygon,
faEdit,
faEllipsisH,
faEnvelope,
faExchangeAlt,
faExclamation,
faExclamationCircle,
faExpand,
faExternalLinkAlt,
faEyeSlash,
faFile,
faFileAlt,
faFileArchive,
faFileAudio,
faFileCode,
faFileDownload,
faFileExcel,
faFileExport,
faFileImport,
faFileMedicalAlt,
faFilePdf,
faFilePowerpoint,
faFileUpload,
faFileVideo,
faFileWord,
faFolder,
faGlobeAfrica,
faIdBadge,
faInfoCircle,
faLayerGroup,
faLightbulb,
faLink,
faList,
faLongArrowAltDown,
faLongArrowAltLeft,
faLongArrowAltRight,
faLongArrowAltUp,
faMagic,
faMapMarkedAlt,
faMapMarkerAlt,
faMicrochip,
faMobileAlt,
faMonument,
faPalette,
faPaperPlane,
faPause,
faPaw,
faPlay,
faPlus,
faPrint,
faQuestion,
faRedoAlt,
faReply,
faRoad,
faRuler,
faRulerCombined,
faSave,
faSearch,
faSearchPlus,
faShieldAlt,
faSignOutAlt,
faSitemap,
faSlidersH,
faSort,
faSortAlphaDown,
faSortAlphaUp,
faSortAmountDown,
faSortAmountUp,
faSortDown,
faSortNumericDown,
faSortNumericUp,
faSortUp,
faSpinner,
faStop,
faStopwatch,
faSun,
faSync,
faTable,
faTags,
faTasks,
faTh,
faTimes,
faTrash,
faUnderline,
faUndo,
faUndoAlt,
faUnlink,
faUnlockAlt,
faUser,
faUserClock,
faUserCheck,
faUserCog,
faUserEdit,
faUsers,
faUserTimes,
faVolumeMute,
faVolumeUp,
faDatabase,
faIndent
} from '@fortawesome/free-solid-svg-icons';
import VModal from 'vue-js-modal';
import Axios from 'axios';
import VueRouter from 'vue-router';
import auth from '@websanova/vue-auth';
import authBearer from '@websanova/vue-auth/drivers/auth/bearer.js';
import authHttp from './queued-axios-1.x-driver.js';
import authRouter from '@websanova/vue-auth/drivers/router/vue-router.2.x.js';
import VueI18n from 'vue-i18n';
import en from './i18n/en';
import de from './i18n/de';
import App from './App.vue';
import Login from './components/Login.vue';
const MainView = () => import(/* webpackChunkName: "group-main" */ './components/MainView.vue')
const EntityDetail = () => import(/* webpackChunkName: "group-main" */ './components/EntityDetail.vue')
const ReferenceModal = () => import(/* webpackChunkName: "group-main" */ './components/EntityReferenceModal.vue')
// Tools
const Bibliography = () => import(/* webpackChunkName: "group-bib" */ './components/BibliographyTable.vue')
const BibliographyItemModal = () => import(/* webpackChunkName: "group-bib" */ './components/BibliographyItemModal.vue')
// Settings
import Users from './components/Users.vue';
import Roles from './components/Roles.vue';
import Preferences from './components/Preferences.vue';
import UserPreferences from './components/UserPreferences.vue';
import UserNotifications from './components/UserNotifications.vue';
import UserActivity from './components/UserActivity.vue';
import GlobalActivity from './components/GlobalActivity.vue';
import UserProfile from './components/UserProfile.vue';
const DataModel = () => import(/* webpackChunkName: "group-bib" */ './components/DataModel.vue')
const DataModelDetailView = () => import(/* webpackChunkName: "group-bib" */ './components/DataModelDetailView.vue')
import VueUploadComponent from 'vue-upload-component';
import * as dayjs from 'dayjs';
import DatePicker from 'vue2-datepicker';
import VeeValidate from 'vee-validate';
import Notifications from 'vue-notification';
import SpacialistPluginSystem from './plugin.js';
import VueScrollTo from 'vue-scrollto';
import InfiniteLoading from 'vue-infinite-loading';
import VueHighlightJS from 'vue-highlightjs';
import 'highlight.js/styles/atom-one-dark.css';
import { EventBus } from './event-bus.js';
library.add(
faFacebookSquare,
faGithub,
faHtml5,
faLaravel,
faVuejs,
faClipboard,
faQuestionCircle,
faAdjust,
faAngleDoubleLeft,
faAngleDoubleRight,
faAngleDown,
faAngleLeft,
faAngleRight,
faAngleUp,
faBan,
faBell,
faBinoculars,
faBolt,
faBook,
faBookmark,
faCalculator,
faCalendarAlt,
faCamera,
faCaretDown,
faCaretUp,
faChartBar,
faChartPie,
faCheck,
faCheckCircle,
faCircle,
faClock,
faClone,
faCog,
faCogs,
faComment,
faComments,
faCopy,
faCopyright,
faCubes,
faDatabase,
faDotCircle,
faDownload,
faDrawPolygon,
faEdit,
faEllipsisH,
faEnvelope,
faExchangeAlt,
faExclamation,
faExclamationCircle,
faExpand,
faExternalLinkAlt,
faEyeSlash,
faFile,
faFileAlt,
faFileArchive,
faFileAudio,
faFileCode,
faFileDownload,
faFileExcel,
faFileExport,
faFileImport,
faFileMedicalAlt,
faFilePdf,
faFilePowerpoint,
faFileUpload,
faFileVideo,
faFileWord,
faFolder,
faGlobeAfrica,
faIdBadge,
faIndent,
faInfoCircle,
faLayerGroup,
faLightbulb,
faLink,
faList,
faLongArrowAltDown,
faLongArrowAltLeft,
faLongArrowAltRight,
faLongArrowAltUp,
faMagic,
faMapMarkedAlt,
faMapMarkerAlt,
faMicrochip,
faMobileAlt,
faMonument,
faOrcid,
faPalette,
faPaperPlane,
faPause,
faPaw,
faPlay,
faPlus,
faPrint,
faQuestion,
faQuestionCircle,
faRedoAlt,
faReply,
faRoad,
faRuler,
faRulerCombined,
faSave,
faSearch,
faSearchPlus,
faShieldAlt,
faSignOutAlt,
faSitemap,
faSlidersH,
faSort,
faSortAlphaDown,
faSortAlphaUp,
faSortAmountDown,
faSortAmountUp,
faSortDown,
faSortNumericDown,
faSortNumericUp,
faSortUp,
faSpinner,
faStop,
faStopwatch,
faSun,
faSync,
faTable,
faTags,
faTasks,
faTh,
faTimes,
faTrash,
faUnderline,
faUndo,
faUndoAlt,
faUnlink,
faUnlockAlt,
faUser,
faUserClock,
faUserCheck,
faUserCog,
faUserEdit,
faUserTimes,
faUsers,
faVolumeMute,
faVolumeUp
);
dom.watch(); // search for <i> tags to replace with <svg>
// Override vue-routers push method to catch (and "suppress") it's errors
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
if(onResolve || onReject) {
return originalPush.call(this, location, onResolve, onReject);
}
return originalPush.call(this, location)
.catch(err =>
console.log("Error while pushing new route")
);
}
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
const {default: PQueue} = require('p-queue');
require('typeface-raleway');
require('typeface-source-code-pro');
require('popper.js');
require('bootstrap');
window.Vue = require('vue');
window._clone = require('lodash/clone');
window._cloneDeep = require('lodash/cloneDeep');
window._orderBy = require('lodash/orderBy');
window._debounce = require('lodash/debounce');
$ = jQuery = window.$ = window.jQuery = require('jquery');
require('./globals.js');
let relativeTime = require('dayjs/plugin/relativeTime');
let utc = require('dayjs/plugin/utc')
dayjs.extend(relativeTime);
dayjs.extend(utc);
// Create Axios instance for external (API) calls
Vue.prototype.$externalHttp = Axios.create({
headers: {
common: {},
},
});
Axios.defaults.baseURL = 'api/v1';
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.queue = Vue.prototype.$httpQueue = window.$httpQueue = new PQueue({concurrency: 1});
Vue.prototype.$http = Axios;
Vue.axios = Axios;
Vue.use(VueRouter);
Vue.use(SpacialistPluginSystem);
Vue.use(VueI18n);
Vue.use(VModal, {dynamic: true});
Vue.use(VeeValidate);
Vue.use(Notifications);
Vue.use(DatePicker);
Vue.use(VueScrollTo);
Vue.use(InfiniteLoading);
Vue.use(VueHighlightJS);
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
return {
x: 0,
y: 0
};
},
routes: [
// deprecated pre-0.6 routes
{
path: '/s',
redirect: { name: 'home' },
children: [
{
path: 'context/:id',
redirect: to => {
return {
name: 'entitydetail',
params: {
id: to.params.id
}
}
},
children: [{
path: 'sources/:aid',
redirect: to => {
return {
name: 'entityrefs',
params: {
id: to.params.id,
aid: to.params.aid,
}
}
}
}]
},
{
path: 'f/:id',
redirect: to => {
return {
name: 'file',
params: {
id: to.params.id
}
}
}
},
{
path: 'user',
redirect: { name: 'users' },
// TODO user edit route (redirect to users or add it)
},
{
path: 'role',
redirect: { name: 'roles' },
// TODO role edit route (redirect to roles or add it)
},
{
path: 'editor/data-model',
redirect: { name: 'dme' },
children: [{
path: 'contexttype/:id',
redirect: to => {
return {
name: 'dmdetail',
params: {
id: to.params.id
}
}
}
}]
},
{
path: 'preferences/:id',
redirect: to => {
return {
name: 'userpreferences',
params: {
id: to.params.id
}
}
}
}
]
},
{
path: '/',
name: 'home',
component: MainView,
children: [
{
path: 'e/:id',
name: 'entitydetail',
component: EntityDetail,
children: [
{
path: 'refs/:aid',
name: 'entityrefs',
component: ReferenceModal
}
]
}
],
meta: {
auth: true
}
},
// Tools
{
path: '/bibliography',
name: 'bibliography',
component: Bibliography,
children: [
{
path: 'edit/:id',
name: 'bibedit',
component: BibliographyItemModal
},
{
path: 'new',
name: 'bibnew',
component: BibliographyItemModal
}
],
meta: {
auth: true
}
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
auth: false
}
},
// Settings
{
path: '/mg/users',
name: 'users',
component: Users,
meta: {
auth: true
}
},
{
path: '/mg/roles',
name: 'roles',
component: Roles,
meta: {
auth: true
}
},
{
path: '/activity/g',
name: 'globalactivity',
component: GlobalActivity,
meta: {
auth: true
}
},
{
path: '/editor/dm',
name: 'dme',
component: DataModel,
children: [
{
path: 'et/:id',
name: 'dmdetail',
component: DataModelDetailView
}
],
meta: {
auth: true
}
},
{
path: '/preferences',
name: 'preferences',
component: Preferences,
meta: {
auth: true
}
},
{
path: '/preferences/u/:id',
name: 'userpreferences',
component: UserPreferences,
meta: {
auth: true
}
},
{
path: '/notifications/:id',
name: 'notifications',
component: UserNotifications,
meta: {
auth: true
}
},
{
path: '/activity/u',
name: 'useractivity',
component: UserActivity,
meta: {
auth: true
}
},
{
path: '/profile',
name: 'userprofile',
component: UserProfile,
meta: {
auth: true
}
},
]
});
// Workaround to load plugin pages, whose routes
// are loaded after the initial page load
router.onReady(() => {
const matchedComponents = router.getMatchedComponents(router.history.current.fullPath);
if(matchedComponents.length == 1) {
router.push(router.history.current.fullPath);
}
});
Vue.router = router;
App.router = Vue.router;
Axios.interceptors.response.use(response => {
return response;
}, error => {
const code = error.response.status;
switch(code) {
case 401:
let redirectQuery = {};
// Only append redirect query if from another route than login
// to prevent recursivly appending current route's full path
// on reloading login page
if(Vue.router.currentRoute.name != 'login') {
redirectQuery.redirect = Vue.router.currentRoute.fullPath;
}
Vue.auth.logout({
redirect: {
name: 'login',
query: redirectQuery
}
});
break;
case 400:
case 422:
// don't do anything. Handle these types at caller
break;
default:
Vue.prototype.$throwError(error);
break;
}
return Promise.reject(error);
});
const messages = {
en: en,
de: de
};
const i18n = new VueI18n({
locale: navigator.language,
fallbackLocale: 'en',
messages
});
Vue.i18n = i18n;
Vue.use(auth, {
auth: authBearer,
http: authHttp,
router: authRouter,
forbiddenRedirect: {
name: 'home'
},
notFoundRedirect: {
name: 'home'
},
});
// Imported Components
Vue.component('multiselect', Multiselect);
Vue.component('file-upload', VueUploadComponent);
// Extended Components
import GlobalSearch from './components/GlobalSearch.vue';
import EntitySearch from './components/EntitySearch.vue';
import EntityTypeSearch from './components/EntityTypeSearch.vue';
import LabelSearch from './components/LabelSearch.vue';
import AttributeSearch from './components/AttributeSearch.vue';
import CsvTable from './components/CsvTable.vue';
// Reusable Components
import ActivityLog from './components/ActivityLog.vue';
import ActivityLogFilter from './components/ActivityLogFilter.vue';
import UserAvatar from './components/UserAvatar.vue';
import Attributes from './components/AttributeList.vue';
import EntityTree from './components/EntityTree.vue';
import EntityTypes from './components/EntityTypeList.vue';
import OlMap from './components/OlMap.vue';
import ColorGradient from './components/Gradient.vue';
import EntityBreadcrumbs from './components/EntityBreadcrumbs.vue';
import CommentList from './components/CommentList.vue';
import NotificationBody from './components/NotificationBody.vue';
import EmojiPicker from './components/EmojiPicker.vue';
// Page Components
import EntityReferenceModal from './components/EntityReferenceModal.vue';
import DiscardChangesModal from './components/DiscardChangesModal.vue';
import AboutDialog from './components/About.vue';
import ErrorModal from './components/Error.vue';
import UserInfoModal from './components/modals/UserInfo.vue';
Vue.component('global-search', GlobalSearch);
Vue.component('entity-search', EntitySearch);
Vue.component('entity-type-search', EntityTypeSearch);
Vue.component('label-search', LabelSearch);
Vue.component('attribute-search', AttributeSearch);
Vue.component('csv-table', CsvTable);
Vue.component('activity-log', ActivityLog);
Vue.component('activity-log-filter', ActivityLogFilter);
Vue.component('user-avatar', UserAvatar);
Vue.component('attributes', Attributes);
Vue.component('entity-tree', EntityTree);
Vue.component('entity-types', EntityTypes);
Vue.component('ol-map', OlMap);
Vue.component('color-gradient', ColorGradient);
Vue.component('entity-breadcrumbs', EntityBreadcrumbs);
Vue.component('comment-list', CommentList);
Vue.component('notification-body', NotificationBody);
Vue.component('emoji-picker', EmojiPicker);
Vue.component('entity-reference-modal', EntityReferenceModal);
Vue.component('discard-changes-modal', DiscardChangesModal);
Vue.component('about-dialog', AboutDialog);
Vue.component('error-modal', ErrorModal);
Vue.component('user-info-modal', UserInfoModal);
// Filter
Vue.filter('date', function(value, format = 'DD.MM.YYYY HH:mm') {
if(value) {
let d;
if(isNaN(value)) {
d = dayjs.utc(value);
} else {
d = dayjs.utc(value*1000);
}
return d.format(format);
}
});
Vue.filter('datestring', function(value) {
if(value) {
const d = isNaN(value) ? dayjs.utc(value) : dayjs.utc(value*1000);
return d.toDate().toString();
}
});
Vue.filter('ago', function(value) {
if(value) {
let d;
if(isNaN(value)) {
d = dayjs.utc(value);
} else {
d = dayjs.utc(value*1000);
}
return d.fromNow();
}
});
Vue.filter('numPlus', function(value, length = 2) {
if(value) {
const v = Math.floor(value);
const max = Math.pow(10, length) - 1;
if(v > max) return `${max.toString(10)}+`;
else return v;
} else {
return value;
}
});
Vue.filter('time', function(value, withHours) {
if(value) {
let hours = 0;
let rHours = 0;
if(withHours) {
hours = parseInt(Math.floor(value / 3600));
rHours = hours * 3600;
}
const minutes = parseInt(Math.floor((value-rHours) / 60));
const rMin = minutes * 60;
const seconds = parseInt(Math.floor(value - rHours - rMin));
const paddedH = hours > 9 ? hours : `0${hours}`;
const paddedM = minutes > 9 ? minutes : `0${minutes}`;
const paddedS = seconds > 9 ? seconds : `0${seconds}`;
if(withHours) {
return `${paddedH}:${paddedM}:${paddedS}`;
} else {
return `${paddedM}:${paddedS}`;
}
} else {
if(withHours) {
return '00:00:00';
} else {
return '00:00';
}
}
});
Vue.filter('length', function(value, precision = 2, isArea = false) {
if(!value) return value;
const length = parseFloat(value);
if(!isFinite(value) || isNaN(length)) {
return length;
}
let unit;
let factor;
if(isArea) {
if(length < 0.00001) {
unit = 'mm²';
factor = 100000;
} else if(length < 0.01) {
unit = 'cm²';
factor = 10000;
} else if(length < 100) {
unit = 'm²';
factor = 1;
} else if(length < 100000) {
unit = 'ha';
factor = 0.0001;
} else {
unit = 'km²';
factor = 0.000001;
}
} else {
if(length < 0.01) {
unit = 'mm';
factor = 1000;
} else if(length < 1) {
unit = 'cm';
factor = 100;
} else if(length < 1000) {
unit = 'm';
factor = 1;
} else {
unit = 'km';
factor = 0.001;
}
}
const sizeInUnit = length * factor;
return sizeInUnit.toFixed(precision) + ' ' + unit;
});
Vue.filter('bytes', function(value, precision = 2) {
if(!value) return value;
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const bytes = parseFloat(value);
let unitIndex;
if(!isFinite(value) || isNaN(bytes)) {
unitIndex = 0;
} else {
unitIndex = Math.floor(Math.log(bytes) / Math.log(1024));
}
const unit = units[unitIndex];
const sizeInUnit = bytes / Math.pow(1024, unitIndex);
return sizeInUnit.toFixed(precision) + ' ' + unit;
});
Vue.filter('toFixed', function(value, precision = 2) {
if(precision < 0) precision = 2;
return value ? value.toFixed(precision) : value;
});
Vue.filter('truncate', function(str, length = 80, ellipses = '…') {
if(length < 0) length = 80;
if(str) {
if(str.length <= length) {
return str;
}
return str.slice(0, length) + ellipses;
}
return str;
});
Vue.filter('bibtexify', function(value, type) {
let rendered = "<pre><code>";
if(type) {
rendered += "@"+type+" {"
if(value['citekey']) rendered += value['citekey'] + ",";
for(let k in value) {
if(value[k] == null || value[k] == '' || k == 'citekey') continue;
rendered += " <br />";
rendered += " " + k + " = \"" + value[k] + "\"";
}
rendered += "<br />";
rendered += "}";
}
rendered += "</code></pre>";
return rendered;
});
Vue.filter('mentionify', function(value) {
const template = `<span class="badge badge-primary">@{name}</span>`;
const unknownTemplate = `<span class="font-weight-bold">@{name}</span>`;
const mentionRegex = /@(\w|\d)+/gi;
let mentions = value.match(mentionRegex);
if(!mentions) return value;
mentions = mentions.filter((m, i) => mentions.indexOf(m) === i);
let newValue = value;
for(let i=0; i<mentions.length; i++) {
const elem = mentions[i];
const m = elem.substring(1);
const user = app.$getUserBy(m, 'nickname');
const replRegex = new RegExp(elem, 'g');
let name = m;
let tpl = unknownTemplate;
if(user) {
name = user.name;
tpl = template;
}
newValue = newValue.replace(replRegex, tpl.replace('{name}', name));
}
return newValue;
});
const app = new Vue({
el: '#app',
i18n: i18n,
router: router,
render: h => {
return h(App, {
props: {
onInit: _ => {
app.init();
}
}
})
},
beforeMount: function() {
this.init();
},
methods: {
init() {
Vue.prototype.$httpQueue.add(() =>
Axios.get('pre').then(response => {
this.preferences = response.data.preferences;
this.concepts = response.data.concepts;
this.entityTypes = response.data.entityTypes;
this.users = response.data.users;
// Check if user is logged in and set preferred language
// instead of browser default
if(!app.$auth.ready()) {
app.$auth.load().then(_ => {
app.$updateLanguage();
});
} else {
app.$updateLanguage();
}
const extensions = this.preferences['prefs.load-extensions'];
for(let k in extensions) {
if(!extensions[k] || (k != 'map' && k != 'files')) {
console.log("Skipping plugin " + k);
continue;
}
let name = k;
let nameExt = name + '.js';
import('./plugins/' + nameExt).then(data => {
Vue.use(data.default);
this.$addEnabledPlugin(name);
});
}
this.$getSpacialistPlugins('plugins');
}));
}
},
data() {
return {
selectedEntity: {},
onSelectEntity: function(selection) {
app.$data.selectedEntity = Object.assign({}, selection);
},
preferences: {},
concepts: {},
entityTypes: {},
users: [],
plugins: {},
onInit: null
}
}
});
|
import { connect } from 'react-redux';
import ClaimList from './view';
import { SETTINGS, selectClaimSearchByQuery, selectClaimsByUri } from 'lbry-redux';
import { makeSelectClientSetting } from 'redux/selectors/settings';
const select = (state) => ({
searchInLanguage: makeSelectClientSetting(SETTINGS.SEARCH_IN_LANGUAGE)(state),
claimSearchByQuery: selectClaimSearchByQuery(state),
claimsByUri: selectClaimsByUri(state),
});
export default connect(select)(ClaimList);
|
/**
* @file config.js
* @author Clotaire Delanchy <clo.delanchy@gmail.com>
* @date 2013-09-30
*
* Default configuration for Pizza Commander
*/
var join = require('path').join;
var config = {
// Port to run server on
port: 8080,
// Web ressources root path(absolute)
root: join(__dirname, '../www'),
// Static contents max age
maxAge: 3600 * 24,
// Application domain
domain: 'localhost',
// Target
target: {
host: "www.dominos.fr",
port: 80,
url: '/carte_pizzas.php'
}
}
module.exports = config; |
/**
* This process was implemented feed cluster.
* License MIT
* see https://github.com/PROJECT-BIGMAMA/PILOT-COLLECTOR
* see BIGMAMA PROJECT (https://github.com/PROJECT-BIGMAMA/BIGMAMA-DOC)
*/
var cluster = require('cluster');
var config = require('../conf/config.json');
if (cluster.isMaster) {
for (i = 0; i < config.feed_cnt; i++) {
cluster.fork();
}
}else{
require('../processes/feed_manager');
} |
/**
*
* PreviewWysiwyg
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import {
CompositeDecorator,
ContentState,
convertFromHTML,
EditorState,
ContentBlock,
genKey,
Entity,
CharacterMetadata,
} from 'draft-js';
import { List, OrderedSet, Repeat, fromJS } from 'immutable';
import cn from 'classnames';
import { isEmpty, toArray } from 'lodash';
import WysiwygEditor from '../WysiwygEditor';
import converter from './converter';
import {
findAtomicEntities,
findLinkEntities,
findImageEntities,
findVideoEntities,
} from './strategies';
import Image from './image';
import Link from './link';
import Video from './video';
import styles from './componentsStyles.scss';
/* eslint-disable react/no-unused-state */
function getBlockStyle(block) {
switch (block.getType()) {
case 'blockquote':
return styles.editorBlockquote;
case 'code-block':
return styles.editorCodeBlock;
case 'unstyled':
return styles.editorParagraph;
case 'unordered-list-item':
return styles.unorderedList;
case 'ordered-list-item':
case 'header-one':
case 'header-two':
case 'header-three':
case 'header-four':
case 'header-five':
case 'header-six':
default:
return null;
}
}
const decorator = new CompositeDecorator([
{
strategy: findLinkEntities,
component: Link,
},
{
strategy: findImageEntities,
component: Image,
},
{
strategy: findVideoEntities,
component: Video,
},
{
strategy: findAtomicEntities,
component: Link,
},
]);
const getBlockSpecForElement = aElement => ({
contentType: 'link',
aHref: aElement.href,
aInnerHTML: aElement.innerHTML,
});
const elementToBlockSpecElement = element => wrapBlockSpec(getBlockSpecForElement(element));
const wrapBlockSpec = blockSpec => {
if (blockSpec == null) {
return null;
}
const tempEl = document.createElement('blockquote');
// stringify meta data and insert it as text content of temp HTML element. We will later extract
// and parse it.
tempEl.innerText = JSON.stringify(blockSpec);
return tempEl;
};
const replaceElement = (oldEl, newEl) => {
if (!(newEl instanceof HTMLElement)) {
return;
}
const parentNode = oldEl.parentNode;
return parentNode.replaceChild(newEl, oldEl);
};
const aReplacer = aElement => replaceElement(aElement, elementToBlockSpecElement(aElement));
const createContentBlock = (blockData = {}) => {
const { key, type, text, data, inlineStyles, entityData } = blockData;
let blockSpec = {
type: type !== null && type !== undefined ? type : 'unstyled',
text: text !== null && text !== undefined ? text : '',
key: key !== null && key !== undefined ? key : genKey(),
};
if (data) {
blockSpec.data = fromJS(data);
}
if (inlineStyles || entityData) {
let entityKey;
if (entityData) {
const { type, mutability, data } = entityData;
entityKey = Entity.create(type, mutability, data);
} else {
entityKey = null;
}
const style = OrderedSet(inlineStyles || []);
const charData = CharacterMetadata.applyEntity(
CharacterMetadata.create({ style, entityKey }),
entityKey,
);
blockSpec.characterList = List(Repeat(charData, text.length));
}
return new ContentBlock(blockSpec);
};
class PreviewWysiwyg extends React.PureComponent {
state = { editorState: EditorState.createEmpty(), isMounted: false };
componentDidMount() {
const { data } = this.props;
this.setState({ isMounted: true });
if (!isEmpty(data)) {
this.previewHTML(data);
}
}
// NOTE: This is not optimal and this lifecycle should be removed
// I couldn't find a better way to decrease the fullscreen preview's data conversion time
// Trying with componentDidUpdate didn't work
UNSAFE_componentWillUpdate(nextProps, nextState) {
if (nextProps.data !== this.props.data) {
new Promise(resolve => {
setTimeout(() => {
if (nextProps.data === this.props.data && nextState.isMounted) {
// I use an handler here to update the state wich is fine since the condition above prevent
// from entering into an infinite loop
this.previewHTML(nextProps.data);
}
resolve();
}, 300);
});
}
}
componentWillUnmount() {
this.setState({ isMounted: false });
}
getClassName = () => {
if (this.context.isFullscreen) {
return cn(styles.editor, styles.editorFullScreen, styles.fullscreenPreviewEditor);
}
return styles.editor;
};
previewHTML = rawContent => {
const initHtml = isEmpty(rawContent) ? '<p></p>' : rawContent;
const html = new DOMParser().parseFromString(converter.makeHtml(initHtml), 'text/html');
toArray(html.getElementsByTagName('a')) // Retrieve all the links <a> tags
.filter((value) => value.getElementsByTagName('img').length > 0) // Filter by checking if they have any <img> children
.forEach(aReplacer); // Change those links into <blockquote> elements so we can set some metacharacters with the img content
// TODO:
// in the same way, retrieve all <pre> tags
// create custom atomic block
// create custom code block
let blocksFromHTML = convertFromHTML(html.body.innerHTML);
if (blocksFromHTML.contentBlocks) {
blocksFromHTML = blocksFromHTML.contentBlocks.reduce((acc, block) => {
if (block.getType() === 'blockquote') {
try {
const { aHref, aInnerHTML } = JSON.parse(block.getText());
const entityData = {
type: 'LINK',
mutability: 'IMMUTABLE',
data: {
aHref,
aInnerHTML,
},
};
const blockSpec = Object.assign(
{ type: 'atomic', text: ' ', key: block.getKey() },
{ entityData },
);
const atomicBlock = createContentBlock(blockSpec); // Create an atomic block so we can identify it easily
return acc.concat([atomicBlock]);
} catch (err) {
return acc.concat(block);
}
}
return acc.concat(block);
}, []);
const contentState = ContentState.createFromBlockArray(blocksFromHTML);
return this.setState({ editorState: EditorState.createWithContent(contentState, decorator) });
}
return this.setState({ editorState: EditorState.createEmpty() });
};
render() {
const { placeholder } = this.context;
// this.previewHTML2(this.props.data);
return (
<div className={this.getClassName()}>
<WysiwygEditor
blockStyleFn={getBlockStyle}
editorState={this.state.editorState}
onChange={() => {}}
placeholder={placeholder}
/>
<input className={styles.editorInput} value="" onChange={() => {}} tabIndex="-1" />
</div>
);
}
}
PreviewWysiwyg.contextTypes = {
isFullscreen: PropTypes.bool,
placeholder: PropTypes.string,
};
PreviewWysiwyg.defaultProps = {
data: '',
};
PreviewWysiwyg.propTypes = {
data: PropTypes.string,
};
export default PreviewWysiwyg;
|
const map = (array, iteratee) => {
if( ! isMappable( array ) ) {
return []
}
const result = []
const fn = iteratee || ( a => a )
for( const key in array ) {
result.push( fn( array[ key ], key, array ) )
}
return result
}
const isMappable = array => {
return array !== null && (
array instanceof Array ||
typeof( array ) === 'object' ||
typeof( array ) === 'string'
)
}
export { map } |
/**
* Gatsby Browser APIs.
*
* @module gatsby-browser.js
*/
import smoothscroll from 'smoothscroll-polyfill'
export const onClientEntry = () => {
smoothscroll.polyfill()
}
|
var passport = require('passport');
module.exports = {
login: function(req, res, next) {
var auth = passport.authenticate('local', function(err, user) {
if (err) return next(err);
if (!user) {
res.send({success: false}); // TODO:
}
req.logIn(user, function(err) {
if (err) return next(err);
res.redirect('/');
})
});
auth(req, res, next);
},
logout: function(req, res, next) {
req.logout();
res.redirect('/');
},
isAuthenticated: function(req, res, next) {
if (!req.isAuthenticated()) {
res.redirect('/login');
}
else {
next();
}
},
hasPhoneNumber: function(req, res, next) {
if(!req.user.phoneNumber) {
req.session.error = 'You must have mobile phone to create an event';
res.redirect('/');
}
else {
next();
}
}
}; |
import { isEmpty } from 'lodash';
import { SET_CURRENT_USER, GET_USER_INFORMATION } from '../actions/types';
export const initialState = {
isAuthenticated: !!localStorage.getItem('authToken'),
userDetails: {},
isLoading: false
};
export default (state = initialState, action = {}) => {
switch (action.type) {
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: !isEmpty(action.user),
userDetails: action.user,
user: action.user,
isLoading: false
};
case 'SIGNUP_REQUEST':
return {
...state,
isLoading: action.isLoading
};
case 'GET_USER_REQUEST':
return {
...state,
isLoading: action.isLoading
};
case GET_USER_INFORMATION:
return {
...state,
isAuthenticated: !isEmpty(action.user),
userDetails: action.user,
isLoading: action.isLoading
};
default:
return state;
}
};
|
var util = require('util');
var db = require('../modules/db');
var _find = function(kampo, valoro){
if(kampo){
kampo = db.escapeId(kampo);
valoro = db.escape(valoro);
var query = util.format('SELECT * FROM `retlist_abono` WHERE %s = %s;', kampo, valoro);
}
else
var query = util.format('SELECT * FROM `retlist_abono`;');
return db.mysqlExec(query);
}
var _insert = function(idRetlisto, ekde, formato_html, kodigxo_utf8, retadreso){
db.escapeArgs(arguments);
var query = util.format( 'INSERT INTO retlist_abono (ekde, formato_html, kodigxo_utf8, \
retadreso, idRetlisto) VALUES (%s, %s, %s, %s, %s);',
ekde, formato_html, kodigxo_utf8, retadreso, idRetlisto);
return db.mysqlExec(query);
}
var _delete = function(id){
id = db.escape(id);
var query = util.format('DELETE FROM `retlist_abono` WHERE `id` = %s ;', id);
return db.mysqlExec(query);
}
module.exports = {
find: _find,
insert: _insert,
delete: _delete
}
|
//taken from https://github.com/simplabs/ember-simple-auth/blob/master/tests/dummy/app/services/session-account.js
import Ember from 'ember';
const { inject: { service } } = Ember;
export default Ember.Service.extend({
session: service('session'),
token: Ember.computed('session.data.authenticated', function() {
let encoded = this.get('session.data.authenticated.token');
if(encoded) {
const token = this.getTokenData(encoded);
return token;
}
}),
//TODO this is copypasta from jwt from ember-simple-auth, could probably import it somehow
/**
Returns the decoded token with accessible returned values.
@method getTokenData
@return {object} An object with properties for the session.
*/
getTokenData(token) {
const tokenData = atob(token.split('.')[1]);
try {
return JSON.parse(tokenData);
} catch (e) {
return tokenData;
}
}
});
|
/* global
describe
it
*/
const {sync} = require('../index.js')
const expect = require('chai').expect
describe('sync test =>', () => {
it('sync 1 cb, valid', done => {
sync([
cb => cb(null, true)
], (err, result) => {
expect(err).to.equal(null)
expect(result).to.equal(true)
done()
})
})
it('sync 4 cb, valid', done => {
sync([
cb => cb(null, true),
cb => cb(null, true),
cb => cb(null, true),
cb => cb(null, true)
], (err, result) => {
expect(err).to.equal(null)
expect(result).to.equal(true)
done()
})
})
it('sync 1 cb, error', done => {
sync([
cb => cb(true, null)
], (err, result) => {
expect(err).to.equal(true)
expect(result).to.equal(null)
done()
})
})
it('sync 4 cb, error', done => {
sync([
cb => cb(true, null),
cb => cb(true, null),
cb => cb(true, null),
cb => cb(true, null)
], (err, result) => {
expect(err).to.equal(true)
expect(result).to.equal(null)
done()
})
})
it('sync 4 cb, sum valid', done => {
sync([
cb => cb(null, 10),
(cb, val) => cb(null, val * 23),
(cb, val) => cb(null, val * 57),
(cb, val) => cb(null, val * 80)
], (err, result) => {
expect(err).to.equal(null)
expect(result).to.equal(1048800)
done()
})
})
it('sync 4 cb timeout, sum valid', done => {
sync([
cb => setTimeout(() => cb(null, 10), 100),
(cb, val) => setTimeout(() => cb(null, val * 23), 50),
(cb, val) => setTimeout(() => cb(null, val * 57), 30),
(cb, val) => setTimeout(() => cb(null, val * 80), 10)
], (err, result) => {
expect(err).to.equal(null)
expect(result).to.equal(1048800)
done()
})
})
it('sync 4 cb timeout, string concat valid', done => {
sync([
cb => setTimeout(() => cb(null, 'x'), 100),
(cb, val) => setTimeout(() => cb(null, `${val}y`), 50),
(cb, val) => setTimeout(() => cb(null, `${val}z`), 30),
(cb, val) => setTimeout(() => cb(null, `${val}f`), 10)
], (err, result) => {
expect(err).to.equal(null)
expect(result).to.equal('xyzf')
done()
})
})
it('sync 4 cb timeout, string concat error', done => {
sync([
cb => setTimeout(() => cb(null, 'x'), 100),
(cb, val) => setTimeout(() => cb(true, `${val}y`), 50),
(cb, val) => setTimeout(() => cb(null, `${val}z`), 30),
(cb, val) => setTimeout(() => cb(null, `${val}f`), 10)
], (err, result) => {
expect(err).to.equal(true)
done()
})
})
it('sync 100 cb timeout, sum valid', done => {
const massSync = Array(100).fill().map((val, key) => {
return (num => {
return (cb, prVal = 1) => {
setTimeout(() => {
return cb(null, prVal + num)
}, num)
}
})(key)
})
sync(massSync, (err, result) => {
expect(err).to.equal(null)
expect(result).to.equal(4951)
done()
})
})
})
|
!function (a) {
"function" == typeof define && define.amd ? define(["jquery"], a) : a(window.jQuery)
}(function (a) {
"function" != typeof Array.prototype.reduce && (Array.prototype.reduce = function (a, b) {
var c, d, e = this.length >>> 0, f = !1;
for (1 < arguments.length && (d = b, f = !0), c = 0; e > c; ++c)this.hasOwnProperty(c) && (f ? d = a(d, this[c], c, this) : (d = this[c], f = !0));
if (!f)throw new TypeError("Reduce of empty array with no initial value");
return d
}), "function" != typeof Array.prototype.filter && (Array.prototype.filter = function (a) {
if (void 0 === this || null === this)throw new TypeError;
var b = Object(this), c = b.length >>> 0;
if ("function" != typeof a)throw new TypeError;
for (var d = [], e = arguments.length >= 2 ? arguments[1] : void 0, f = 0; c > f; f++)if (f in b) {
var g = b[f];
a.call(e, g, f, b) && d.push(g)
}
return d
});
var b, c = "function" == typeof define && define.amd, d = function (b) {
var c = "Comic Sans MS" === b ? "Courier New" : "Comic Sans MS", d = a("<div>").css({
position: "absolute",
left: "-9999px",
top: "-9999px",
fontSize: "200px"
}).text("mmmmmmmmmwwwwwww").appendTo(document.body), e = d.css("fontFamily", c).width(), f = d.css("fontFamily", b + "," + c).width();
return d.remove(), e !== f
}, e = {
isMac: navigator.appVersion.indexOf("Mac") > -1,
isMSIE: navigator.userAgent.indexOf("MSIE") > -1 || navigator.userAgent.indexOf("Trident") > -1,
isFF: navigator.userAgent.indexOf("Firefox") > -1,
jqueryVersion: parseFloat(a.fn.jquery),
isSupportAmd: c,
hasCodeMirror: c ? require.specified("CodeMirror") : !!window.CodeMirror,
isFontInstalled: d,
isW3CRangeSupport: !!document.createRange
}, f = function () {
var b = function (a) {
return function (b) {
return a === b
}
}, c = function (a, b) {
return a === b
}, d = function (a) {
return function (b, c) {
return b[a] === c[a]
}
}, e = function () {
return !0
}, f = function () {
return !1
}, g = function (a) {
return function () {
return !a.apply(a, arguments)
}
}, h = function (a, b) {
return function (c) {
return a(c) && b(c)
}
}, i = function (a) {
return a
}, j = 0, k = function (a) {
var b = ++j + "";
return a ? a + b : b
}, l = function (b) {
var c = a(document);
return {
top: b.top + c.scrollTop(),
left: b.left + c.scrollLeft(),
width: b.right - b.left,
height: b.bottom - b.top
}
}, m = function (a) {
var b = {};
for (var c in a)a.hasOwnProperty(c) && (b[a[c]] = c);
return b
};
return {
eq: b,
eq2: c,
peq2: d,
ok: e,
fail: f,
self: i,
not: g,
and: h,
uniqueId: k,
rect2bnd: l,
invertObject: m
}
}(), g = function () {
var b = function (a) {
return a[0]
}, c = function (a) {
return a[a.length - 1]
}, d = function (a) {
return a.slice(0, a.length - 1)
}, e = function (a) {
return a.slice(1)
}, g = function (a, b) {
for (var c = 0, d = a.length; d > c; c++) {
var e = a[c];
if (b(e))return e
}
}, h = function (a, b) {
for (var c = 0, d = a.length; d > c; c++)if (!b(a[c]))return !1;
return !0
}, i = function (b, c) {
return -1 !== a.inArray(c, b)
}, j = function (a, b) {
return b = b || f.self, a.reduce(function (a, c) {
return a + b(c)
}, 0)
}, k = function (a) {
for (var b = [], c = -1, d = a.length; ++c < d;)b[c] = a[c];
return b
}, l = function (a, d) {
if (!a.length)return [];
var f = e(a);
return f.reduce(function (a, b) {
var e = c(a);
return d(c(e), b) ? e[e.length] = b : a[a.length] = [b], a
}, [[b(a)]])
}, m = function (a) {
for (var b = [], c = 0, d = a.length; d > c; c++)a[c] && b.push(a[c]);
return b
}, n = function (a) {
for (var b = [], c = 0, d = a.length; d > c; c++)i(b, a[c]) || b.push(a[c]);
return b
}, o = function (a, b) {
var c = a.indexOf(b);
return -1 === c ? null : a[c + 1]
}, p = function (a, b) {
var c = a.indexOf(b);
return -1 === c ? null : a[c - 1]
};
return {
head: b,
last: c,
initial: d,
tail: e,
prev: p,
next: o,
find: g,
contains: i,
all: h,
sum: j,
from: k,
clusterBy: l,
compact: m,
unique: n
}
}(), h = String.fromCharCode(160), i = "", j = function () {
var b = function (b) {
return b && a(b).hasClass("note-editable")
}, c = function (b) {
return b && a(b).hasClass("note-control-sizing")
}, d = function (b) {
var c;
if (b.hasClass("note-air-editor")) {
var d = g.last(b.attr("id").split("-"));
return c = function (b) {
return function () {
return a(b + d)
}
}, {
editor: function () {
return b
}, editable: function () {
return b
}, popover: c("#note-popover-"), handle: c("#note-handle-"), dialog: c("#note-dialog-")
}
}
return c = function (a) {
return function () {
return b.find(a)
}
}, {
editor: function () {
return b
},
dropzone: c(".note-dropzone"),
toolbar: c(".note-toolbar"),
editable: c(".note-editable"),
codable: c(".note-codable"),
statusbar: c(".note-statusbar"),
popover: c(".note-popover"),
handle: c(".note-handle"),
dialog: c(".note-dialog")
}
}, k = function (a) {
return a = a.toUpperCase(), function (b) {
return b && b.nodeName.toUpperCase() === a
}
}, l = function (a) {
return a && 3 === a.nodeType
}, m = function (a) {
return a && /^BR|^IMG|^HR/.test(a.nodeName.toUpperCase())
}, n = function (a) {
return b(a) ? !1 : a && /^DIV|^P|^LI|^H[1-7]/.test(a.nodeName.toUpperCase())
}, o = k("LI"), p = function (a) {
return n(a) && !o(a)
}, q = function (a) {
return !u(a) && !r(a) && !n(a)
}, r = function (a) {
return a && /^UL|^OL/.test(a.nodeName.toUpperCase())
}, s = function (a) {
return a && /^TD|^TH/.test(a.nodeName.toUpperCase())
}, t = k("BLOCKQUOTE"), u = function (a) {
return s(a) || t(a) || b(a)
}, v = k("A"), w = function (a) {
return q(a) && !!D(a, n)
}, x = function (a) {
return q(a) && !D(a, n)
}, y = k("BODY"), z = e.isMSIE ? " " : "<br>", A = function (a) {
return l(a) ? a.nodeValue.length : a.childNodes.length
}, B = function (a) {
var b = A(a);
return 0 === b ? !0 : j.isText(a) || 1 !== b || a.innerHTML !== z ? !1 : !0
}, C = function (a) {
m(a) || A(a) || (a.innerHTML = z)
}, D = function (a, c) {
for (; a;) {
if (c(a))return a;
if (b(a))break;
a = a.parentNode
}
return null
}, E = function (a, c) {
c = c || f.fail;
var d = [];
return D(a, function (a) {
return b(a) || d.push(a), c(a)
}), d
}, F = function (a, b) {
var c = E(a);
return g.last(c.filter(b))
}, G = function (b, c) {
for (var d = E(b), e = c; e; e = e.parentNode)if (a.inArray(e, d) > -1)return e;
return null
}, H = function (a, b) {
b = b || f.fail;
for (var c = []; a && !b(a);)c.push(a), a = a.previousSibling;
return c
}, I = function (a, b) {
b = b || f.fail;
for (var c = []; a && !b(a);)c.push(a), a = a.nextSibling;
return c
}, J = function (a, b) {
var c = [];
return b = b || f.ok, function d(e) {
a !== e && b(e) && c.push(e);
for (var f = 0, g = e.childNodes.length; g > f; f++)d(e.childNodes[f])
}(a), c
}, K = function (b, c) {
var d = b.parentNode, e = a("<" + c + ">")[0];
return d.insertBefore(e, b), e.appendChild(b), e
}, L = function (a, b) {
var c = b.nextSibling, d = b.parentNode;
return c ? d.insertBefore(a, c) : d.appendChild(a), a
}, M = function (b, c) {
return a.each(c, function (a, c) {
b.appendChild(c)
}), b
}, N = function (a) {
return 0 === a.offset
}, O = function (a) {
return a.offset === A(a.node)
}, P = function (a) {
return N(a) || O(a)
}, Q = function (a, b) {
for (; a && a !== b;) {
if (0 !== S(a))return !1;
a = a.parentNode
}
return !0
}, R = function (a, b) {
for (; a && a !== b;) {
if (S(a) !== A(a.parentNode) - 1)return !1;
a = a.parentNode
}
return !0
}, S = function (a) {
for (var b = 0; a = a.previousSibling;)b += 1;
return b
}, T = function (a) {
return !!(a && a.childNodes && a.childNodes.length)
}, U = function (a, c) {
var d, e;
if (0 === a.offset) {
if (b(a.node))return null;
d = a.node.parentNode, e = S(a.node)
} else T(a.node) ? (d = a.node.childNodes[a.offset - 1], e = A(d)) : (d = a.node, e = c ? 0 : a.offset - 1);
return {node: d, offset: e}
}, V = function (a, c) {
var d, e;
if (A(a.node) === a.offset) {
if (b(a.node))return null;
d = a.node.parentNode, e = S(a.node) + 1
} else T(a.node) ? (d = a.node.childNodes[a.offset], e = 0) : (d = a.node, e = c ? A(a.node) : a.offset + 1);
return {node: d, offset: e}
}, W = function (a, b) {
return a.node === b.node && a.offset === b.offset
}, X = function (a) {
if (l(a.node) || !T(a.node) || B(a.node))return !0;
var b = a.node.childNodes[a.offset - 1], c = a.node.childNodes[a.offset];
return b && !m(b) || c && !m(c) ? !1 : !0
}, Y = function (a, b) {
for (; a;) {
if (b(a))return a;
a = U(a)
}
return null
}, Z = function (a, b) {
for (; a;) {
if (b(a))return a;
a = V(a)
}
return null
}, $ = function (a, b, c, d) {
for (var e = a; e && (c(e), !W(e, b));) {
var f = d && a.node !== e.node && b.node !== e.node;
e = V(e, f)
}
}, _ = function (b, c) {
var d = E(c, f.eq(b));
return a.map(d, S).reverse()
}, ab = function (a, b) {
for (var c = a, d = 0, e = b.length; e > d; d++)c = c.childNodes.length <= b[d] ? c.childNodes[c.childNodes.length - 1] : c.childNodes[b[d]];
return c
}, bb = function (a, b) {
if (l(a.node))return N(a) ? a.node : O(a) ? a.node.nextSibling : a.node.splitText(a.offset);
var c = a.node.childNodes[a.offset], d = L(a.node.cloneNode(!1), a.node);
return M(d, I(c)), b || (C(a.node), C(d)), d
}, cb = function (a, b, c) {
var d = E(b.node, f.eq(a));
return d.length ? 1 === d.length ? bb(b, c) : d.reduce(function (a, d) {
var e = L(d.cloneNode(!1), d);
return a === b.node && (a = bb(b, c)), M(e, I(a)), c || (C(d), C(e)), e
}) : null
}, db = function (a) {
return document.createElement(a)
}, eb = function (a) {
return document.createTextNode(a)
}, fb = function (a, b) {
if (a && a.parentNode) {
if (a.removeNode)return a.removeNode(b);
var c = a.parentNode;
if (!b) {
var d, e, f = [];
for (d = 0, e = a.childNodes.length; e > d; d++)f.push(a.childNodes[d]);
for (d = 0, e = f.length; e > d; d++)c.insertBefore(f[d], a)
}
c.removeChild(a)
}
}, gb = function (a, c) {
for (; a && !b(a) && c(a);) {
var d = a.parentNode;
fb(a), a = d
}
}, hb = function (a, b) {
if (a.nodeName.toUpperCase() === b.toUpperCase())return a;
var c = db(b);
return a.style.cssText && (c.style.cssText = a.style.cssText), M(c, g.from(a.childNodes)), L(c, a), fb(a), c
}, ib = k("TEXTAREA"), jb = function (b, c) {
var d = ib(b[0]) ? b.val() : b.html();
if (c) {
var e = /<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g;
d = d.replace(e, function (a, b, c) {
c = c.toUpperCase();
var d = /^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(c) && !!b, e = /^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(c);
return a + (d || e ? "\n" : "")
}), d = a.trim(d)
}
return d
}, kb = function (a) {
var b = a.val();
return b.replace(/[\n\r]/g, "")
};
return {
NBSP_CHAR: h,
ZERO_WIDTH_NBSP_CHAR: i,
blank: z,
emptyPara: "<p>" + z + "</p>",
isEditable: b,
isControlSizing: c,
buildLayoutInfo: d,
isText: l,
isPara: n,
isPurePara: p,
isInline: q,
isBodyInline: x,
isBody: y,
isParaInline: w,
isList: r,
isTable: k("TABLE"),
isCell: s,
isBlockquote: t,
isBodyContainer: u,
isAnchor: v,
isDiv: k("DIV"),
isLi: o,
isSpan: k("SPAN"),
isB: k("B"),
isU: k("U"),
isS: k("S"),
isI: k("I"),
isImg: k("IMG"),
isTextarea: ib,
isEmpty: B,
isEmptyAnchor: f.and(v, B),
nodeLength: A,
isLeftEdgePoint: N,
isRightEdgePoint: O,
isEdgePoint: P,
isLeftEdgeOf: Q,
isRightEdgeOf: R,
prevPoint: U,
nextPoint: V,
isSamePoint: W,
isVisiblePoint: X,
prevPointUntil: Y,
nextPointUntil: Z,
walkPoint: $,
ancestor: D,
listAncestor: E,
lastAncestor: F,
listNext: I,
listPrev: H,
listDescendant: J,
commonAncestor: G,
wrap: K,
insertAfter: L,
appendChildNodes: M,
position: S,
hasChildren: T,
makeOffsetPath: _,
fromOffsetPath: ab,
splitTree: cb,
create: db,
createText: eb,
remove: fb,
removeWhile: gb,
replace: hb,
html: jb,
value: kb
}
}(), k = function () {
var b = function (a, b) {
var c, d, e = a.parentElement(), f = document.body.createTextRange(), h = g.from(e.childNodes);
for (c = 0; c < h.length; c++)if (!j.isText(h[c])) {
if (f.moveToElementText(h[c]), f.compareEndPoints("StartToStart", a) >= 0)break;
d = h[c]
}
if (0 !== c && j.isText(h[c - 1])) {
var i = document.body.createTextRange(), k = null;
i.moveToElementText(d || e), i.collapse(!d), k = d ? d.nextSibling : e.firstChild;
var l = a.duplicate();
l.setEndPoint("StartToStart", i);
for (var m = l.text.replace(/[\r\n]/g, "").length; m > k.nodeValue.length && k.nextSibling;)m -= k.nodeValue.length, k = k.nextSibling;
{
k.nodeValue
}
b && k.nextSibling && j.isText(k.nextSibling) && m === k.nodeValue.length && (m -= k.nodeValue.length, k = k.nextSibling), e = k, c = m
}
return {cont: e, offset: c}
}, c = function (a) {
var b = function (a, c) {
var d, e;
if (j.isText(a)) {
var h = j.listPrev(a, f.not(j.isText)), i = g.last(h).previousSibling;
d = i || a.parentNode, c += g.sum(g.tail(h), j.nodeLength), e = !i
} else {
if (d = a.childNodes[c] || a, j.isText(d))return b(d, 0);
c = 0, e = !1
}
return {node: d, collapseToStart: e, offset: c}
}, c = document.body.createTextRange(), d = b(a.node, a.offset);
return c.moveToElementText(d.node), c.collapse(d.collapseToStart), c.moveStart("character", d.offset), c
}, d = function (b, h, i, k) {
this.sc = b, this.so = h, this.ec = i, this.eo = k;
var l = function () {
if (e.isW3CRangeSupport) {
var a = document.createRange();
return a.setStart(b, h), a.setEnd(i, k), a
}
var d = c({node: b, offset: h});
return d.setEndPoint("EndToEnd", c({node: i, offset: k})), d
};
this.getPoints = function () {
return {sc: b, so: h, ec: i, eo: k}
}, this.getStartPoint = function () {
return {node: b, offset: h}
}, this.getEndPoint = function () {
return {node: i, offset: k}
}, this.select = function () {
var a = l();
if (e.isW3CRangeSupport) {
var b = document.getSelection();
b.rangeCount > 0 && b.removeAllRanges(), b.addRange(a)
} else a.select()
}, this.normalize = function () {
var a = function (a) {
return j.isVisiblePoint(a) || (j.isLeftEdgePoint(a) ? a = j.nextPointUntil(a, j.isVisiblePoint) : j.isRightEdgePoint(a) && (a = j.prevPointUntil(a, j.isVisiblePoint))), a
}, b = a(this.getStartPoint()), c = a(this.getStartPoint());
return new d(b.node, b.offset, c.node, c.offset)
}, this.nodes = function (a, b) {
a = a || f.ok;
var c = b && b.includeAncestor, d = b && b.fullyContains, e = this.getStartPoint(), h = this.getEndPoint(), i = [], k = [];
return j.walkPoint(e, h, function (b) {
if (!j.isEditable(b.node)) {
var e;
d ? (j.isLeftEdgePoint(b) && k.push(b.node), j.isRightEdgePoint(b) && g.contains(k, b.node) && (e = b.node)) : e = c ? j.ancestor(b.node, a) : b.node, e && a(e) && i.push(e)
}
}, !0), g.unique(i)
}, this.commonAncestor = function () {
return j.commonAncestor(b, i)
}, this.expand = function (a) {
var c = j.ancestor(b, a), e = j.ancestor(i, a);
if (!c && !e)return new d(b, h, i, k);
var f = this.getPoints();
return c && (f.sc = c, f.so = 0), e && (f.ec = e, f.eo = j.nodeLength(e)), new d(f.sc, f.so, f.ec, f.eo)
}, this.collapse = function (a) {
return a ? new d(b, h, b, h) : new d(i, k, i, k)
}, this.splitText = function () {
var a = b === i, c = this.getPoints();
return j.isText(i) && !j.isEdgePoint(this.getEndPoint()) && i.splitText(k), j.isText(b) && !j.isEdgePoint(this.getStartPoint()) && (c.sc = b.splitText(h), c.so = 0, a && (c.ec = c.sc, c.eo = k - h)), new d(c.sc, c.so, c.ec, c.eo)
}, this.deleteContents = function () {
if (this.isCollapsed())return this;
var b = this.splitText(), c = b.nodes(null, {fullyContains: !0}), e = j.prevPointUntil(b.getStartPoint(), function (a) {
return !g.contains(c, a.node)
}), f = [];
return a.each(c, function (a, b) {
var c = b.parentNode;
e.node !== c && 1 === j.nodeLength(c) && f.push(c), j.remove(b, !1)
}), a.each(f, function (a, b) {
j.remove(b, !1)
}), new d(e.node, e.offset, e.node, e.offset)
};
var m = function (a) {
return function () {
var c = j.ancestor(b, a);
return !!c && c === j.ancestor(i, a)
}
};
this.isOnEditable = m(j.isEditable), this.isOnList = m(j.isList), this.isOnAnchor = m(j.isAnchor), this.isOnCell = m(j.isCell), this.isLeftEdgeOf = function (a) {
if (!j.isLeftEdgePoint(this.getStartPoint()))return !1;
var b = j.ancestor(this.sc, a);
return b && j.isLeftEdgeOf(this.sc, b)
}, this.isCollapsed = function () {
return b === i && h === k
}, this.wrapBodyInlineWithPara = function () {
if (j.isBodyContainer(b) && j.isEmpty(b))return b.innerHTML = j.emptyPara, new d(b.firstChild, 0);
if (j.isParaInline(b) || j.isPara(b))return this.normalize();
var a;
if (j.isInline(b)) {
var c = j.listAncestor(b, f.not(j.isInline));
a = g.last(c), j.isInline(a) || (a = c[c.length - 2] || b.childNodes[h])
} else a = b.childNodes[h - 1];
var e = j.listPrev(a, j.isParaInline).reverse();
if (e = e.concat(j.listNext(a.nextSibling, j.isParaInline)), e.length) {
var i = j.wrap(g.head(e), "p");
j.appendChildNodes(i, g.tail(e))
}
return this.normalize()
}, this.insertNode = function (a, b) {
var c, d, e, f = this.wrapBodyInlineWithPara(), h = f.getStartPoint();
if (b)d = j.isPara(h.node) ? h.node : h.node.parentNode, e = j.isPara(h.node) ? h.node.childNodes[h.offset] : j.splitTree(h.node, h); else {
var i = j.listAncestor(h.node, j.isBodyContainer), k = g.last(i) || h.node;
j.isBodyContainer(k) ? (c = i[i.length - 2], d = k) : (c = k, d = c.parentNode), e = c && j.splitTree(c, h)
}
return e ? e.parentNode.insertBefore(a, e) : d.appendChild(a), a
}, this.toString = function () {
var a = l();
return e.isW3CRangeSupport ? a.toString() : a.text
}, this.bookmark = function (a) {
return {s: {path: j.makeOffsetPath(a, b), offset: h}, e: {path: j.makeOffsetPath(a, i), offset: k}}
}, this.getClientRects = function () {
var a = l();
return a.getClientRects()
}
};
return {
create: function (a, c, f, g) {
if (arguments.length)2 === arguments.length && (f = a, g = c); else if (e.isW3CRangeSupport) {
var h = document.getSelection();
if (0 === h.rangeCount)return null;
if (j.isBody(h.anchorNode))return null;
var i = h.getRangeAt(0);
a = i.startContainer, c = i.startOffset, f = i.endContainer, g = i.endOffset
} else {
var k = document.selection.createRange(), l = k.duplicate();
l.collapse(!1);
var m = k;
m.collapse(!0);
var n = b(m, !0), o = b(l, !1);
j.isText(n.node) && j.isLeftEdgePoint(n) && j.isTextNode(o.node) && j.isRightEdgePoint(o) && o.node.nextSibling === n.node && (n = o), a = n.cont, c = n.offset, f = o.cont, g = o.offset
}
return new d(a, c, f, g)
}, createFromNode: function (a) {
return this.create(a, 0, a, 1)
}, createFromBookmark: function (a, b) {
var c = j.fromOffsetPath(a, b.s.path), e = b.s.offset, f = j.fromOffsetPath(a, b.e.path), g = b.e.offset;
return new d(c, e, f, g)
}
}
}(), l = {
version: "0.6.0",
options: {
width: null,
height: null,
minHeight: null,
maxHeight: null,
focus: !1,
tabsize: 4,
styleWithSpan: !0,
disableLinkTarget: !1,
disableDragAndDrop: !1,
disableResizeEditor: !1,
shortcuts: !0,
placeholder: !1,
codemirror: {mode: "text/html", htmlMode: !0, lineNumbers: !0},
lang: "en-US",
direction: null,
toolbar: [["style", ["style"]], ["font", ["bold", "italic", "underline", "clear"]], ["fontname", ["fontname"]], ["color", ["color"]], ["para", ["ul", "ol", "paragraph"]], ["height", ["height"]], ["table", ["table"]], ["insert", ["link", "picture", "hr"]], ["view", ["fullscreen", "codeview"]], ["help", ["help"]]],
airMode: !1,
airPopover: [["color", ["color"]], ["font", ["bold", "underline", "clear"]], ["para", ["ul", "paragraph"]], ["table", ["table"]], ["insert", ["link", "picture"]]],
styleTags: ["p", "blockquote", "pre", "h1", "h2", "h3", "h4", "h5", "h6"],
defaultFontName: "Helvetica Neue",
fontNames: ["Arial", "Arial Black", "Comic Sans MS", "Courier New", "Helvetica Neue", "Impact", "Lucida Grande", "Tahoma", "Times New Roman", "Verdana"],
colors: [["#000000", "#424242", "#636363", "#9C9C94", "#CEC6CE", "#EFEFEF", "#F7F7F7", "#FFFFFF"], ["#FF0000", "#FF9C00", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#9C00FF", "#FF00FF"], ["#F7C6CE", "#FFE7CE", "#FFEFC6", "#D6EFD6", "#CEDEE7", "#CEE7F7", "#D6D6E7", "#E7D6DE"], ["#E79C9C", "#FFC69C", "#FFE79C", "#B5D6A5", "#A5C6CE", "#9CC6EF", "#B5A5D6", "#D6A5BD"], ["#E76363", "#F7AD6B", "#FFD663", "#94BD7B", "#73A5AD", "#6BADDE", "#8C7BC6", "#C67BA5"], ["#CE0000", "#E79439", "#EFC631", "#6BA54A", "#4A7B8C", "#3984C6", "#634AA5", "#A54A7B"], ["#9C0000", "#B56308", "#BD9400", "#397B21", "#104A5A", "#085294", "#311873", "#731842"], ["#630000", "#7B3900", "#846300", "#295218", "#083139", "#003163", "#21104A", "#4A1031"]],
lineHeights: ["1.0", "1.2", "1.4", "1.5", "1.6", "1.8", "2.0", "3.0"],
insertTableMaxSize: {col: 10, row: 10},
maximumImageFileSize: null,
oninit: null,
onfocus: null,
onblur: null,
onenter: null,
onkeyup: null,
onkeydown: null,
onImageUpload: null,
onImageUploadError: null,
onToolbarClick: null,
onsubmit: null,
onCreateLink: function (a) {
return -1 !== a.indexOf("@") && -1 === a.indexOf(":") ? a = "mailto:" + a : -1 === a.indexOf("://") && (a = "http://" + a), a
},
keyMap: {
pc: {
ENTER: "insertParagraph",
"CTRL+Z": "undo",
"CTRL+Y": "redo",
TAB: "tab",
"SHIFT+TAB": "untab",
"CTRL+B": "bold",
"CTRL+I": "italic",
"CTRL+U": "underline",
"CTRL+SHIFT+S": "strikethrough",
"CTRL+BACKSLASH": "removeFormat",
"CTRL+SHIFT+L": "justifyLeft",
"CTRL+SHIFT+E": "justifyCenter",
"CTRL+SHIFT+R": "justifyRight",
"CTRL+SHIFT+J": "justifyFull",
"CTRL+SHIFT+NUM7": "insertUnorderedList",
"CTRL+SHIFT+NUM8": "insertOrderedList",
"CTRL+LEFTBRACKET": "outdent",
"CTRL+RIGHTBRACKET": "indent",
"CTRL+NUM0": "formatPara",
"CTRL+NUM1": "formatH1",
"CTRL+NUM2": "formatH2",
"CTRL+NUM3": "formatH3",
"CTRL+NUM4": "formatH4",
"CTRL+NUM5": "formatH5",
"CTRL+NUM6": "formatH6",
"CTRL+ENTER": "insertHorizontalRule",
"CTRL+K": "showLinkDialog"
},
mac: {
ENTER: "insertParagraph",
"CMD+Z": "undo",
"CMD+SHIFT+Z": "redo",
TAB: "tab",
"SHIFT+TAB": "untab",
"CMD+B": "bold",
"CMD+I": "italic",
"CMD+U": "underline",
"CMD+SHIFT+S": "strikethrough",
"CMD+BACKSLASH": "removeFormat",
"CMD+SHIFT+L": "justifyLeft",
"CMD+SHIFT+E": "justifyCenter",
"CMD+SHIFT+R": "justifyRight",
"CMD+SHIFT+J": "justifyFull",
"CMD+SHIFT+NUM7": "insertUnorderedList",
"CMD+SHIFT+NUM8": "insertOrderedList",
"CMD+LEFTBRACKET": "outdent",
"CMD+RIGHTBRACKET": "indent",
"CMD+NUM0": "formatPara",
"CMD+NUM1": "formatH1",
"CMD+NUM2": "formatH2",
"CMD+NUM3": "formatH3",
"CMD+NUM4": "formatH4",
"CMD+NUM5": "formatH5",
"CMD+NUM6": "formatH6",
"CMD+ENTER": "insertHorizontalRule",
"CMD+K": "showLinkDialog"
}
}
},
lang: {
"en-US": {
font: {
bold: "Bold",
italic: "Italic",
underline: "Underline",
clear: "Remove Font Style",
height: "Line Height",
name: "Font Family"
},
image: {
image: "Picture",
insert: "Insert Image",
resizeFull: "Resize Full",
resizeHalf: "Resize Half",
resizeQuarter: "Resize Quarter",
floatLeft: "Float Left",
floatRight: "Float Right",
floatNone: "Float None",
shapeRounded: "Shape: Rounded",
shapeCircle: "Shape: Circle",
shapeThumbnail: "Shape: Thumbnail",
shapeNone: "Shape: None",
dragImageHere: "Drag image or text here",
dropImage: "Drop image or Text",
selectFromFiles: "Select from files",
maximumFileSize: "Maximum file size",
maximumFileSizeError: "Maximum file size exceeded.",
url: "Image URL",
remove: "Remove Image"
},
link: {
link: "Link",
insert: "Insert Link",
unlink: "Unlink",
edit: "Edit",
textToDisplay: "Text to display",
url: "To what URL should this link go?",
openInNewWindow: "Open in new window"
},
table: {table: "Table"},
hr: {insert: "Insert Horizontal Rule"},
style: {
style: "Style",
normal: "Normal",
blockquote: "Quote",
pre: "Code",
h1: "Header 1",
h2: "Header 2",
h3: "Header 3",
h4: "Header 4",
h5: "Header 5",
h6: "Header 6"
},
lists: {unordered: "Unordered list", ordered: "Ordered list"},
options: {help: "Help", fullscreen: "Full Screen", codeview: "Code View"},
paragraph: {
paragraph: "Paragraph",
outdent: "Outdent",
indent: "Indent",
left: "Align left",
center: "Align center",
right: "Align right",
justify: "Justify full"
},
color: {
recent: "Recent Color",
more: "More Color",
background: "Background Color",
foreground: "Foreground Color",
transparent: "Transparent",
setTransparent: "Set transparent",
reset: "Reset",
resetToDefault: "Reset to default"
},
shortcut: {
shortcuts: "Keyboard shortcuts",
close: "Close",
textFormatting: "Text formatting",
action: "Action",
paragraphFormatting: "Paragraph formatting",
documentStyle: "Document Style",
extraKeys: "Extra keys"
},
history: {undo: "Undo", redo: "Redo"}
}
}
}, m = function () {
var b = function (b) {
return a.Deferred(function (c) {
a.extend(new FileReader, {
onload: function (a) {
var b = a.target.result;
c.resolve(b)
}, onerror: function () {
c.reject(this)
}
}).readAsDataURL(b)
}).promise()
}, c = function (b, c) {
return a.Deferred(function (d) {
a("<img>").one("load", function () {
d.resolve(a(this))
}).one("error abort", function () {
d.reject(a(this).detach())
}).css({display: "none"}).appendTo(document.body).attr("src", b).attr("data-filename", c)
}).promise()
};
return {readFileAsDataURL: b, createImage: c}
}(), n = {
isEdit: function (a) {
return g.contains([8, 9, 13, 32], a)
},
nameFromCode: {
8: "BACKSPACE",
9: "TAB",
13: "ENTER",
32: "SPACE",
48: "NUM0",
49: "NUM1",
50: "NUM2",
51: "NUM3",
52: "NUM4",
53: "NUM5",
54: "NUM6",
55: "NUM7",
56: "NUM8",
66: "B",
69: "E",
73: "I",
74: "J",
75: "K",
76: "L",
82: "R",
83: "S",
85: "U",
89: "Y",
90: "Z",
191: "SLASH",
219: "LEFTBRACKET",
220: "BACKSLASH",
221: "RIGHTBRACKET"
}
}, o = function () {
var b = function (b, c) {
if (e.jqueryVersion < 1.9) {
var d = {};
return a.each(c, function (a, c) {
d[c] = b.css(c)
}), d
}
return b.css.call(b, c)
};
this.stylePara = function (b, c) {
a.each(b.nodes(j.isPara, {includeAncestor: !0}), function (b, d) {
a(d).css(c)
})
}, this.current = function (c, d) {
var e = a(j.isText(c.sc) ? c.sc.parentNode : c.sc), f = ["font-family", "font-size", "text-align", "list-style-type", "line-height"], g = b(e, f) || {};
if (g["font-size"] = parseInt(g["font-size"], 10), g["font-bold"] = document.queryCommandState("bold") ? "bold" : "normal", g["font-italic"] = document.queryCommandState("italic") ? "italic" : "normal", g["font-underline"] = document.queryCommandState("underline") ? "underline" : "normal", g["font-strikethrough"] = document.queryCommandState("strikeThrough") ? "strikethrough" : "normal", g["font-superscript"] = document.queryCommandState("superscript") ? "superscript" : "normal", g["font-subscript"] = document.queryCommandState("subscript") ? "subscript" : "normal", c.isOnList()) {
var h = ["circle", "disc", "disc-leading-zero", "square"], i = a.inArray(g["list-style-type"], h) > -1;
g["list-style"] = i ? "unordered" : "ordered"
} else g["list-style"] = "none";
var k = j.ancestor(c.sc, j.isPara);
if (k && k.style["line-height"])g["line-height"] = k.style.lineHeight; else {
var l = parseInt(g["line-height"], 10) / parseInt(g["font-size"], 10);
g["line-height"] = l.toFixed(1)
}
return g.image = j.isImg(d) && d, g.anchor = c.isOnAnchor() && j.ancestor(c.sc, j.isAnchor), g.ancestors = j.listAncestor(c.sc, j.isEditable), g.range = c, g
}
}, p = function () {
this.insertTab = function (a, b, c) {
var d = j.createText(new Array(c + 1).join(j.NBSP_CHAR));
b = b.deleteContents(), b.insertNode(d, !0), b = k.create(d, c), b.select()
}, this.insertParagraph = function () {
var b = k.create();
b = b.deleteContents(), b = b.wrapBodyInlineWithPara();
var c, d = j.ancestor(b.sc, j.isPara);
if (d) {
c = j.splitTree(d, b.getStartPoint());
var e = j.listDescendant(d, j.isEmptyAnchor);
e = e.concat(j.listDescendant(c, j.isEmptyAnchor)), a.each(e, function (a, b) {
j.remove(b)
})
} else {
var f = b.sc.childNodes[b.so];
c = a(j.emptyPara)[0], f ? b.sc.insertBefore(c, f) : b.sc.appendChild(c)
}
k.create(c, 0).normalize().select()
}
}, q = function () {
this.tab = function (a, b) {
var c = j.ancestor(a.commonAncestor(), j.isCell), d = j.ancestor(c, j.isTable), e = j.listDescendant(d, j.isCell), f = g[b ? "prev" : "next"](e, c);
f && k.create(f, 0).select()
}, this.createTable = function (b, c) {
for (var d, e = [], f = 0; b > f; f++)e.push("<td>" + j.blank + "</td>");
d = e.join("");
for (var g, h = [], i = 0; c > i; i++)h.push("<tr>" + d + "</tr>");
return g = h.join(""), a('<table class="table table-bordered">' + g + "</table>")[0]
}
}, r = function () {
this.insertOrderedList = function () {
this.toggleList("OL")
}, this.insertUnorderedList = function () {
this.toggleList("UL")
}, this.indent = function () {
var b = this, c = k.create().wrapBodyInlineWithPara(), d = c.nodes(j.isPara, {includeAncestor: !0}), e = g.clusterBy(d, f.peq2("parentNode"));
a.each(e, function (c, d) {
var e = g.head(d);
j.isLi(e) ? b.wrapList(d, e.parentNode.nodeName) : a.each(d, function (b, c) {
a(c).css("marginLeft", function (a, b) {
return (parseInt(b, 10) || 0) + 25
})
})
}), c.select()
}, this.outdent = function () {
var b = this, c = k.create().wrapBodyInlineWithPara(), d = c.nodes(j.isPara, {includeAncestor: !0}), e = g.clusterBy(d, f.peq2("parentNode"));
a.each(e, function (c, d) {
var e = g.head(d);
j.isLi(e) ? b.releaseList([d]) : a.each(d, function (b, c) {
a(c).css("marginLeft", function (a, b) {
return b = parseInt(b, 10) || 0, b > 25 ? b - 25 : ""
})
})
}), c.select()
}, this.toggleList = function (b) {
var c = this, d = k.create().wrapBodyInlineWithPara(), e = d.nodes(j.isPara, {includeAncestor: !0}), h = g.clusterBy(e, f.peq2("parentNode"));
if (g.find(e, j.isPurePara))a.each(h, function (a, d) {
c.wrapList(d, b)
}); else {
var i = d.nodes(j.isList, {includeAncestor: !0}).filter(function (c) {
return !a.nodeName(c, b)
});
i.length ? a.each(i, function (a, c) {
j.replace(c, b)
}) : this.releaseList(h, !0)
}
d.select()
}, this.wrapList = function (b, c) {
var d = g.head(b), e = g.last(b), f = j.isList(d.previousSibling) && d.previousSibling, h = j.isList(e.nextSibling) && e.nextSibling, i = f || j.insertAfter(j.create(c || "UL"), e);
b = a.map(b, function (a) {
return j.isPurePara(a) ? j.replace(a, "LI") : a
}), j.appendChildNodes(i, b), h && (j.appendChildNodes(i, g.from(h.childNodes)), j.remove(h))
}, this.releaseList = function (b, c) {
var d = [];
return a.each(b, function (b, e) {
var f = g.head(e), h = g.last(e), i = c ? j.lastAncestor(f, j.isList) : f.parentNode, k = i.childNodes.length > 1 ? j.splitTree(i, {
node: h.parentNode,
offset: j.position(h) + 1
}, !0) : null, l = j.splitTree(i, {node: f.parentNode, offset: j.position(f)}, !0);
e = c ? j.listDescendant(l, j.isLi) : g.from(l.childNodes).filter(j.isLi), (c || !j.isList(i.parentNode)) && (e = a.map(e, function (a) {
return j.replace(a, "P")
})), a.each(g.from(e).reverse(), function (a, b) {
j.insertAfter(b, i)
});
var m = g.compact([i, l, k]);
a.each(m, function (b, c) {
var d = [c].concat(j.listDescendant(c, j.isList));
a.each(d.reverse(), function (a, b) {
j.nodeLength(b) || j.remove(b, !0)
})
}), d = d.concat(e)
}), d
}
}, s = function () {
var b = new o, c = new q, d = new p, f = new r;
this.createRange = function (a) {
return a.focus(), k.create()
}, this.saveRange = function (a, b) {
a.focus(), a.data("range", k.create()), b && k.create().collapse().select()
}, this.saveNode = function (a) {
for (var b = [], c = 0, d = a[0].childNodes.length; d > c; c++)b.push(a[0].childNodes[c]);
a.data("childNodes", b)
}, this.restoreRange = function (a) {
var b = a.data("range");
b && (b.select(), a.focus())
}, this.restoreNode = function (a) {
a.html("");
for (var b = a.data("childNodes"), c = 0, d = b.length; d > c; c++)a[0].appendChild(b[c])
}, this.currentStyle = function (a) {
var c = k.create();
return c ? c.isOnEditable() && b.current(c, a) : !1
};
var h = this.triggerOnChange = function (a) {
var b = a.data("callbacks").onChange;
b && b(a.html(), a)
};
this.undo = function (a) {
a.data("NoteHistory").undo(), h(a)
}, this.redo = function (a) {
a.data("NoteHistory").redo(), h(a)
};
for (var i = this.afterCommand = function (a) {
a.data("NoteHistory").recordUndo(), h(a)
}, l = ["bold", "italic", "underline", "strikethrough", "superscript", "subscript", "justifyLeft", "justifyCenter", "justifyRight", "justifyFull", "formatBlock", "removeFormat", "backColor", "foreColor", "insertHorizontalRule", "fontName"], n = 0, s = l.length; s > n; n++)this[l[n]] = function (a) {
return function (b, c) {
document.execCommand(a, !1, c), i(b)
}
}(l[n]);
this.tab = function (a, b) {
var e = k.create();
e.isCollapsed() && e.isOnCell() ? c.tab(e) : (d.insertTab(a, e, b.tabsize), i(a))
}, this.untab = function () {
var a = k.create();
a.isCollapsed() && a.isOnCell() && c.tab(a, !0)
}, this.insertParagraph = function (a) {
d.insertParagraph(a), i(a)
}, this.insertOrderedList = function (a) {
f.insertOrderedList(a), i(a)
}, this.insertUnorderedList = function (a) {
f.insertUnorderedList(a), i(a)
}, this.indent = function (a) {
f.indent(a), i(a)
}, this.outdent = function (a) {
f.outdent(a), i(a)
}, this.insertImage = function (a, b, c) {
m.createImage(b, c).then(function (b) {
b.css({display: "", width: Math.min(a.width(), b.width())}), k.create().insertNode(b[0]), i(a)
}).fail(function () {
var b = a.data("callbacks");
b.onImageUploadError && b.onImageUploadError()
})
}, this.insertNode = function (a, b, c) {
k.create().insertNode(b, c), i(a)
}, this.insertText = function (a, b) {
var c = this.createRange(a).insertNode(j.createText(b), !0);
k.create(c, j.nodeLength(c)).select(), i(a)
}, this.formatBlock = function (a, b) {
b = e.isMSIE ? "<" + b + ">" : b, document.execCommand("FormatBlock", !1, b), i(a)
}, this.formatPara = function (a) {
this.formatBlock(a, "P"), i(a)
};
for (var n = 1; 6 >= n; n++)this["formatH" + n] = function (a) {
return function (b) {
this.formatBlock(b, "H" + a)
}
}(n);
this.fontSize = function (a, b) {
document.execCommand("fontSize", !1, 3), e.isFF ? a.find("font[size=3]").removeAttr("size").css("font-size", b + "px") : a.find("span").filter(function () {
return "medium" === this.style.fontSize
}).css("font-size", b + "px"), i(a)
}, this.lineHeight = function (a, c) {
b.stylePara(k.create(), {lineHeight: c}), i(a)
}, this.unlink = function (a) {
var b = k.create();
if (b.isOnAnchor()) {
var c = j.ancestor(b.sc, j.isAnchor);
b = k.createFromNode(c), b.select(), document.execCommand("unlink"), i(a)
}
}, this.createLink = function (b, c, d) {
var e = c.url, f = c.text, g = c.newWindow, h = c.range;
d.onCreateLink && (e = d.onCreateLink(e)), h = h.deleteContents();
var j = h.insertNode(a("<A>" + f + "</A>")[0], !0);
a(j).attr({href: e, target: g ? "_blank" : ""}), k.createFromNode(j).select(), i(b)
}, this.getLinkInfo = function (b) {
b.focus();
var c = k.create().expand(j.isAnchor), d = a(g.head(c.nodes(j.isAnchor)));
return {
range: c,
text: c.toString(),
isNewWindow: d.length ? "_blank" === d.attr("target") : !0,
url: d.length ? d.attr("href") : ""
}
}, this.color = function (a, b) {
var c = JSON.parse(b), d = c.foreColor, e = c.backColor;
d && document.execCommand("foreColor", !1, d), e && document.execCommand("backColor", !1, e), i(a)
}, this.insertTable = function (a, b) {
var d = b.split("x"), e = k.create();
e = e.deleteContents(), e.insertNode(c.createTable(d[0], d[1])), i(a)
}, this.floatMe = function (a, b, c) {
c.css("float", b), i(a)
}, this.imageShape = function (a, b, c) {
c.removeClass("img-rounded img-circle img-thumbnail"), b && c.addClass(b), i(a)
}, this.resize = function (a, b, c) {
c.css({width: 100 * b + "%", height: ""}), i(a)
}, this.resizeTo = function (a, b, c) {
var d;
if (c) {
var e = a.y / a.x, f = b.data("ratio");
d = {width: f > e ? a.x : a.y / f, height: f > e ? a.x * f : a.y}
} else d = {width: a.x, height: a.y};
b.css(d)
}, this.removeMedia = function (a, b, c) {
c.detach(), i(a)
}
}, t = function (a) {
var b = [], c = -1, d = a[0], e = function () {
var b = k.create(), c = {s: {path: [0], offset: 0}, e: {path: [0], offset: 0}};
return {contents: a.html(), bookmark: b ? b.bookmark(d) : c}
}, f = function (b) {
null !== b.contents && a.html(b.contents), null !== b.bookmark && k.createFromBookmark(d, b.bookmark).select()
};
this.undo = function () {
c > 0 && (c--, f(b[c]))
}, this.redo = function () {
b.length - 1 > c && (c++, f(b[c]))
}, this.recordUndo = function () {
c++, b.length > c && (b = b.slice(0, c)), b.push(e())
}, this.recordUndo()
}, u = function () {
this.update = function (b, c) {
var d = function (b, c) {
b.find(".dropdown-menu li a").each(function () {
var b = a(this).data("value") + "" == c + "";
this.className = b ? "checked" : ""
})
}, e = function (a, c) {
var d = b.find(a);
d.toggleClass("active", c())
}, f = b.find(".note-fontname");
if (f.length) {
var h = c["font-family"];
h && (h = g.head(h.split(",")), h = h.replace(/\'/g, ""), f.find(".note-current-fontname").text(h), d(f, h))
}
var i = b.find(".note-fontsize");
i.find(".note-current-fontsize").text(c["font-size"]), d(i, parseFloat(c["font-size"]));
var j = b.find(".note-height");
d(j, parseFloat(c["line-height"])), e('button[data-event="bold"]', function () {
return "bold" === c["font-bold"]
}), e('button[data-event="italic"]', function () {
return "italic" === c["font-italic"]
}), e('button[data-event="underline"]', function () {
return "underline" === c["font-underline"]
}), e('button[data-event="strikethrough"]', function () {
return "strikethrough" === c["font-strikethrough"]
}), e('button[data-event="superscript"]', function () {
return "superscript" === c["font-superscript"]
}), e('button[data-event="subscript"]', function () {
return "subscript" === c["font-subscript"]
}), e('button[data-event="justifyLeft"]', function () {
return "left" === c["text-align"] || "start" === c["text-align"]
}), e('button[data-event="justifyCenter"]', function () {
return "center" === c["text-align"]
}), e('button[data-event="justifyRight"]', function () {
return "right" === c["text-align"]
}), e('button[data-event="justifyFull"]', function () {
return "justify" === c["text-align"]
}), e('button[data-event="insertUnorderedList"]', function () {
return "unordered" === c["list-style"]
}), e('button[data-event="insertOrderedList"]', function () {
return "ordered" === c["list-style"]
})
}, this.updateRecentColor = function (b, c, d) {
var e = a(b).closest(".note-color"), f = e.find(".note-recent-color"), g = JSON.parse(f.attr("data-value"));
g[c] = d, f.attr("data-value", JSON.stringify(g));
var h = "backColor" === c ? "background-color" : "color";
f.find("i").css(h, d)
}
}, v = function () {
var a = new u;
this.update = function (b, c) {
a.update(b, c)
}, this.updateRecentColor = function (b, c, d) {
a.updateRecentColor(b, c, d)
}, this.activate = function (a) {
a.find("button").not('button[data-event="codeview"]').removeClass("disabled")
}, this.deactivate = function (a) {
a.find("button").not('button[data-event="codeview"]').addClass("disabled")
}, this.updateFullscreen = function (a, b) {
var c = a.find('button[data-event="fullscreen"]');
c.toggleClass("active", b)
}, this.updateCodeview = function (a, b) {
var c = a.find('button[data-event="codeview"]');
c.toggleClass("active", b)
}
}, w = function () {
var b = new u, c = function (b, c) {
var d = a(b), e = c ? d.offset() : d.position(), f = d.outerHeight(!0);
return {left: e.left, top: e.top + f}
}, d = function (a, b) {
a.css({display: "block", left: b.left, top: b.top})
}, e = 20;
this.update = function (h, i, j) {
b.update(h, i);
var k = h.find(".note-link-popover");
if (i.anchor) {
var l = k.find("a"), m = a(i.anchor).attr("href");
l.attr("href", m).html(m), d(k, c(i.anchor, j))
} else k.hide();
var n = h.find(".note-image-popover");
i.image ? d(n, c(i.image, j)) : n.hide();
var o = h.find(".note-air-popover");
if (j && !i.range.isCollapsed()) {
var p = f.rect2bnd(g.last(i.range.getClientRects()));
d(o, {left: Math.max(p.left + p.width / 2 - e, 0), top: p.top + p.height})
} else o.hide()
}, this.updateRecentColor = function (a, b, c) {
a.updateRecentColor(a, b, c)
}, this.hide = function (a) {
a.children().hide()
}
}, x = function () {
this.update = function (b, c, d) {
var e = b.find(".note-control-selection");
if (c.image) {
var f = a(c.image), g = d ? f.offset() : f.position(), h = {w: f.outerWidth(!0), h: f.outerHeight(!0)};
e.css({display: "block", left: g.left, top: g.top, width: h.w, height: h.h}).data("target", c.image);
var i = h.w + "x" + h.h;
e.find(".note-control-selection-info").text(i)
} else e.hide()
}, this.hide = function (a) {
a.children().hide()
}
}, y = function () {
var b = function (a, b) {
a.toggleClass("disabled", !b), a.attr("disabled", !b)
};
this.showImageDialog = function (c, d) {
return a.Deferred(function (a) {
var c = d.find(".note-image-dialog"), e = d.find(".note-image-input"), f = d.find(".note-image-url"), g = d.find(".note-image-btn");
c.one("shown.bs.modal", function () {
e.replaceWith(e.clone().on("change", function () {
a.resolve(this.files || this.value), c.modal("hide")
}).val("")), g.click(function (b) {
b.preventDefault(), a.resolve(f.val()), c.modal("hide")
}), f.on("keyup paste", function (a) {
var c;
c = "paste" === a.type ? a.originalEvent.clipboardData.getData("text") : f.val(), b(g, c)
}).val("").trigger("focus")
}).one("hidden.bs.modal", function () {
e.off("change"), f.off("keyup paste"), g.off("click"), "pending" === a.state() && a.reject()
}).modal("show")
})
}, this.showLinkDialog = function (c, d, e) {
return a.Deferred(function (a) {
var c = d.find(".note-link-dialog"), f = c.find(".note-link-text"), g = c.find(".note-link-url"), h = c.find(".note-link-btn"), i = c.find("input[type=checkbox]");
c.one("shown.bs.modal", function () {
f.val(e.text), f.on("input", function () {
e.text = f.val()
}), e.url || (e.url = e.text, b(h, e.text)), g.on("input", function () {
b(h, g.val()), e.text || f.val(g.val())
}).val(e.url).trigger("focus").trigger("select"), i.prop("checked", e.newWindow), h.one("click", function (b) {
b.preventDefault(), a.resolve({
range: e.range,
url: g.val(),
text: f.val(),
newWindow: i.is(":checked")
}), c.modal("hide")
})
}).one("hidden.bs.modal", function () {
f.off("input"), g.off("input"), h.off("click"), "pending" === a.state() && a.reject()
}).modal("show")
}).promise()
}, this.showHelpDialog = function (b, c) {
return a.Deferred(function (a) {
var b = c.find(".note-help-dialog");
b.one("hidden.bs.modal", function () {
a.resolve()
}).modal("show")
}).promise()
}
};
e.hasCodeMirror && (e.isSupportAmd ? require(["CodeMirror"], function (a) {
b = a
}) : b = window.CodeMirror);
var z = function () {
var c = a(window), d = a(document), f = a("html, body"), h = new s, i = new v, k = new w, l = new x, o = new y;
this.getEditor = function () {
return h
};
var p = function (b) {
var c = a(b).closest(".note-editor, .note-air-editor, .note-air-layout");
if (!c.length)return null;
var d;
return d = c.is(".note-editor, .note-air-editor") ? c : a("#note-editor-" + g.last(c.attr("id").split("-"))), j.buildLayoutInfo(d)
}, q = function (b, c) {
var d = b.editor(), e = b.editable(), f = e.data("callbacks"), g = d.data("options");
f.onImageUpload ? f.onImageUpload(c, h, e) : a.each(c, function (a, b) {
var c = b.name;
g.maximumImageFileSize && g.maximumImageFileSize < b.size ? f.onImageUploadError ? f.onImageUploadError(g.langInfo.image.maximumFileSizeError) : alert(g.langInfo.image.maximumFileSizeError) : m.readFileAsDataURL(b).then(function (a) {
h.insertImage(e, a, c)
}).fail(function () {
f.onImageUploadError && f.onImageUploadError()
})
})
}, r = {
showLinkDialog: function (a) {
var b = a.editor(), c = a.dialog(), d = a.editable(), e = h.getLinkInfo(d), f = b.data("options");
h.saveRange(d), o.showLinkDialog(d, c, e).then(function (b) {
h.restoreRange(d), h.createLink(d, b, f), k.hide(a.popover())
}).fail(function () {
h.restoreRange(d)
})
}, showImageDialog: function (a) {
var b = a.dialog(), c = a.editable();
h.saveRange(c), o.showImageDialog(c, b).then(function (b) {
h.restoreRange(c), "string" == typeof b ? h.insertImage(c, b) : q(a, b)
}).fail(function () {
h.restoreRange(c)
})
}, showHelpDialog: function (a) {
var b = a.dialog(), c = a.editable();
h.saveRange(c, !0), o.showHelpDialog(c, b).then(function () {
h.restoreRange(c)
})
}, fullscreen: function (a) {
var b = a.editor(), d = a.toolbar(), e = a.editable(), g = a.codable(), h = function (a) {
e.css("height", a.h), g.css("height", a.h), g.data("cmeditor") && g.data("cmeditor").setsize(null, a.h)
};
b.toggleClass("fullscreen");
var j = b.hasClass("fullscreen");
j ? (e.data("orgheight", e.css("height")), c.on("resize", function () {
h({h: c.height() - d.outerHeight()})
}).trigger("resize"), f.css("overflow", "hidden")) : (c.off("resize"), h({h: e.data("orgheight")}), f.css("overflow", "visible")), i.updateFullscreen(d, j)
}, codeview: function (a) {
var c, d, f = a.editor(), g = a.toolbar(), h = a.editable(), m = a.codable(), n = a.popover(), o = a.handle(), p = f.data("options");
f.toggleClass("codeview");
var q = f.hasClass("codeview");
q ? (m.val(j.html(h, !0)), m.height(h.height()), i.deactivate(g), k.hide(n), l.hide(o), m.focus(), e.hasCodeMirror && (c = b.fromTextArea(m[0], p.codemirror), p.codemirror.tern && (d = new b.TernServer(p.codemirror.tern), c.ternServer = d, c.on("cursorActivity", function (a) {
d.updateArgHints(a)
})), c.setSize(null, h.outerHeight()), m.data("cmEditor", c))) : (e.hasCodeMirror && (c = m.data("cmEditor"), m.val(c.getValue()), c.toTextArea()), h.html(j.value(m) || j.emptyPara), h.height(p.height ? m.height() : "auto"), i.activate(g), h.focus()), i.updateCodeview(a.toolbar(), q)
}
}, u = function (a) {
j.isImg(a.target) && a.preventDefault()
}, z = function (a) {
setTimeout(function () {
var b = p(a.currentTarget || a.target), c = h.currentStyle(a.target);
if (c) {
var d = b.editor().data("options").airMode;
d || i.update(b.toolbar(), c), k.update(b.popover(), c, d), l.update(b.handle(), c, d)
}
}, 0)
}, A = function (a) {
var b = p(a.currentTarget || a.target);
k.hide(b.popover()), l.hide(b.handle())
}, B = function (a) {
var b = a.originalEvent.clipboardData, c = p(a.currentTarget || a.target), d = c.editable();
if (!b || !b.items || !b.items.length) {
var e = d.data("callbacks");
if (!e.onImageUpload)return;
return h.saveNode(d), h.saveRange(d), d.html(""), void setTimeout(function () {
for (var a = d.find("img"), b = a[0].src, e = atob(b.split(",")[1]), f = new Uint8Array(e.length), g = 0; g < e.length; g++)f[g] = e.charCodeAt(g);
var i = new Blob([f], {type: "image/png"});
i.name = "clipboard.png", h.restoreNode(d), h.restoreRange(d), q(c, [i]), h.afterCommand(d)
}, 0)
}
var f = g.head(b.items), i = "file" === f.kind && -1 !== f.type.indexOf("image/");
i && q(c, [f.getAsFile()]), h.afterCommand(d)
}, C = function (b) {
if (j.isControlSizing(b.target)) {
b.preventDefault(), b.stopPropagation();
var c = p(b.target), e = c.handle(), f = c.popover(), g = c.editable(), i = c.editor(), m = e.find(".note-control-selection").data("target"), n = a(m), o = n.offset(), q = d.scrollTop(), r = i.data("options").airMode;
d.on("mousemove", function (a) {
h.resizeTo({
x: a.clientX - o.left,
y: a.clientY - (o.top - q)
}, n, !a.shiftKey), l.update(e, {image: m}, r), k.update(f, {image: m}, r)
}).one("mouseup", function () {
d.off("mousemove"), h.afterCommand(g)
}), n.data("ratio") || n.data("ratio", n.height() / n.width())
}
}, D = function (b) {
var c = a(b.target).closest("[data-event]");
c.length && b.preventDefault()
}, E = function (b) {
var c = a(b.target).closest("[data-event]");
if (c.length) {
var d = c.attr("data-event"), e = c.attr("data-value"), f = c.attr("data-hide"), j = p(b.target);
b.preventDefault();
var l;
if (-1 !== a.inArray(d, ["resize", "floatMe", "removeMedia", "imageShape"])) {
var m = j.handle().find(".note-control-selection");
l = a(m.data("target"))
}
if (f && c.parents(".popover").hide(), h[d]) {
var n = j.editable();
n.trigger("focus"), h[d](n, e, l)
} else r[d] ? r[d].call(this, j) : a.isFunction(a.summernote.pluginEvents[d]) && a.summernote.pluginEvents[d](j, e, l);
if (-1 !== a.inArray(d, ["backColor", "foreColor"])) {
var o = j.editor().data("options", o), q = o.airMode ? k : i;
q.updateRecentColor(g.head(c), d, e)
}
z(b)
}
}, F = 24, G = function (a) {
a.preventDefault(), a.stopPropagation();
var b = p(a.target).editable(), c = b.offset().top - d.scrollTop(), e = p(a.currentTarget || a.target), f = e.editor().data("options");
d.on("mousemove", function (a) {
var d = a.clientY - (c + F);
d = f.minHeight > 0 ? Math.max(d, f.minHeight) : d, d = f.maxHeight > 0 ? Math.min(d, f.maxHeight) : d, b.height(d)
}).one("mouseup", function () {
d.off("mousemove")
})
}, H = 18, I = function (b, c) {
var d, e = a(b.target.parentNode), f = e.next(), g = e.find(".note-dimension-picker-mousecatcher"), h = e.find(".note-dimension-picker-highlighted"), i = e.find(".note-dimension-picker-unhighlighted");
if (void 0 === b.offsetX) {
var j = a(b.target).offset();
d = {x: b.pageX - j.left, y: b.pageY - j.top}
} else d = {x: b.offsetX, y: b.offsetY};
var k = {c: Math.ceil(d.x / H) || 1, r: Math.ceil(d.y / H) || 1};
h.css({
width: k.c + "em",
height: k.r + "em"
}), g.attr("data-value", k.c + "x" + k.r), 3 < k.c && k.c < c.insertTableMaxSize.col && i.css({width: k.c + 1 + "em"}), 3 < k.r && k.r < c.insertTableMaxSize.row && i.css({height: k.r + 1 + "em"}), f.html(k.c + " x " + k.r)
}, J = function (a, b) {
b.disableDragAndDrop ? d.on("drop", function (a) {
a.preventDefault()
}) : K(a, b)
}, K = function (b, c) {
var e = a(), f = b.dropzone, g = b.dropzone.find(".note-dropzone-message");
d.on("dragenter", function (a) {
var d = b.editor.hasClass("codeview");
d || e.length || (b.editor.addClass("dragover"), f.width(b.editor.width()), f.height(b.editor.height()), g.text(c.langInfo.image.dragImageHere)), e = e.add(a.target)
}).on("dragleave", function (a) {
e = e.not(a.target), e.length || b.editor.removeClass("dragover")
}).on("drop", function () {
e = a(), b.editor.removeClass("dragover")
}), f.on("dragenter", function () {
f.addClass("hover"), g.text(c.langInfo.image.dropImage)
}).on("dragleave", function () {
f.removeClass("hover"), g.text(c.langInfo.image.dragImageHere)
}), f.on("drop", function (a) {
a.preventDefault();
var b = a.originalEvent.dataTransfer, c = b.getData("text/plain"), d = p(a.currentTarget || a.target);
d.editable().focus(), b && b.files && b.files.length ? q(d, b.files) : c && h.insertText(d.editable(), c)
}).on("dragover", !1)
};
this.bindKeyMap = function (b, c) {
var d = b.editor, e = b.editable;
b = p(e), e.on("keydown", function (f) {
var g = [];
f.metaKey && g.push("CMD"), f.ctrlKey && !f.altKey && g.push("CTRL"), f.shiftKey && g.push("SHIFT");
var i = n.nameFromCode[f.keyCode];
i && g.push(i);
var j = c[g.join("+")];
if (j) {
if (f.preventDefault(), h[j])h[j](e, d.data("options")); else if (r[j])r[j].call(this, b); else if (a.summernote.plugins[j]) {
var k = a.summernote.plugins[j];
a.isFunction(k.event) && k.event(f, h, b)
}
} else n.isEdit(f.keyCode) && h.afterCommand(e)
})
}, this.attach = function (a, b) {
b.shortcuts && this.bindKeyMap(a, b.keyMap[e.isMac ? "mac" : "pc"]), a.editable.on("mousedown", u), a.editable.on("keyup mouseup", z), a.editable.on("scroll", A), a.editable.on("paste", B), a.handle.on("mousedown", C), a.popover.on("click", E), a.popover.on("mousedown", D), b.airMode || (J(a, b), a.toolbar.on("click", E), a.toolbar.on("mousedown", D), b.disableResizeEditor || a.statusbar.on("mousedown", G));
var c = b.airMode ? a.popover : a.toolbar, d = c.find(".note-dimension-picker-mousecatcher");
d.css({
width: b.insertTableMaxSize.col + "em",
height: b.insertTableMaxSize.row + "em"
}).on("mousemove", function (a) {
I(a, b)
}), a.editor.data("options", b), e.isMSIE || setTimeout(function () {
document.execCommand("styleWithCSS", 0, b.styleWithSpan)
}, 0);
var f = new t(a.editable);
if (a.editable.data("NoteHistory", f), b.onenter && a.editable.keypress(function (a) {
a.keyCode === n.ENTER && b.onenter(a)
}), b.onfocus && a.editable.focus(b.onfocus), b.onblur && a.editable.blur(b.onblur), b.onkeyup && a.editable.keyup(b.onkeyup), b.onkeydown && a.editable.keydown(b.onkeydown), b.onpaste && a.editable.on("paste", b.onpaste), b.onToolbarClick && a.toolbar.click(b.onToolbarClick), b.onChange) {
var g = function () {
h.triggerOnChange(a.editable)
};
if (e.isMSIE) {
var i = "DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted";
a.editable.on(i, g)
} else a.editable.on("input", g)
}
a.editable.data("callbacks", {
onChange: b.onChange,
onAutoSave: b.onAutoSave,
onImageUpload: b.onImageUpload,
onImageUploadError: b.onImageUploadError,
onFileUpload: b.onFileUpload,
onFileUploadError: b.onFileUpload
})
}, this.detach = function (a, b) {
a.editable.off(), a.popover.off(), a.handle.off(), a.dialog.off(), b.airMode || (a.dropzone.off(), a.toolbar.off(), a.statusbar.off())
}
}, A = function () {
var b = function (a, b) {
var c = b.event, d = b.value, e = b.title, f = b.className, g = b.dropdown, h = b.hide;
return '<button type="button" class="btn btn-default btn-sm btn-small' + (f ? " " + f : "") + (g ? " dropdown-toggle" : "") + '"' + (g ? ' data-toggle="dropdown"' : "") + (e ? ' title="' + e + '"' : "") + (c ? ' data-event="' + c + '"' : "") + (d ? " data-value='" + d + "'" : "") + (h ? " data-hide='" + h + "'" : "") + ' tabindex="-1">' + a + (g ? ' <span class="caret"></span>' : "") + "</button>" + (g || "")
}, c = function (a, c) {
var d = '<i class="' + a + '"></i>';
return b(d, c)
}, d = function (a, b) {
return '<div class="' + a + ' popover bottom in" style="display: none;"><div class="arrow"></div><div class="popover-content">' + b + "</div></div>"
}, g = function (a, b, c, d) {
return '<div class="' + a + ' modal" aria-hidden="false"><div class="modal-dialog"><div class="modal-content">' + (b ? '<div class="modal-header"><button type="button" class="close" aria-hidden="true" tabindex="-1">×</button><h4 class="modal-title">' + b + "</h4></div>" : "") + '<form class="note-modal-form"><div class="modal-body">' + c + "</div>" + (d ? '<div class="modal-footer">' + d + "</div>" : "") + "</form></div></div></div>"
}, h = {
picture: function (a) {
return c("fa fa-picture-o", {event: "showImageDialog", title: a.image.image, hide: !0})
}, link: function (a) {
return c("fa fa-link", {event: "showLinkDialog", title: a.link.link, hide: !0})
}, table: function (a) {
var b = '<ul class="note-table dropdown-menu"><div class="note-dimension-picker"><div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div><div class="note-dimension-picker-highlighted"></div><div class="note-dimension-picker-unhighlighted"></div></div><div class="note-dimension-display"> 1 x 1 </div></ul>';
return c("fa fa-table", {title: a.table.table, dropdown: b})
}, style: function (a, b) {
var d = b.styleTags.reduce(function (b, c) {
var d = a.style["p" === c ? "normal" : c];
return b + '<li><a data-event="formatBlock" href="#" data-value="' + c + '">' + ("p" === c || "pre" === c ? d : "<" + c + ">" + d + "</" + c + ">") + "</a></li>"
}, "");
return c("fa fa-magic", {title: a.style.style, dropdown: '<ul class="dropdown-menu">' + d + "</ul>"})
}, fontname: function (a, c) {
var d = c.fontNames.reduce(function (a, b) {
return e.isFontInstalled(b) ? a + '<li><a data-event="fontName" href="#" data-value="' + b + '"><i class="fa fa-check"></i> ' + b + "</a></li>" : a
}, ""), f = '<span class="note-current-fontname">' + c.defaultFontName + "</span>";
return b(f, {title: a.font.name, dropdown: '<ul class="dropdown-menu">' + d + "</ul>"})
}, color: function (a) {
var c = '<i class="fa fa-font" style="color:black;background-color:yellow;"></i>', d = b(c, {
className: "note-recent-color",
title: a.color.recent,
event: "color",
value: '{"backColor":"yellow"}'
}), e = '<ul class="dropdown-menu"><li><div class="btn-group"><div class="note-palette-title">' + a.color.background + '</div><div class="note-color-reset" data-event="backColor" data-value="inherit" title="' + a.color.transparent + '">' + a.color.setTransparent + '</div><div class="note-color-palette" data-target-event="backColor"></div></div><div class="btn-group"><div class="note-palette-title">' + a.color.foreground + '</div><div class="note-color-reset" data-event="foreColor" data-value="inherit" title="' + a.color.reset + '">' + a.color.resetToDefault + '</div><div class="note-color-palette" data-target-event="foreColor"></div></div></li></ul>', f = b("", {
title: a.color.more,
dropdown: e
});
return d + f
}, bold: function (a) {
return c("fa fa-bold", {event: "bold", title: a.font.bold})
}, italic: function (a) {
return c("fa fa-italic", {event: "italic", title: a.font.italic})
}, underline: function (a) {
return c("fa fa-underline", {event: "underline", title: a.font.underline})
}, clear: function (a) {
return c("fa fa-eraser", {event: "removeFormat", title: a.font.clear})
}, ul: function (a) {
return c("fa fa-list-ul", {event: "insertUnorderedList", title: a.lists.unordered})
}, ol: function (a) {
return c("fa fa-list-ol", {event: "insertOrderedList", title: a.lists.ordered})
}, paragraph: function (a) {
var b = c("fa fa-align-left", {
title: a.paragraph.left,
event: "justifyLeft"
}), d = c("fa fa-align-center", {
title: a.paragraph.center,
event: "justifyCenter"
}), e = c("fa fa-align-right", {
title: a.paragraph.right,
event: "justifyRight"
}), f = c("fa fa-align-justify", {
title: a.paragraph.justify,
event: "justifyFull"
}), g = c("fa fa-outdent", {
title: a.paragraph.outdent,
event: "outdent"
}), h = c("fa fa-indent", {
title: a.paragraph.indent,
event: "indent"
}), i = '<div class="dropdown-menu"><div class="note-align btn-group">' + b + d + e + f + '</div><div class="note-list btn-group">' + h + g + "</div></div>";
return c("fa fa-align-left", {title: a.paragraph.paragraph, dropdown: i})
}, height: function (a, b) {
var d = b.lineHeights.reduce(function (a, b) {
return a + '<li><a data-event="lineHeight" href="#" data-value="' + parseFloat(b) + '"><i class="fa fa-check"></i> ' + b + "</a></li>"
}, "");
return c("fa fa-text-height", {
title: a.font.height,
dropdown: '<ul class="dropdown-menu">' + d + "</ul>"
})
}, help: function (a) {
return c("fa fa-question", {event: "showHelpDialog", title: a.options.help, hide: !0})
}, fullscreen: function (a) {
return c("fa fa-arrows-alt", {event: "fullscreen", title: a.options.fullscreen})
}, codeview: function (a) {
return c("fa fa-code", {event: "codeview", title: a.options.codeview})
}, undo: function (a) {
return c("fa fa-undo", {event: "undo", title: a.history.undo})
}, redo: function (a) {
return c("fa fa-repeat", {event: "redo", title: a.history.redo})
}, hr: function (a) {
return c("fa fa-minus", {event: "insertHorizontalRule", title: a.hr.insert})
}
}, i = function (a, e) {
var f = function () {
var b = c("fa fa-edit", {
title: a.link.edit,
event: "showLinkDialog",
hide: !0
}), e = c("fa fa-unlink", {
title: a.link.unlink,
event: "unlink"
}), f = '<a href="http://www.google.com" target="_blank">www.google.com</a> <div class="note-insert btn-group">' + b + e + "</div>";
return d("note-link-popover", f)
}, g = function () {
var e = b('<span class="note-fontsize-10">100%</span>', {
title: a.image.resizeFull,
event: "resize",
value: "1"
}), f = b('<span class="note-fontsize-10">50%</span>', {
title: a.image.resizeHalf,
event: "resize",
value: "0.5"
}), g = b('<span class="note-fontsize-10">25%</span>', {
title: a.image.resizeQuarter,
event: "resize",
value: "0.25"
}), h = c("fa fa-align-left", {
title: a.image.floatLeft,
event: "floatMe",
value: "left"
}), i = c("fa fa-align-right", {
title: a.image.floatRight,
event: "floatMe",
value: "right"
}), j = c("fa fa-align-justify", {
title: a.image.floatNone,
event: "floatMe",
value: "none"
}), k = c("fa fa-square", {
title: a.image.shapeRounded,
event: "imageShape",
value: "img-rounded"
}), l = c("fa fa-circle-o", {
title: a.image.shapeCircle,
event: "imageShape",
value: "img-circle"
}), m = c("fa fa-picture-o", {
title: a.image.shapeThumbnail,
event: "imageShape",
value: "img-thumbnail"
}), n = c("fa fa-times", {
title: a.image.shapeNone,
event: "imageShape",
value: ""
}), o = c("fa fa-trash-o", {
title: a.image.remove,
event: "removeMedia",
value: "none"
}), p = '<div class="btn-group">' + e + f + g + '</div><div class="btn-group">' + h + i + j + '</div><div class="btn-group">' + k + l + m + n + '</div><div class="btn-group">' + o + "</div>";
return d("note-image-popover", p)
}, i = function () {
for (var b = "", c = 0, f = e.airPopover.length; f > c; c++) {
var g = e.airPopover[c];
b += '<div class="note-' + g[0] + ' btn-group">';
for (var i = 0, j = g[1].length; j > i; i++)b += h[g[1][i]](a, e);
b += "</div>"
}
return d("note-air-popover", b)
};
return '<div class="note-popover">' + f() + g() + (e.airMode ? i() : "") + "</div>"
}, k = function () {
return '<div class="note-handle"><div class="note-control-selection"><div class="note-control-selection-bg"></div><div class="note-control-holder note-control-nw"></div><div class="note-control-holder note-control-ne"></div><div class="note-control-holder note-control-sw"></div><div class="note-control-sizing note-control-se"></div><div class="note-control-selection-info"></div></div></div>'
}, l = function (a, b) {
var c = "note-shortcut-col col-xs-6 note-shortcut-", d = [];
for (var e in b)d.push('<div class="' + c + 'key">' + b[e].kbd + '</div><div class="' + c + 'name">' + b[e].text + "</div>");
return '<div class="note-shortcut-row row"><div class="' + c + 'title col-xs-offset-6">' + a + '</div></div><div class="note-shortcut-row row">' + d.join('</div><div class="note-shortcut-row row">') + "</div>"
}, m = function (a) {
var b = [{kbd: "⌘ + B", text: a.font.bold}, {kbd: "⌘ + I", text: a.font.italic}, {
kbd: "⌘ + U",
text: a.font.underline
}, {kbd: "⌘ + \\", text: a.font.clear}];
return l(a.shortcut.textFormatting, b)
}, n = function (a) {
var b = [{kbd: "⌘ + Z", text: a.history.undo}, {kbd: "⌘ + ⇧ + Z", text: a.history.redo}, {
kbd: "⌘ + ]",
text: a.paragraph.indent
}, {kbd: "⌘ + [", text: a.paragraph.outdent}, {kbd: "⌘ + ENTER", text: a.hr.insert}];
return l(a.shortcut.action, b)
}, o = function (a) {
var b = [{kbd: "⌘ + ⇧ + L", text: a.paragraph.left}, {
kbd: "⌘ + ⇧ + E",
text: a.paragraph.center
}, {kbd: "⌘ + ⇧ + R", text: a.paragraph.right}, {
kbd: "⌘ + ⇧ + J",
text: a.paragraph.justify
}, {kbd: "⌘ + ⇧ + NUM7", text: a.lists.ordered}, {kbd: "⌘ + ⇧ + NUM8", text: a.lists.unordered}];
return l(a.shortcut.paragraphFormatting, b)
}, p = function (a) {
var b = [{kbd: "⌘ + NUM0", text: a.style.normal}, {kbd: "⌘ + NUM1", text: a.style.h1}, {
kbd: "⌘ + NUM2",
text: a.style.h2
}, {kbd: "⌘ + NUM3", text: a.style.h3}, {kbd: "⌘ + NUM4", text: a.style.h4}, {
kbd: "⌘ + NUM5",
text: a.style.h5
}, {kbd: "⌘ + NUM6", text: a.style.h6}];
return l(a.shortcut.documentStyle, b)
}, q = function (a, b) {
var c = b.extraKeys, d = [];
for (var e in c)c.hasOwnProperty(e) && d.push({kbd: e, text: c[e]});
return l(a.shortcut.extraKeys, d)
}, r = function (a, b) {
var c = 'class="note-shortcut note-shortcut-col col-sm-6 col-xs-12"', d = ["<div " + c + ">" + n(a, b) + "</div><div " + c + ">" + m(a, b) + "</div>", "<div " + c + ">" + p(a, b) + "</div><div " + c + ">" + o(a, b) + "</div>"];
return b.extraKeys && d.push("<div " + c + ">" + q(a, b) + "</div>"), '<div class="note-shortcut-row row">' + d.join('</div><div class="note-shortcut-row row">') + "</div>"
}, s = function (a) {
return a.replace(/⌘/g, "Ctrl").replace(/⇧/g, "Shift")
}, t = {
image: function (a, b) {
var c = "";
if (b.maximumImageFileSize) {
var d = Math.floor(Math.log(b.maximumImageFileSize) / Math.log(1024)), e = 1 * (b.maximumImageFileSize / Math.pow(1024, d)).toFixed(2) + " " + " KMGTP"[d] + "B";
c = "<small>" + a.image.maximumFileSize + " : " + e + "</small>"
}
var f = '<div class="form-group row-fluid note-group-select-from-files"><label>' + a.image.selectFromFiles + '</label><input class="note-image-input" type="file" name="files" accept="image/*" multiple="multiple" />' + c + '</div><div class="form-group row-fluid"><label>' + a.image.url + '</label><input class="note-image-url form-control span12" type="text" /></div>', h = '<button href="#" class="btn btn-primary note-image-btn disabled" disabled>' + a.image.insert + "</button>";
return g("note-image-dialog", a.image.insert, f, h)
}, link: function (a, b) {
var c = '<div class="form-group row-fluid"><label>' + a.link.textToDisplay + '</label><input class="note-link-text form-control span12" type="text" /></div><div class="form-group row-fluid"><label>' + a.link.url + '</label><input class="note-link-url form-control span12" type="text" /></div>' + (b.disableLinkTarget ? "" : '<div class="checkbox"><label><input type="checkbox" checked> ' + a.link.openInNewWindow + "</label></div>"), d = '<button href="#" class="btn btn-primary note-link-btn disabled" disabled>' + a.link.insert + "</button>";
return g("note-link-dialog", a.link.insert, c, d)
}, help: function (a, b) {
var c = '<a class="modal-close pull-right" aria-hidden="true" tabindex="-1">' + a.shortcut.close + '</a><div class="title">' + a.shortcut.shortcuts + "</div>" + (e.isMac ? r(a, b) : s(r(a, b))) + '<p class="text-center"><a href="//hackerwins.github.io/summernote/" target="_blank">Summernote 0.6.0</a> · <a href="//github.com/HackerWins/summernote" target="_blank">Project</a> · <a href="//github.com/HackerWins/summernote/issues" target="_blank">Issues</a></p>';
return g("note-help-dialog", "", c, "")
}
}, u = function (b, c) {
var d = "";
return a.each(t, function (a, e) {
d += e(b, c)
}), '<div class="note-dialog">' + d + "</div>"
}, v = function () {
return '<div class="note-resizebar"><div class="note-icon-bar"></div><div class="note-icon-bar"></div><div class="note-icon-bar"></div></div>'
}, w = function (a) {
return e.isMac && (a = a.replace("CMD", "⌘").replace("SHIFT", "⇧")), a.replace("BACKSLASH", "\\").replace("SLASH", "/").replace("LEFTBRACKET", "[").replace("RIGHTBRACKET", "]")
}, x = function (b, c, d) {
var e = f.invertObject(c), g = b.find("button");
g.each(function (b, c) {
var d = a(c), f = e[d.data("event")];
f && d.attr("title", function (a, b) {
return b + " (" + w(f) + ")"
})
}).tooltip({container: "body", trigger: "hover", placement: d || "top"}).on("click", function () {
a(this).tooltip("hide")
})
}, y = function (b, c) {
var d = c.colors;
b.find(".note-color-palette").each(function () {
for (var b = a(this), c = b.attr("data-target-event"), e = [], f = 0, g = d.length; g > f; f++) {
for (var h = d[f], i = [], j = 0, k = h.length; k > j; j++) {
var l = h[j];
i.push(['<button type="button" class="note-color-btn" style="background-color:', l, ';" data-event="', c, '" data-value="', l, '" title="', l, '" data-toggle="button" tabindex="-1"></button>'].join(""))
}
e.push('<div class="note-color-row">' + i.join("") + "</div>")
}
b.html(e.join(""))
})
};
this.createLayoutByAirMode = function (b, c) {
var d = c.langInfo, g = c.keyMap[e.isMac ? "mac" : "pc"], h = f.uniqueId();
b.addClass("note-air-editor note-editable"), b.attr({id: "note-editor-" + h, contentEditable: !0});
var j = document.body, l = a(i(d, c));
l.addClass("note-air-layout"), l.attr("id", "note-popover-" + h), l.appendTo(j), x(l, g), y(l, c);
var m = a(k());
m.addClass("note-air-layout"), m.attr("id", "note-handle-" + h), m.appendTo(j);
var n = a(u(d, c));
n.addClass("note-air-layout"), n.attr("id", "note-dialog-" + h), n.find("button.close, a.modal-close").click(function () {
a(this).closest(".modal").modal("hide")
}), n.appendTo(j)
}, this.createLayoutByFrame = function (b, c) {
var d = c.langInfo, f = a('<div class="note-editor"></div>');
c.width && f.width(c.width), c.height > 0 && a('<div class="note-statusbar">' + (c.disableResizeEditor ? "" : v()) + "</div>").prependTo(f);
var g = !b.is(":disabled"), l = a('<div class="note-editable" contentEditable="' + g + '"></div>').prependTo(f);
c.height && l.height(c.height), c.direction && l.attr("dir", c.direction), c.placeholder && l.attr("data-placeholder", c.placeholder), l.html(j.html(b)), a('<textarea class="note-codable"></textarea>').prependTo(f);
for (var m = "", n = 0, o = c.toolbar.length; o > n; n++) {
var p = c.toolbar[n][0], q = c.toolbar[n][1];
m += '<div class="note-' + p + ' btn-group">';
for (var r = 0, s = q.length; s > r; r++) {
var t = h[q[r]];
a.isFunction(t) && (m += t(d, c))
}
m += "</div>"
}
m = '<div class="note-toolbar btn-toolbar">' + m + "</div>";
var w = a(m).prependTo(f), z = c.keyMap[e.isMac ? "mac" : "pc"];
y(w, c), x(w, z, "bottom");
var A = a(i(d, c)).prependTo(f);
y(A, c), x(A, z), a(k()).prependTo(f);
var B = a(u(d, c)).prependTo(f);
B.find("button.close, a.modal-close").click(function () {
a(this).closest(".modal").modal("hide")
}), a('<div class="note-dropzone"><div class="note-dropzone-message"></div></div>').prependTo(f), f.insertAfter(b), b.hide()
}, this.noteEditorFromHolder = function (b) {
return b.hasClass("note-air-editor") ? b : b.next().hasClass("note-editor") ? b.next() : a()
}, this.createLayout = function (a, b) {
this.noteEditorFromHolder(a).length || (b.airMode ? this.createLayoutByAirMode(a, b) : this.createLayoutByFrame(a, b))
}, this.layoutInfoFromHolder = function (a) {
var b = this.noteEditorFromHolder(a);
if (b.length) {
var c = j.buildLayoutInfo(b);
for (var d in c)c.hasOwnProperty(d) && (c[d] = c[d].call());
return c
}
}, this.removeLayout = function (a, b, c) {
c.airMode ? (a.removeClass("note-air-editor note-editable").removeAttr("id contentEditable"), b.popover.remove(), b.handle.remove(), b.dialog.remove()) : (a.html(b.editable.html()), b.editor.remove(), a.show())
}, this.getTemplate = function () {
return {button: b, iconButton: c, dialog: g}
}, this.addButtonInfo = function (a, b) {
h[a] = b
}, this.addDialogInfo = function (a, b) {
t[a] = b
}
};
a.summernote = a.summernote || {}, a.extend(a.summernote, l);
var B = new A, C = new z;
a.extend(a.summernote, {
renderer: B,
eventHandler: C,
core: {agent: e, dom: j, range: k},
pluginEvents: {}
}), a.summernote.addPlugin = function (b) {
b.buttons && a.each(b.buttons, function (a, b) {
B.addButtonInfo(a, b)
}), b.dialogs && a.each(b.dialogs, function (a, b) {
B.addDialogInfo(a, b)
}), b.events && a.each(b.events, function (b, c) {
a.summernote.pluginEvents[b] = c
}), b.langs && a.each(b.langs, function (b, c) {
a.summernote.lang[b] && a.extend(a.summernote.lang[b], c)
}), b.options && a.extend(a.summernote.options, b.options)
}, a.fn.extend({
summernote: function (b) {
if (b = a.extend({}, a.summernote.options, b), b.langInfo = a.extend(!0, {}, a.summernote.lang["en-US"], a.summernote.lang[b.lang]), this.each(function (c, d) {
var e = a(d);
B.createLayout(e, b);
var f = B.layoutInfoFromHolder(e);
C.attach(f, b), j.isTextarea(e[0]) && e.closest("form").submit(function () {
var a = e.code();
e.val(a), b.onsubmit && b.onsubmit(a)
})
}), this.first().length && b.focus) {
var c = B.layoutInfoFromHolder(this.first());
c.editable.focus()
}
return this.length && b.oninit && b.oninit(), this
}, code: function (b) {
if (void 0 === b) {
var c = this.first();
if (!c.length)return;
var d = B.layoutInfoFromHolder(c);
if (d && d.editable) {
var f = d.editor.hasClass("codeview");
return f && e.hasCodeMirror && d.codable.data("cmEditor").save(), f ? d.codable.val() : d.editable.html()
}
return j.isTextarea(c[0]) ? c.val() : c.html()
}
return this.each(function (c, d) {
var e = B.layoutInfoFromHolder(a(d));
e && e.editable && e.editable.html(b)
}), this
}, destroy: function () {
return this.each(function (b, c) {
var d = a(c), e = B.layoutInfoFromHolder(d);
if (e && e.editable) {
var f = e.editor.data("options");
C.detach(e, f), B.removeLayout(d, e, f)
}
}), this
}
})
}); |
this.NesDb = this.NesDb || {};
NesDb[ 'F8FAA774708E108984158FCD9BBC5482ED7165C4' ] = {
"$": {
"name": "M.C. Kids",
"class": "Licensed",
"catalog": "NES-4Q-USA",
"publisher": "Virgin Games",
"developer": "Virgin Games",
"region": "USA",
"players": "2",
"date": "1992-02"
},
"cartridge": [
{
"$": {
"system": "NES-NTSC",
"crc": "B0EBF3DB",
"sha1": "F8FAA774708E108984158FCD9BBC5482ED7165C4",
"dump": "ok",
"dumper": "polarz",
"datedumped": "2006-11-04"
},
"board": [
{
"$": {
"type": "NES-TSROM",
"pcb": "NES-TSROM-08",
"mapper": "4"
},
"prg": [
{
"$": {
"name": "NES-4Q-0 PRG",
"size": "128k",
"crc": "6C15F90E",
"sha1": "5C695483AB4E9D3FB5D4A10A96E7C85E8774362C"
}
}
],
"chr": [
{
"$": {
"name": "NES-4Q-0 CHR",
"size": "128k",
"crc": "32AF2F1B",
"sha1": "A54EE0C06CF82D3092612DB7A370DA948A270666"
}
}
],
"wram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "MMC3C"
}
}
],
"cic": [
{
"$": {
"type": "6113B1"
}
}
]
}
]
},
{
"$": {
"system": "NES-NTSC",
"crc": "B0EBF3DB",
"sha1": "F8FAA774708E108984158FCD9BBC5482ED7165C4",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2005-11-21"
},
"board": [
{
"$": {
"type": "NES-TSROM",
"pcb": "NES-TSROM-08",
"mapper": "4"
},
"prg": [
{
"$": {
"name": "NES-4Q-0 PRG",
"size": "128k",
"crc": "6C15F90E",
"sha1": "5C695483AB4E9D3FB5D4A10A96E7C85E8774362C"
}
}
],
"chr": [
{
"$": {
"name": "NES-4Q-0 CHR",
"size": "128k",
"crc": "32AF2F1B",
"sha1": "A54EE0C06CF82D3092612DB7A370DA948A270666"
}
}
],
"wram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "MMC3B"
}
}
],
"cic": [
{
"$": {
"type": "6113B1"
}
}
]
}
]
}
],
"gameGenieCodes": [
{
"name": "Start with 2 lives",
"codes": [
[
"PAKILYLA"
]
]
},
{
"name": "Start with 7 lives",
"codes": [
[
"TAKILYLA"
]
]
},
{
"name": "Start with 10 lives",
"codes": [
[
"PAKILYLE"
]
]
},
{
"name": "Infinite lives",
"codes": [
[
"GXKSUOSE"
]
]
},
{
"name": "Infinite hearts",
"codes": [
[
"EGETYTIA"
]
]
},
{
"name": "Don't lose Golden Arches when hit",
"codes": [
[
"EKNVYIIA"
]
]
},
{
"name": "Super jump",
"codes": [
[
"AOVEGTGE",
"AEVEPTLA"
]
]
},
{
"name": "1 heart per life",
"codes": [
[
"AAKSAYZA",
"AEKSNPZA"
]
]
},
{
"name": "8 hearts per life",
"codes": [
[
"YAKSAYZA",
"YEKSNPZA"
]
]
}
]
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
TicketType = mongoose.model('TicketType'),
_ = require('lodash');
/**
* Find article by id
*/
exports.ticketType = function(req, res, next, id) {
TicketType.load(id, function(err, ticketType) {
if (err) return next(err);
if (!ticketType) return next(new Error('Failed to load ticketType ' + id));
req.ticketType = ticketType;
next();
});
};
/**
* Create TicketType
*/
exports.create = function(req, res) {
var ticketType = new TicketType(req.body);
ticketType.save(function(err) {
var errorMsg = '';
if (err) {
switch(err.code){
case 11000:
case 11001:
errorMsg = 'Name already exsits.';
break;
default:
errorMsg ='Error occured while processing your request.';
}
return res.status(400).send(errorMsg);
}
res.jsonp(ticketType);
});
};
/**
* Update an ticketType
*/
exports.update = function(req, res) {
var ticketType = req.ticketType;
ticketType = _.extend(ticketType, req.body);
ticketType.save(function(err) {
var errorMsg = '';
if (err) {
switch(err.code){
case 11000:
case 11001:
errorMsg = 'Name already exsits.';
break;
default:
errorMsg ='Error occured while processing your request.';
}
return res.status(400).send(errorMsg);
}
res.jsonp(ticketType);
});
};
/**
* Show an ticketType
*/
exports.show = function(req, res) {
res.jsonp(req.ticketType);
};
/**
* List of TicketType
*/
exports.all = function(req, res) {
TicketType.find().exec(function(err, ticketType) {
if (err) {
return res.jsonp(500, {
error: 'Cannot list the ticketType'
});
}
res.jsonp(ticketType);
});
}; |
var React = require('react');
var Header = require('./Header.react');
var Instructions = React.createClass({
render: function() {
return (
<div className="ink-grid">
<Header page='instructions'/>
<hr />
<div className="column-group gutters">
<div className="all-100 center">
<p>
I am Nataliia Uvarova, Master student at Gjovik University
College, writing Master thesis in the field of Information
Retrieval.
</p>
<p>
The topic of the reseach is Summarization of Microblog data. You
are herebly asked to help the research by producing a golden
human-generated summaries for the given topics. It should take
from 30 minutes to 1 hour of work, depending on your speed and
what topics you will get. Each person produces summaries for
three topic from nine available. The topics are assigned
randomly.
</p>
<p>
The summary of the topic --- is a subset of all tweets posted on
the topic. In an ideal situation, the summary covers every aspect
of the topic, as presented in the complete set of tweets. Each
tweet included in the summary should therefore add some piece of
information about the topic that is not already covered in the
summary. The final summary may consist of a few core tweets, that
cover the generics of the topic, and some that adds some relevant
detail to this core summary.
</p>
<h4>What you should do:</h4>
<ul>
<li>
After you have read these Instructions and know what is expected
from you, press the green button on the top right corner. You will
then be redirected to the page with the first topic.
</li>
<li>On the top of the page you will see the topic name. The
presented tweets and the produced summary will be about this
topic.There are different types of topics. The topic can be quite
specific -- for instance about event like Oscar nominations or be a
broad one --- like opinions about fast-food chains in February 2011.
</li>
<li>You will see the list of tweets on the left --- it is a list of all
available tweets about particular event. The empty list on the right --- it is
where you should produce your summary.</li>
<li>You can move tweets between lists pressing "select"/"unselect"
buttons on the desired tweets.</li>
<li>There are quite a few tweets available, and your task is to select a
group of them which <em>together</em> form a representative summary of all the
tweets posted on this topic. There are no right or wrong answers --- select
tweets that you believe represent the topic in the best way.</li>
<li>The length of the summary should be around 5 to 10 tweets. Please try not
to make it too short or to long, except if you really fill that you cannot
add/delete tweets.</li>
<li>Please organize the tweets in the summary in order of increasing
importantness --- the first tweet represent the essence of the topic best,
next tweets add more information and details.
You can use "up"/"down" buttons for this.</li>
<li>To simplify work with long list of tweets there is a "hide" button on each unseleted tweet.
You can hide tweets that you sure, should not be present in the summary.
If you accidentaly hide tweet, use "Show hidden items" button to show all hidden
tweets. Then you can restore any of them.
</li>
<li>You can press "Read instructions" button at any time, dont worry, your
progress will be saved.</li>
<li>When you are satisfied with the summary, press the "Submit and next"
button, your summary will be saved on the server and new topic will be
presented.</li>
<li>Repeat the same procedure for a new topic. There will be approximately three
topics.</li>
</ul>
<p>Thank you for participating!</p>
<p>If you are interested in knowing more about the results from this research project, please contact me at nataliia.uvarova@gmail.com</p>
</div>
</div>
</div>
);
}
});
module.exports = Instructions;
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["../../core/Accessor","../../core/kebabDictionary","../../geometry/support/jsonUtils","dojo/_base/array"],function(e,i,t,s){var r=i({109006:"centimeters",9102:"decimal-degrees",109005:"decimeters",9002:"feet",109009:"inches",9036:"kilometers",9001:"meters",9035:"miles",109007:"millimeters",109012:"nautical-miles",9096:"yards"}),o=e.createSubclass({declaredClass:"esri.tasks.support.GeneralizeParameters",properties:{geometries:null,deviationUnit:null,maxDeviation:null},toJSON:function(){var e=s.map(this.geometries,function(e){return e.toJSON()}),i={};return this.geometries&&this.geometries.length>0&&(i.geometries=JSON.stringify({geometryType:t.getJsonType(this.geometries[0]),geometries:e}),i.sr=JSON.stringify(this.geometries[0].spatialReference.toJSON())),this.deviationUnit&&(i.deviationUnit=r.toJSON(this.deviationUnit)),this.maxDeviation&&(i.maxDeviation=this.maxDeviation),i}});return o}); |
var mongoose = require('mongoose')
var mongooseHistory=require('mongoose-history')
var config =require('../config')
console.log(config.mongodb.server+config.mongodb.port+config.mongodb.db)
mongoose.connect(config.mongodb.server+config.mongodb.port+config.mongodb.db)
/*Schema*/
var organisationSchema = new mongoose.Schema({
registrations:[
{
nationalRegistrations:[
{
informationSource:{
type:String,
required:true,
enum:['BASUN','CustomerGiven']
},
organisationNumber:{
type:String,
required:true,
maxlength:[12,'organisationNumber must be 12 chars!'],
minlength:[12,'organisationNumber must be 12 chars!']
},
isActive:{
type:Boolean,
required:true
}
}]
}],
partyNames: [
{
fullName: {
type: String, selected: true, minlength: [2, 'The fullName must be greater or equal to 2 chars'],
maxlength: [50, 'The fullName must be less or equal to 50 chars'],
required: [true, 'The fullName cannot be empty!']
},
informationSource: {
type: String,
required: [true, 'The informationSource property is empty or not one of the enumerations!'],
enum: ['CustomerGiven', 'Official']
}
}
],
documentMetaData: {
version: {
type: Number,
default: 1
},
documentCreatedDate: {
type: Date,
default: Date.now()//'2016-06-06'
},
documentLastUpdatedDate: {
type: Date,
default: Date.now()//'2016-06-06'
}
}
}, { minimize: false })
/*Custom validations*/
organisationSchema.path('partyNames').validate(function (partyNames) {
if (!partyNames) { return false }
else if (partyNames.length === 0) { return false }
return true
}, 'A person must have at least one partyName!')
organisationSchema.path('registrations')
.schema.path('nationalRegistrations')
.schema.path('organisationNumber')
.validate(function (OrganisationNumber) {
if (!OrganisationNumber) { return false }
else if (OrganisationNumber.length===0) { return false }
return true
}, 'A organisationNumber must be of the format 16xxxxxxxxxx!')
/*Custom methods*/
organisationSchema.methods.map=function(mapObject){
//console.log(mapObject)
this.registrations=mapObject.registrations
this.partyNames=mapObject.partyNames
this.documentMetaData.documentLastUpdatedDate=Date.now()
}
organisationSchema.plugin(mongooseHistory)
/*Model*/
var Organisation = mongoose.model('Organisation', organisationSchema)
/*Exports*/
module.exports = Organisation
|
version https://git-lfs.github.com/spec/v1
oid sha256:cd9afdec70ea74bd87a91ce0e2094c4c9dad4f77fd60224208973b4302f9ebb5
size 5116
|
var code = {
0xff: "Some code"
} |
import alt from '../core/alt';
import UserActions from '../actions/UserActions';
/**
* user profile and operations
*/
class UserStore {
constructor() {
// real-auth
this.user = {
id: null,
token: null,
personname: null,
logo: null,
provider: null,
};
this.exportPublicMethods({
isLoggedIn: this.isLoggedIn,
getUser: this.getUser,
getUid: this.getUid,
getPersonName: this.getPersonName,
});
this.bindActions(UserActions);
}
//
onLogin(info) {
this.user = info;
}
//
onLogout() {
this.user.id = null;
}
// static
isLoggedIn() {
const uid = this.getState().user.id;
return (uid !== null);
}
// static
getUser() {
return this.getState().user;
}
// static
getUid() {
const st = this.getState().user;
return st.id;
}
// static
getPersonName() {
const st = this.getState().user;
return st.personname;
}
}
export default alt.createStore(UserStore, 'UserStore');
|
/*global module:false*/
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed MIT */\n',
// Task configuration.
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true
},
dist: {
src: ['src/index.js', 'src/validator/*'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
src: '<%= concat.dist.dest %>',
dest: 'dist/<%= pkg.name %>.min.js'
}
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
globals: {
window: true,
Luhnar: true
}
},
gruntfile: {
src: 'Gruntfile.js'
},
lib_test: {
src: ['src/*.js', 'src/**/*js']
}
},
qunit: {
all: ['test/**/*.html']
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
// Default task.
grunt.registerTask('default', ['jshint']);
grunt.registerTask('test', ['qunit']);
grunt.registerTask('build', ['jshint', 'concat', 'uglify', 'qunit']);
};
|
import React, { Component } from 'react';
import { Jumbotron } from 'react-bootstrap';
import { connect } from 'react-redux';
class Home extends Component {
render() {
return (
<div>
<Jumbotron className="text-center">
<h1 className="title">
audio-editor
<br />
<small>An audio editor built with React</small>
</h1>
<p>
This is currently a work-in-progress, and not yet
complete. It is being actively developed, and you
can log feature requests on the
<a href="https://github.com/skratchdot/audio-editor/issues">
Github Issues Page.
</a>
</p>
</Jumbotron>
</div>
);
}
}
export default connect()(Home);
|
import React from 'react';
import PropTypes from 'prop-types';
import style from './BtnAddCard.sass';
const BtnAddCard = ({ onClick }) => (
<button onClick={onClick} className={style['btn-add-card']} > + Add Card </button>
);
BtnAddCard.propTypes = {
onClick: PropTypes.func.isRequired,
};
export default BtnAddCard;
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.5.1-5-1
description: >
Defining a property named 4294967295 (2**32-1)(not an array
element)
includes: [runTestCase.js]
---*/
function testcase() {
var a =[];
a[4294967295] = "not an array element" ;
return a[4294967295] === "not an array element";
}
runTestCase(testcase);
|
import { combineReducers } from 'redux';
import PostsReducer from './reducer_posts';
import { reducer as formReducer } from 'redux-form';
const rootReducer = combineReducers({
post: PostsReducer,
form: formReducer
});
export default rootReducer;
|
import * as actions from './actions';
export const initialState = {
open: false,
activeAreaId: null,
};
const setConfirmSubscriptionModalSettings = (state, { payload }) => ({
...state,
...payload,
});
export default {
[actions.setConfirmSubscriptionModalSettings]: setConfirmSubscriptionModalSettings,
};
|
// Meter class that generates a number correlated to audio volume.
// The meter class itself displays nothing, but it makes the
// instantaneous and time-decaying volumes available for inspection.
// It also reports on the fraction of samples that were at or near
// the top of the measurement range.
function SoundMeter (context) {
var AudioContext = window.AudioContext || window.webkitAudioContext;
this.context = new AudioContext();
this.instant = 0.0;
this.script = this.context.createScriptProcessor (2048, 1, 1);
this.stopped = true;
var self = this;
this.script.onaudioprocess = function (event) {
var input = event.inputBuffer.getChannelData (0);
var i;
var sum = 0.0;
for (i = 0; i < input.length; ++i)
sum += input[i]*input[i]*10000;
self.instant = Math.sqrt(sum) / input.length;
};
}
SoundMeter.prototype.connectToSource = function (stream) {
var self = this;
if (this.stopped)
//Stop
this.stop();
return new Promise(function(resolve, reject) {
try {
self.mic = self.context.createMediaStreamSource(stream);
self.mic.connect(self.script);
// necessary to make sample run, but should not be.
self.script.connect (self.context.destination);
//Done
resolve();
} catch (e) {
reject(e);
}
});
};
SoundMeter.prototype.stop = function () {
if(this.stopped)
return;
this.stopped = true;
try{
if(this.script){
this.script.onaudioprocess = null;
this.script.disconnect(this.context.destination);
}
this.mic && this.mic.disconnect();
} catch (e){
}
};
|
(function () {
'use strict';
angular.module("Root", [])
.config(function ($stateProvider) {
$stateProvider
.state('root', {
url: '/',
views: {
'main': {
templateUrl: './modules/root/root.html',
controller: 'rootController',
controllerAs: 'vm'
}
}
});
})
})(); |
var config = {
TUMBLR_KEY: process.env.TUMBLR_KEY,
TUMBLR_SECRET: process.env.TUMBLR_SECRET,
ACCESS_TOKEN: process.env.ACCESS_TOKEN,
ACCESS_SECRET: process.env.ACCESS_SECRET,
GOOGLE_APP_KEY: process.env.GOOGLE_APP_KEY,
gif_path: './temp/gifs',
blogname: process.env.BLOG_NAME
};
module.exports = config;
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define("require exports ../../core/compilerUtils ../../core/Error ../HeightModelInfo ../../layers/support/arcgisLayerUrl".split(" "),function(v,f,l,g,k,r){function t(a,c,b){if(!h(a)||!h(c))return 4;if(null==a||null==c)return 0;if(!b&&a.heightUnit!==c.heightUnit)return 1;if(a.heightModel!==c.heightModel)return 2;switch(a.heightModel){case "gravity-related-height":return 0;case "ellipsoidal":return a.vertCRS===c.vertCRS?0:3;default:return 4}}function h(a){return null==a||null!=a.heightModel&&null!=
a.heightUnit}function m(a){var c=a.url&&r.parse(a.url);return(null!=(a.spatialReference&&a.spatialReference.vcsWkid)||!c||"ImageServer"!==c.serverType)&&"heightModelInfo"in a&&a.heightModelInfo?a.heightModelInfo:n(a)?k.deriveUnitFromSR(u,a.spatialReference):null}function p(a){if("unknown"===a.type||!("capabilities"in a))return!1;switch(a.type){case "csv":case "feature":case "geojson":return!0;case "imagery":case "map-image":case "tile":case "vector-tile":case null:return!1;default:return l.neverReached(a),
!1}}function n(a){return p(a)?!!(a.capabilities&&a.capabilities.data&&a.capabilities.data.supportsZ):q(a)}function q(a){switch(a.type){case "building-scene":case "elevation":case "integrated-mesh":case "point-cloud":case "scene":return!0;case "base-dynamic":case "base-elevation":case "base-tile":case "bing-maps":case "csv":case "geojson":case "feature":case "geo-rss":case "graphics":case "group":case "imagery":case "imagery-tile":case "kml":case "map-image":case "map-notes":case "open-street-map":case "route":case "stream":case "tile":case "unknown":case "unsupported":case "vector-tile":case "web-tile":case "wms":case "wmts":case null:break;
default:l.neverReached(a)}return!1}Object.defineProperty(f,"__esModule",{value:!0});f.validateWebSceneError=function(a,c){if(!a)return null;if(!h(a))return new g("webscene:unsupported-height-model-info","The vertical coordinate system of the scene is not supported",{heightModelInfo:a});var b=a.heightUnit;a=k.deriveUnitFromSR(a,c).heightUnit;return b!==a?new g("webscene:incompatible-height-unit","The vertical units of the scene ("+b+") must match the horizontal units of the scene ("+a+")",{verticalUnit:b,
horizontalUnit:a}):null};f.rejectLayerError=function(a,c,b){var d=m(a),f=t(d,c,b),e=null;if(d){var h=k.deriveUnitFromSR(d,a.spatialReference).heightUnit;b||h===d.heightUnit||(e=new g("layerview:unmatched-height-unit","The vertical units of the layer must match the horizontal units ("+h+")",{horizontalUnit:h}))}if(!("heightModelInfo"in a&&null!=a.heightModelInfo||null!=a.spatialReference)&&n(a)||4===f||e)return new g("layerview:unsupported-height-model-info","The vertical coordinate system of the layer is not supported",
{heightModelInfo:d,error:e});e=null;switch(f){case 1:a=d.heightUnit||"unknown";b=c.heightUnit||"unknown";e=new g("layerview:incompatible-height-unit","The vertical units of the layer ("+a+") must match the vertical units of the scene ("+b+")",{layerUnit:a,sceneUnit:b});break;case 2:a=d.heightModel||"unknown";b=c.heightModel||"unknown";e=new g("layerview:incompatible-height-model","The height model of the layer ("+a+") must match the height model of the scene ("+b+")",{layerHeightModel:a,sceneHeightModel:b});
break;case 3:a=d.vertCRS||"unknown",b=c.vertCRS||"unknown",e=new g("layerview:incompatible-vertical-datum","The vertical datum of the layer ("+a+") must match the vertical datum of the scene ("+b+")",{layerDatum:a,sceneDatum:b})}return e?new g("layerview:incompatible-height-model-info","The vertical coordinate system of the layer is incompatible with the scene",{layerHeightModelInfo:d,sceneHeightModelInfo:c,error:e}):null};f.deriveHeightModelInfoFromLayer=m;f.mayHaveHeightModelInfo=function(a){return null!=
a.layers||q(a)||p(a)||"heightModelInfo"in a};var u=new k({heightModel:"gravity-related-height"})}); |
/**
* @license Angulartics
* (c) 2013 Luis Farzati http://angulartics.github.io/
* License: MIT
*/
(function(angular, analytics) {
'use strict';
var angulartics = window.angulartics || (window.angulartics = {});
angulartics.waitForVendorCount = 0;
angulartics.waitForVendorApi = function (objectName, delay, containsField, registerFn, onTimeout) {
if (!onTimeout) { angulartics.waitForVendorCount++; }
if (!registerFn) { registerFn = containsField; containsField = undefined; }
if (!Object.prototype.hasOwnProperty.call(window, objectName) || (containsField !== undefined && window[objectName][containsField] === undefined)) {
setTimeout(function () { angulartics.waitForVendorApi(objectName, delay, containsField, registerFn, true); }, delay);
}
else {
angulartics.waitForVendorCount--;
registerFn(window[objectName]);
}
};
/**
* @ngdoc overview
* @name angulartics
*/
angular.module('angulartics', [])
.provider('$analytics', $analytics)
.run(['$rootScope', '$window', '$analytics', '$injector', $analyticsRun])
.directive('analyticsOn', ['$analytics', analyticsOn])
.config(['$provide', exceptionTrack]);
function $analytics() {
var vm = this;
var settings = {
pageTracking: {
autoTrackFirstPage: true,
autoTrackVirtualPages: true,
trackRelativePath: false,
trackRoutes: true,
trackStates: true,
autoBasePath: false,
basePath: '',
excludedRoutes: [],
queryKeysWhitelisted: [],
queryKeysBlacklisted: [],
filterUrlSegments: []
},
eventTracking: {},
bufferFlushDelay: 1000, // Support only one configuration for buffer flush delay to simplify buffering
trackExceptions: false,
optOut: false,
developerMode: false // Prevent sending data in local/development environment
};
// List of known handlers that plugins can register themselves for
var knownHandlers = [
'pageTrack',
'eventTrack',
'exceptionTrack',
'transactionTrack',
'setAlias',
'setUsername',
'setUserProperties',
'setUserPropertiesOnce',
'setSuperProperties',
'setSuperPropertiesOnce',
'incrementProperty',
'userTimings',
'clearCookies'
];
// Cache and handler properties will match values in 'knownHandlers' as the buffering functons are installed.
var cache = {};
var handlers = {};
var handlerOptions = {};
// General buffering handler
function bufferedHandler(handlerName){
return function(){
if(angulartics.waitForVendorCount){
if(!cache[handlerName]){ cache[handlerName] = []; }
cache[handlerName].push(arguments);
}
};
}
// As handlers are installed by plugins, they get pushed into a list and invoked in order.
function updateHandlers(handlerName, fn, options){
if(!handlers[handlerName]){
handlers[handlerName] = [];
}
handlers[handlerName].push(fn);
handlerOptions[fn] = options;
return function(){
if(!this.settings.optOut) {
var handlerArgs = Array.prototype.slice.apply(arguments);
return this.$inject(['$q', angular.bind(this, function($q) {
return $q.all(handlers[handlerName].map(function(handlerFn) {
var options = handlerOptions[handlerFn] || {};
if (options.async) {
var deferred = $q.defer();
var currentArgs = angular.copy(handlerArgs);
currentArgs.unshift(deferred.resolve);
handlerFn.apply(this, currentArgs);
return deferred.promise;
} else{
return $q.when(handlerFn.apply(this, handlerArgs));
}
}, this));
})]);
}
};
}
// The api (returned by this provider) gets populated with handlers below.
var api = {
settings: settings
};
// Opt in and opt out functions
api.setOptOut = function(optOut) {
vm.settings.optOut = optOut;
triggerRegister();
};
api.getOptOut = function() {
return vm.settings.optOut;
};
// Will run setTimeout if delay is > 0
// Runs immediately if no delay to make sure cache/buffer is flushed before anything else.
// Plugins should take care to register handlers by order of precedence.
function onTimeout(fn, delay){
if(delay){
setTimeout(fn, delay);
} else {
fn();
}
}
var provider = {
$get: ['$injector', function($injector) {
return apiWithInjector($injector);
}],
api: api,
settings: settings,
virtualPageviews: function (value) { this.settings.pageTracking.autoTrackVirtualPages = value; },
trackStates: function (value) { this.settings.pageTracking.trackStates = value; },
trackRoutes: function (value) { this.settings.pageTracking.trackRoutes = value; },
excludeRoutes: function(routes) { this.settings.pageTracking.excludedRoutes = routes; },
queryKeysWhitelist: function(keys) { this.settings.pageTracking.queryKeysWhitelisted = keys; },
queryKeysBlacklist: function(keys) { this.settings.pageTracking.queryKeysBlacklisted = keys; },
filterUrlSegments: function(filters) { this.settings.pageTracking.filterUrlSegments = filters; },
firstPageview: function (value) { this.settings.pageTracking.autoTrackFirstPage = value; },
withBase: function (value) {
this.settings.pageTracking.basePath = (value) ? angular.element(document).find('base').attr('href') : '';
},
withAutoBase: function (value) { this.settings.pageTracking.autoBasePath = value; },
trackExceptions: function (value) { this.settings.trackExceptions = value; },
developerMode: function(value) { this.settings.developerMode = value; }
};
// General function to register plugin handlers. Flushes buffers immediately upon registration according to the specified delay.
function register(handlerName, fn, options){
// Do not add a handler if developerMode is true
if (settings.developerMode) {
return;
}
api[handlerName] = updateHandlers(handlerName, fn, options);
var handlerSettings = settings[handlerName];
var handlerDelay = (handlerSettings) ? handlerSettings.bufferFlushDelay : null;
var delay = (handlerDelay !== null) ? handlerDelay : settings.bufferFlushDelay;
angular.forEach(cache[handlerName], function (args, index) {
onTimeout(function () { fn.apply(this, args); }, index * delay);
});
}
function capitalize(input) {
return input.replace(/^./, function (match) {
return match.toUpperCase();
});
}
//provide a method to inject services into handlers
var apiWithInjector = function(injector) {
return angular.extend(api, {
'$inject': injector.invoke
});
};
// Adds to the provider a 'register#{handlerName}' function that manages multiple plugins and buffer flushing.
function installHandlerRegisterFunction(handlerName){
var registerName = 'register'+capitalize(handlerName);
provider[registerName] = function(fn, options){
register(handlerName, fn, options);
};
api[handlerName] = updateHandlers(handlerName, bufferedHandler(handlerName));
}
function startRegistering(_provider, _knownHandlers, _installHandlerRegisterFunction) {
angular.forEach(_knownHandlers, _installHandlerRegisterFunction);
for (var key in _provider) {
vm[key] = _provider[key];
}
}
// Allow $angulartics to trigger the register to update opt in/out
var triggerRegister = function() {
startRegistering(provider, knownHandlers, installHandlerRegisterFunction);
};
// Initial register
startRegistering(provider, knownHandlers, installHandlerRegisterFunction);
}
function $analyticsRun($rootScope, $window, $analytics, $injector) {
function matchesExcludedRoute(url) {
for (var i = 0; i < $analytics.settings.pageTracking.excludedRoutes.length; i++) {
var excludedRoute = $analytics.settings.pageTracking.excludedRoutes[i];
if ((excludedRoute instanceof RegExp && excludedRoute.test(url)) || url.indexOf(excludedRoute) > -1) {
return true;
}
}
return false;
}
function arrayDifference(a1, a2) {
var result = [];
for (var i = 0; i < a1.length; i++) {
if (a2.indexOf(a1[i]) === -1) {
result.push(a1[i]);
}
}
return result;
}
function filterQueryString(url, keysMatchArr, thisType){
if (/\?/.test(url) && keysMatchArr.length > 0) {
var urlArr = url.split('?');
var urlBase = urlArr[0];
var pairs = urlArr[1].split('&');
var matchedPairs = [];
for (var i = 0; i < keysMatchArr.length; i++) {
var listedKey = keysMatchArr[i];
for (var j = 0; j < pairs.length; j++) {
if ((listedKey instanceof RegExp && listedKey.test(pairs[j])) || pairs[j].indexOf(listedKey) > -1) matchedPairs.push(pairs[j]);
}
}
var matchedPairsArr = (thisType == 'white' ? matchedPairs : arrayDifference(pairs,matchedPairs));
if(matchedPairsArr.length > 0){
return urlBase + '?' + matchedPairsArr.join('&');
}else{
return urlBase;
}
} else {
return url;
}
}
function whitelistQueryString(url){
return filterQueryString(url, $analytics.settings.pageTracking.queryKeysWhitelisted, 'white');
}
function blacklistQueryString(url){
return filterQueryString(url, $analytics.settings.pageTracking.queryKeysBlacklisted, 'black');
}
function filterUrlSegments(url){
var segmentFiltersArr = $analytics.settings.pageTracking.filterUrlSegments;
if (segmentFiltersArr.length > 0) {
var urlArr = url.split('?');
var urlBase = urlArr[0];
var segments = urlBase.split('/');
for (var i = 0; i < segmentFiltersArr.length; i++) {
var segmentFilter = segmentFiltersArr[i];
for (var j = 1; j < segments.length; j++) {
/* First segment will be host/protocol or base path. */
if ((segmentFilter instanceof RegExp && segmentFilter.test(segments[j])) || segments[j].indexOf(segmentFilter) > -1) {
segments[j] = 'FILTERED';
}
}
}
return segments.join('/');
} else {
return url;
}
}
function pageTrack(url, $location) {
if (!matchesExcludedRoute(url)) {
url = whitelistQueryString(url);
url = blacklistQueryString(url);
url = filterUrlSegments(url);
$analytics.pageTrack(url, $location);
}
}
var noRoutesOrStates;
var $route;
var route;
if ($analytics.settings.pageTracking.autoTrackFirstPage) {
/* Only track the 'first page' if there are no routes or states on the page */
noRoutesOrStates = true;
if ($injector.has('$route')) {
$route = $injector.get('$route');
if ($route) {
for (route in $route.routes) {
noRoutesOrStates = false;
break;
}
} else if ($route === null){
noRoutesOrStates = false;
}
} else if ($injector.has('$state')) {
var $state = $injector.get('$state');
if ($state.get().length > 1) noRoutesOrStates = false;
}
if (noRoutesOrStates) {
if ($analytics.settings.pageTracking.autoBasePath) {
$analytics.settings.pageTracking.basePath = $window.location.pathname;
}
$injector.invoke(['$location', function ($location) {
if ($analytics.settings.pageTracking.trackRelativePath) {
var url = $analytics.settings.pageTracking.basePath + $location.url();
pageTrack(url, $location);
} else {
pageTrack($location.absUrl(), $location);
}
}]);
}
}
if ($analytics.settings.pageTracking.autoTrackVirtualPages) {
if ($analytics.settings.pageTracking.autoBasePath) {
/* Add the full route to the base. */
$analytics.settings.pageTracking.basePath = $window.location.pathname + "#";
}
noRoutesOrStates = true;
if ($analytics.settings.pageTracking.trackRoutes) {
if ($injector.has('$route')) {
$route = $injector.get('$route');
if ($route) {
for (route in $route.routes) {
noRoutesOrStates = false;
break;
}
} else if ($route === null){
noRoutesOrStates = false;
}
$rootScope.$on('$routeChangeSuccess', function (event, current) {
if (current && (current.$$route||current).redirectTo) return;
$injector.invoke(['$location', function ($location) {
var url = $analytics.settings.pageTracking.basePath + $location.url();
pageTrack(url, $location);
}]);
});
}
}
if ($analytics.settings.pageTracking.trackStates) {
if ($injector.has('$state') && !$injector.has('$transitions')) {
noRoutesOrStates = false;
$rootScope.$on('$stateChangeSuccess', function (event, current) {
$injector.invoke(['$location', function ($location) {
var url = $analytics.settings.pageTracking.basePath + $location.url();
pageTrack(url, $location);
}]);
});
}
if ($injector.has('$state') && $injector.has('$transitions')) {
noRoutesOrStates = false;
$injector.invoke(['$transitions', function($transitions) {
$transitions.onSuccess({}, function($transition$) {
var transitionOptions = $transition$.options();
// only track for transitions that would have triggered $stateChangeSuccess
if (transitionOptions.notify) {
$injector.invoke(['$location', function ($location) {
var url = $analytics.settings.pageTracking.basePath + $location.url();
pageTrack(url, $location);
}]);
}
});
}]);
}
}
if (noRoutesOrStates) {
$rootScope.$on('$locationChangeSuccess', function (event, current) {
if (current && (current.$$route || current).redirectTo) return;
$injector.invoke(['$location', function ($location) {
if ($analytics.settings.pageTracking.trackRelativePath) {
var url = $analytics.settings.pageTracking.basePath + $location.url();
pageTrack(url, $location);
} else {
pageTrack($location.absUrl(), $location);
}
}]);
});
}
}
if ($analytics.settings.developerMode) {
angular.forEach($analytics, function(attr, name) {
if (typeof attr === 'function') {
$analytics[name] = function(){};
}
});
}
}
function analyticsOn($analytics) {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
var eventType = $attrs.analyticsOn || 'click';
var trackingData = {};
angular.forEach($attrs.$attr, function(attr, name) {
if (isProperty(name)) {
trackingData[propertyName(name)] = $attrs[name];
$attrs.$observe(name, function(value){
trackingData[propertyName(name)] = value;
});
}
});
angular.element($element[0]).on(eventType, function ($event) {
var eventName = $attrs.analyticsEvent || inferEventName($element[0]);
trackingData.eventType = $event.type;
if($attrs.analyticsIf){
if(! $scope.$eval($attrs.analyticsIf)){
return; // Cancel this event if we don't pass the analytics-if condition
}
}
// Allow components to pass through an expression that gets merged on to the event properties
// eg. analytics-properites='myComponentScope.someConfigExpression.$analyticsProperties'
if($attrs.analyticsProperties){
angular.extend(trackingData, $scope.$eval($attrs.analyticsProperties));
}
$analytics.eventTrack(eventName, trackingData);
});
}
};
}
function exceptionTrack($provide) {
$provide.decorator('$exceptionHandler', ['$delegate', '$injector', function ($delegate, $injector) {
return function (error, cause) {
var result = $delegate(error, cause);
var $analytics = $injector.get('$analytics');
if ($analytics.settings.trackExceptions) {
$analytics.exceptionTrack(error, cause);
}
return result;
};
}]);
}
function isCommand(element) {
return ['a:','button:','button:button','button:submit','input:button','input:submit'].indexOf(
element.tagName.toLowerCase()+':'+(element.type||'')) >= 0;
}
function inferEventType(element) {
if (isCommand(element)) return 'click';
return 'click';
}
function inferEventName(element) {
if (isCommand(element)) return element.innerText || element.value;
return element.id || element.name || element.tagName;
}
function isProperty(name) {
return name.substr(0, 9) === 'analytics' && ['On', 'Event', 'If', 'Properties', 'EventType'].indexOf(name.substr(9)) === -1;
}
function propertyName(name) {
var s = name.slice(9); // slice off the 'analytics' prefix
if (typeof s !== 'undefined' && s!==null && s.length > 0) {
return s.substring(0, 1).toLowerCase() + s.substring(1);
}
else {
return s;
}
}
})(angular);
|
const createBuffer = Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow
? Buffer.from
: val => new Buffer(val)
;
function calCrc(buf, previous) {
let TABLE = [
0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40,
0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40,
0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641,
0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240,
0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41,
0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41,
0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640,
0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240,
0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41,
0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41,
0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640,
0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241,
0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40,
0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40,
0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641,
0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040
];
if (typeof(Int32Array) !== 'undefined') TABLE = new Int32Array(TABLE);
if (!Buffer.isBuffer(buf)) buf = createBuffer(buf);
let crc = typeof(previous) !== 'undefined' ? ~~previous : 0xffff;
for (let index = 0; index < buf.length; index++) {
const byte = buf[index];
crc = ((TABLE[(crc ^ byte) & 0xff] ^ (crc >> 8)) & 0xffff);
}
let swapped = ((crc << 8) & 0xff00) | ((crc >> 8) & 0x00ff);
return swapped;
}
function checkCrc(buf, check) {
return calCrc(buf) == check;
}
exports.createBuffer = createBuffer;
exports.calCrc = calCrc;
exports.checkCrc = calCrc; |
import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.scss';
import Header from '../Header';
import Feedback from '../Feedback';
import Footer from '../Footer';
class App extends Component {
static propTypes = {
context: PropTypes.shape({
insertCss: PropTypes.func,
onSetTitle: PropTypes.func,
onSetMeta: PropTypes.func,
onPageNotFound: PropTypes.func,
}),
children: PropTypes.element.isRequired,
error: PropTypes.object,
};
static childContextTypes = {
insertCss: PropTypes.func.isRequired,
onSetTitle: PropTypes.func.isRequired,
onSetMeta: PropTypes.func.isRequired,
onPageNotFound: PropTypes.func.isRequired,
};
getChildContext() {
const context = this.props.context;
return {
insertCss: context.insertCss || emptyFunction,
onSetTitle: context.onSetTitle || emptyFunction,
onSetMeta: context.onSetMeta || emptyFunction,
onPageNotFound: context.onPageNotFound || emptyFunction,
};
}
componentWillMount() {
this.removeCss = this.props.context.insertCss(s);
}
componentWillUnmount() {
this.removeCss();
}
render() {
return !this.props.error ? (
<div>
<Header />
{this.props.children}
<Feedback />
<Footer />
</div>
) : this.props.children;
}
}
export default App;
|
import Dispatcher from './src/Dispatcher';
import DisposableStack from './src/DisposableStack';
import PureView from './src/PureView';
import Store from './src/Store';
import View from './src/View';
export default {
Dispatcher,
DisposableStack,
PureView,
Store,
View
};
|
(function(handler) {
var $doc = handler(document);
var eventMap = {};
var eventList = ['swip', 'swipeup', 'swipedown', 'swipeleft', 'swiperight', 'drag', 'dragstart', 'dragend', 'tab', 'doubletab', 'hold', 'rotate'];
handler.each(eventList, function(eventName) {
eventMap[eventName] = handler.event(eventName);
});
var startX = 0, startY = 0;
$doc.on('touchstart', function(event) {
var touches = event.originalEvent.touches;
startX = touches[0].pageX;
startY = touches[0].pageY;
});
var stop = false;
$doc.on('touchmove', function(event) {
if (stop) return true;
var touches = event.originalEvent.touches;
var deltaX = touches[0].pageX - startX;
var deltaY = touches[0].pageY - startY;
if (deltaX > 50 && Math.abs(deltaY) < deltaX) {
stop = true;
event.originalEvent.target.dispatchEvent(eventMap['swiperight']);
}
if (deltaX < -50 && Math.abs(deltaY) < Math.abs(deltaX)) {
stop = true;
event.originalEvent.target.dispatchEvent(eventMap['swipeleft']);
}
if (deltaY > 50 && Math.abs(deltaX) < deltaY) {
stop = true;
event.originalEvent.target.dispatchEvent(eventMap['swipedown']);
}
if (deltaY < -50 && Math.abs(deltaX) < Math.abs(deltaY)) {
stop = true;
event.originalEvent.target.dispatchEvent(eventMap['swipeup']);
}
});
$doc.on('touchend', function(event) {
stop = false;
});
})(J);
|
'use strict';
angular.module('myApp.view1', ['ngRoute','nvd3ChartDirectives'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/homeAutomation', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ["$scope","$http","temperatureService",function($scope, $http, temperatureService) {
function initialize(){
$scope.currentTemperature = 0;
$scope.previousTemperature = 0;
$scope.tempChangeAreaChartData = [
{
"key": "Change in Temperature",
"values": [ [ 0 , 16],[8, 16], [9.6, 16], [11.2, 16], [12.8, 16], [14.4, 16], [16, 16]]
}
];
}
initialize();
$scope.xAxisTickFormat = function(){
return function(d){
return d;
}
};
$scope.yAxisTickFormat = function(){
return function(d){
return d;
}
};
$scope.toolTipContentFunction = function(){
return function(key, x, y, e, graph) {
return 'Super New Tooltip' +
'<h1>' + key + '</h1>' +
'<p>' + y + ' at ' + x + '</p>'
}
};
function rotate( array , times ){
array = array.slice();
while( times-- ){
var temp = array.shift();
array.push( temp )
}
return array;
}
// when submitting the add form, send the text to the node API
$scope.changeTemperature = function(changedTemperatureValue) {
if($scope.dataOnOff===true){
$scope.previousTemperature = angular.copy($scope.currentTemperature);
$scope.currentTemperature = changedTemperatureValue;
//Due to lack of time I am just rotating the list of values in $scope.tempChangeAreaChartData variable to represent temperature change.
var tempArray = rotate($scope.tempChangeAreaChartData[0].values, 1);
$scope.tempChangeAreaChartData = [];
$scope.tempChangeAreaChartData.push({
"key": "Change in Temperature",
"values":tempArray
});
//Fetch object that contains the json response for temperature change.
temperatureService.fetchTemperature().then(function(response){
console.log(response, "The response object with all the temperature change information returned by node");
});
//Set new temperature value.
temperatureService.setTemperature({}).then(function(data){
console.log(data, " Changed temperature posted successfully ")
});
}
};
}]); |
/* ========================================================================
* OctoberCMS: front-end JavaScript extras
* http://octobercms.com
* ========================================================================
* Copyright 2016 Alexey Bobkov, Samuel Georges
* ======================================================================== */
+function ($) { "use strict";
if ($.oc === undefined)
$.oc = {}
// @todo Provide an interface for configuration
// - Custom loader CSS class
// - Custom stripe loader color
// - Flash message interval
var LOADER_CLASS = 'oc-loading';
// FLASH HANDLING
// ============================
$(document).on('ajaxSetup', '[data-request][data-request-flash]', function(event, context) {
context.options.handleErrorMessage = function(message) {
$.oc.flashMsg({ text: message, class: 'error' })
}
context.options.handleFlashMessage = function(message, type) {
$.oc.flashMsg({ text: message, class: type })
}
})
// FORM VALIDATION
// ============================
$(document).on('ajaxValidation', '[data-request][data-request-validate]', function(event, context, errorMsg, fields) {
var $this = $(this).closest('form'),
$container = $('[data-validate-error]', $this),
messages = [],
$field
$.each(fields, function(fieldName, fieldMessages) {
$field = $('[data-validate-for="'+fieldName+'"]', $this)
messages = $.merge(messages, fieldMessages)
if (!!$field.length) {
if (!$field.text().length || $field.data('emptyMode') == true) {
$field
.data('emptyMode', true)
.text(fieldMessages.join(', '))
}
$field.addClass('visible')
}
})
if (!!$container.length) {
$container = $('[data-validate-error]')
}
if (!!$container.length) {
var $oldMessages = $('[data-message]', $container)
$container.addClass('visible')
if (!!$oldMessages.length) {
var $clone = $oldMessages.first()
$.each(messages, function(key, message) {
$clone.clone().text(message).insertAfter($clone)
})
$oldMessages.remove()
}
else {
$container.text(errorMsg)
}
}
$this.one('ajaxError', function(event){
event.preventDefault()
})
})
$(document).on('ajaxPromise', '[data-request][data-request-validate]', function() {
var $this = $(this).closest('form')
$('[data-validate-for]', $this).removeClass('visible')
$('[data-validate-error]', $this).removeClass('visible')
})
// LOADING BUTTONS
// ============================
$(document)
.on('ajaxPromise', '[data-request]', function() {
var $target = $(this)
if ($target.data('attach-loading') !== undefined) {
$target
.addClass(LOADER_CLASS)
.prop('disabled', true)
}
if ($target.is('form')) {
$('[data-attach-loading]', $target)
.addClass(LOADER_CLASS)
.prop('disabled', true)
}
})
.on('ajaxFail ajaxDone', '[data-request]', function() {
var $target = $(this)
if ($target.data('attach-loading') !== undefined) {
$target
.removeClass(LOADER_CLASS)
.prop('disabled', false)
}
if ($target.is('form')) {
$('[data-attach-loading]', $target)
.removeClass(LOADER_CLASS)
.prop('disabled', false)
}
})
// STRIPE LOAD INDICATOR
// ============================
var StripeLoadIndicator = function() {
var self = this
this.counter = 0
this.indicator = $('<div/>').addClass('stripe-loading-indicator loaded')
.append($('<div />').addClass('stripe'))
.append($('<div />').addClass('stripe-loaded'))
this.stripe = this.indicator.find('.stripe')
$(document).ready(function() {
$(document.body).append(self.indicator)
})
}
StripeLoadIndicator.prototype.show = function() {
this.counter++
// Restart the animation
this.stripe.after(this.stripe = this.stripe.clone()).remove()
if (this.counter > 1) {
return
}
this.indicator.removeClass('loaded')
$(document.body).addClass('oc-loading')
}
StripeLoadIndicator.prototype.hide = function(force) {
this.counter--
if (force !== undefined && force) {
this.counter = 0
}
if (this.counter <= 0) {
this.indicator.addClass('loaded')
$(document.body).removeClass('oc-loading')
}
}
$.oc.stripeLoadIndicator = new StripeLoadIndicator()
// STRIPE LOAD INDICATOR DATA-API
// ============================
$(document)
.on('ajaxPromise', '[data-request]', function(event) {
// Prevent this event from bubbling up to a non-related data-request
// element, for example a <form> tag wrapping a <button> tag
event.stopPropagation()
$.oc.stripeLoadIndicator.show()
// This code will cover instances where the element has been removed
// from the DOM, making the resolution event below an orphan.
var $el = $(this)
$(window).one('ajaxUpdateComplete', function() {
if ($el.closest('html').length === 0)
$.oc.stripeLoadIndicator.hide()
})
})
.on('ajaxFail ajaxDone', '[data-request]', function(event) {
event.stopPropagation()
$.oc.stripeLoadIndicator.hide()
})
// FLASH MESSAGE
// ============================
var FlashMessage = function (options, el) {
var
options = $.extend({}, FlashMessage.DEFAULTS, options),
$element = $(el)
$('body > p.flash-message').remove()
if ($element.length == 0) {
$element = $('<p />').addClass(options.class).html(options.text)
}
$element
.addClass('flash-message fade')
.attr('data-control', null)
.on('click', 'button', remove)
.on('click', remove)
.append('<button type="button" class="close" aria-hidden="true">×</button>')
$(document.body).append($element)
setTimeout(function() {
$element.addClass('in')
}, 100)
var timer = window.setTimeout(remove, options.interval * 1000)
function removeElement() {
$element.remove()
}
function remove() {
window.clearInterval(timer)
$element.removeClass('in')
$.support.transition && $element.hasClass('fade')
? $element
.one($.support.transition.end, removeElement)
.emulateTransitionEnd(500)
: removeElement()
}
}
FlashMessage.DEFAULTS = {
class: 'success',
text: 'Default text',
interval: 5
}
if ($.oc === undefined)
$.oc = {}
$.oc.flashMsg = FlashMessage
// FLASH MESSAGE DATA-API
// ===============
$(document).render(function(){
$('[data-control=flash-message]').each(function(){
$.oc.flashMsg($(this).data(), this)
})
})
}(window.jQuery);
|
// dropdown-menu.js
$(function() {
$('.navbar__dropdown .navbar__dropdown--wrapper ul').hide();
$('.navbar__dropdown .navbar__dropdown--wrapper').click(function(e) {
$('.navbar__dropdown .navbar__dropdown--wrapper ul').slideToggle(200);
$('.navbar__dropdown--menu').toggleClass('active');
e.stopPropagation();
});
$(document).click(function() {
if ($('.navbar__dropdown .navbar__dropdown--wrapper ul').is(':visible')) {
$('.navbar__dropdown .navbar__dropdown--wrapper ul', this).slideUp();
$('.navbar__dropdown--menu').removeClass('active');
}
});
});
|
(function(angular) {
var app = angular.module('SuperCoolApp');
app.factory('FeatureService', [FeatureController, function(FeatureController){
}]);
})(window.angular); |
var Promise = require("nodegit-promise");
var NodeGit = require("../");
var Blob = NodeGit.Blob;
var Checkout = NodeGit.Checkout;
var Commit = NodeGit.Commit;
var normalizeOptions = NodeGit.Utils.normalizeOptions;
var Reference = NodeGit.Reference;
var Remote = NodeGit.Remote;
var Repository = NodeGit.Repository;
var Revwalk = NodeGit.Revwalk;
var Status = NodeGit.Status;
var StatusFile = NodeGit.StatusFile;
var StatusList = NodeGit.StatusList;
var Tag = NodeGit.Tag;
var Tree = NodeGit.Tree;
var TreeBuilder = NodeGit.Treebuilder;
Object.defineProperty(Repository.prototype, "openIndex", {
enumerable: false,
value: Repository.prototype.index
});
/**
* Creates a branch with the passed in name pointing to the commit
*
* @async
* @param {String} name Branch name, e.g. "master"
* @param {Commit|String|Oid} commit The commit the branch will point to
* @param {bool} force Overwrite branch if it exists
* @param {Signature} signature Identity to use to populate reflog
* @param {String} logMessage One line message to be appended to the reflog
* @return {Ref}
*/
Repository.prototype.createBranch =
function(name, commit, force, signature, logMessage) {
var repo = this;
if (commit instanceof Commit) {
return NodeGit.Branch.create(
repo,
name,
commit,
force ? 1 : 0,
signature,
logMessage);
}
else {
return repo.getCommit(commit).then(function(commit) {
return NodeGit.Branch.create(
repo,
name,
commit,
force ? 1 : 0,
signature,
logMessage);
});
}
};
/**
* Look up a refs's commit.
*
* @async
* @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
* or Branch Ref
* @return {Commit}
*/
Repository.prototype.getReferenceCommit = function(name, callback) {
var repository = this;
return this.getReference(name).then(function(reference) {
return repository.getCommit(reference.target()).then(function(commit) {
if (typeof callback === "function") {
callback(null, commit);
}
return commit;
});
}, callback);
};
/**
* Look up a branch. Alias for `getReference`
*
* @async
* @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
* or Branch Ref
* @return {Ref}
*/
Repository.prototype.getBranch = function(name, callback) {
return this.getReference(name, callback);
};
/**
* Look up a branch's most recent commit. Alias to `getReferenceCommit`
*
* @async
* @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
* or Branch Ref
* @return {Commit}
*/
Repository.prototype.getBranchCommit = function(name, callback) {
return this.getReferenceCommit(name, callback);
};
/**
* Gets the branch that HEAD currently points to
* Is an alias to head()
* @async
* @return {Reference}
*/
Repository.prototype.getCurrentBranch = function() {
return this.head();
};
/**
* Lookup the reference with the given name.
*
* @async
* @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
* or Branch Ref
* @return {Reference}
*/
Repository.prototype.getReference = function(name, callback) {
var repository = this;
return Reference.dwim(this, name).then(function(reference) {
if (reference.isSymbolic()) {
return reference.resolve().then(function(reference) {
reference.repo = repository;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
}, callback);
} else {
reference.repo = repository;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
}
}, callback);
};
Repository.getReferences = function(repo, type, refNamesOnly, callback) {
return Reference.list(repo).then(function(refList) {
var refFilterPromises = [];
var filteredRefs = [];
refList.forEach(function(refName) {
refFilterPromises.push(Reference.lookup(repo, refName)
.then(function(ref) {
if (type == Reference.TYPE.ALL || ref.type() == type) {
if (refNamesOnly) {
filteredRefs.push(refName);
return;
}
if (ref.isSymbolic()) {
return ref.resolve().then(function(resolvedRef) {
resolvedRef.repo = repo;
filteredRefs.push(resolvedRef);
});
}
else {
filteredRefs.push(ref);
}
}
})
);
});
return Promise.all(refFilterPromises).then(function() {
if (typeof callback === "function") {
callback(null, filteredRefs);
}
return filteredRefs;
}, callback);
});
};
/**
* Lookup references for a repository.
*
* @async
* @param {Reference.TYPE} type Type of reference to look up
* @return {Array<Reference>}
*/
Repository.prototype.getReferences = function(type, callback) {
return Repository.getReferences(this, type, false, callback);
};
/**
* Lookup reference names for a repository.
*
* @async
* @param {Reference.TYPE} type Type of reference to look up
* @return {Array<String>}
*/
Repository.prototype.getReferenceNames = function(type, callback) {
return Repository.getReferences(this, type, true, callback);
};
/**
* Retrieve the commit identified by oid.
*
* @async
* @param {String|Oid} String sha or Oid
* @return {Commit}
*/
Repository.prototype.getCommit = function(oid, callback) {
var repository = this;
return Commit.lookup(repository, oid).then(function(commit) {
commit.repo = repository;
if (typeof callback === "function") {
callback(null, commit);
}
return commit;
}, callback);
};
/**
* Retrieve the blob represented by the oid.
*
* @async
* @param {String|Oid} String sha or Oid
* @return {Blob}
*/
Repository.prototype.getBlob = function(oid, callback) {
var repository = this;
return Blob.lookup(repository, oid).then(function(blob) {
blob.repo = repository;
if (typeof callback === "function") {
callback(null, blob);
}
return blob;
}, callback);
};
/**
* Retrieve the tree represented by the oid.
*
* @async
* @param {String|Oid} String sha or Oid
* @return {Tree}
*/
Repository.prototype.getTree = function(oid, callback) {
var repository = this;
return Tree.lookup(repository, oid).then(function(tree) {
tree.repo = repository;
if (typeof callback === "function") {
callback(null, tree);
}
return tree;
}, callback);
};
/**
* Creates a new annotated tag
*
* @async
* @param {String|Oid} String sha or Oid
* @param {String} name the name of the tag
* @param {String} message the description that will be attached to the
* annotated tag
* @return {Tag}
*/
Repository.prototype.createTag = function(oid, name, message, callback) {
var repository = this;
var signature = repository.defaultSignature();
return Commit.lookup(repository, oid)
.then(function(commit) {
// Final argument is `force` which overwrites any previous tag
return Tag.create(repository, name, commit, signature, message, 0);
})
.then(function(tagOid) {
return repository.getTag(tagOid, callback);
});
};
/**
* Creates a new lightweight tag
*
* @async
* @param {String|Oid} String sha or Oid
* @param {String} name the name of the tag
* @return {Reference}
*/
Repository.prototype.createLightweightTag = function(oid, name, callback) {
var repository = this;
return Commit.lookup(repository, oid)
.then(function(commit) {
// Final argument is `force` which overwrites any previous tag
return Tag.createLightweight(repository, name, commit, 0);
})
.then(function() {
return Reference.lookup(repository, "refs/tags/" + name);
});
};
/**
* Retrieve the tag represented by the oid.
*
* @async
* @param {String|Oid} String sha or Oid
* @return {Tag}
*/
Repository.prototype.getTag = function(oid, callback) {
var repository = this;
return Tag.lookup(repository, oid).then(function(reference) {
reference.repo = repository;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
}, callback);
};
/**
* Retrieve the tag represented by the tag name.
*
* @async
* @param {String} Short or full tag name
* @return {Tag}
*/
Repository.prototype.getTagByName = function(name, callback) {
var repo = this;
name = ~name.indexOf("refs/tags/") ? name : "refs/tags/" + name;
return Reference.nameToId(repo, name).then(function(oid) {
return Tag.lookup(repo, oid).then(function(reference) {
reference.repo = repo;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
});
}, callback);
};
/**
* Deletes a tag from a repository by the tag name.
*
* @async
* @param {String} Short or full tag name
*/
Repository.prototype.deleteTagByName = function(name) {
var repository = this;
name = ~name.indexOf("refs/tags/") ? name.substr(10) : name;
return Tag.delete(repository, name);
};
/**
* Instantiate a new revision walker for browsing the Repository"s history.
* See also `Commit.prototype.history()`
*
* @param {String|Oid} String sha or Oid
* @return {RevWalk}
*/
Repository.prototype.createRevWalk = function() {
var revWalk = Revwalk.create(this);
revWalk.repo = this;
return revWalk;
};
/**
* Retrieve the master branch commit.
*
* @async
* @return {Commit}
*/
Repository.prototype.getMasterCommit = function(callback) {
return this.getBranchCommit("master", callback);
};
/**
* Retrieve the commit that HEAD is currently pointing to
*
* @async
* @return {Commit}
*/
Repository.prototype.getHeadCommit = function(callback) {
var repo = this;
return Reference.nameToId(repo, "HEAD").then(function(head) {
return repo.getCommit(head, callback);
});
};
/**
* Create a commit
*
* @async
* @param {String} updateRef
* @param {Signature} author
* @param {Signature} committer
* @param {String} message
* @param {Tree|Oid|String} Tree
* @param {Array} parents
* @return {Oid} The oid of the commit
*/
Repository.prototype.createCommit = function(
updateRef, author, committer, message, tree, parents, callback) {
var repo = this;
var promises = [];
parents = parents || [];
promises.push(repo.getTree(tree));
parents.forEach(function(parent) {
promises.push(repo.getCommit(parent));
});
return Promise.all(promises).then(function(results) {
tree = results[0];
// Get the normalized values for our input into the function
var parentsLength = parents.length;
parents = [];
for (var i = 0; i < parentsLength; i++) {
parents.push(results[i + 1]);
}
return Commit.create(
repo,
updateRef,
author,
committer,
null /* use default message encoding */,
message,
tree,
parents.length,
parents
);
}).then(function(commit) {
if (typeof callback === "function") {
callback(null, commit);
}
return commit;
}, callback);
};
/**
* Creates a new commit on HEAD from the list of passed in files
* @async
* @param {Array} filesToAdd
* @param {Signature} author
* @param {Signature} committer
* @param {String} message
* @return {Oid} The oid of the new commit
*/
Repository.prototype.createCommitOnHead = function(
filesToAdd,
author,
committer,
message,
callback){
var repo = this;
var index;
return repo.openIndex().then(function(index_) {
index = index_;
index.read(1);
return index.addAll();
})
.then(function() {
index.write();
return index.writeTree();
}).then(function(treeOid) {
return repo.getHeadCommit().then(function(parent) {
return repo.createCommit(
"HEAD",
author,
committer,
message,
treeOid,
[parent],
callback);
});
}, callback);
};
/**
* Create a blob from a buffer
*
* @param {Buffer} buffer
* @return {Blob}
*/
Repository.prototype.createBlobFromBuffer = function(buffer, callback) {
return Blob.createFromBuffer(this, buffer, buffer.length, callback);
};
/**
* Create a new tree builder.
*
* @param {Tree} tree
*/
Repository.prototype.treeBuilder = function() {
var builder = TreeBuilder.create(null);
builder.root = builder;
builder.repo = this;
return builder;
};
/**
* Gets the default signature for the default user and now timestamp
* @return {Signature}
*/
Repository.prototype.defaultSignature = function() {
var result = NodeGit.Signature.default(this);
if (!result.name()) {
result = NodeGit.Signature.now("unknown", "unknown@unknown.com");
}
return result;
};
/**
* Lists out the remotes in the given repository.
*
* @param {Function} Optional callback
* @return {Object} Promise object.
*/
Repository.prototype.getRemotes = function(callback) {
return Remote.list(this).then(function(remotes) {
if (typeof callback === "function") {
callback(null, remotes);
}
return remotes;
}, callback);
};
/**
* Gets a remote from the repo
*
* @param {String|Remote} remote
* @param {Function} callback
* @return {Remote} The remote object
*/
Repository.prototype.getRemote = function(remote, callback) {
if (remote instanceof NodeGit.Remote) {
return Promise.resolve(remote).then(function(remoteObj) {
if (typeof callback === "function") {
callback(null, remoteObj);
}
return remoteObj;
}, callback);
}
return NodeGit.Remote.lookup(this, remote).then(function(remoteObj) {
if (typeof callback === "function") {
callback(null, remoteObj);
}
return remoteObj;
}, callback);
};
/**
* Fetches from a remote
*
* @param {String|Remote} remote
* @param {Object|RemoteCallback} remoteCallbacks Any custom callbacks needed
* @param {Bool} pruneAfter will perform a prune after the fetch if true
*/
Repository.prototype.fetch = function(
remote,
remoteCallbacks,
pruneAfter,
callback)
{
var repo = this;
return repo.getRemote(remote).then(function(remote) {
remote.setCallbacks(remoteCallbacks);
return remote.fetch(null, repo.defaultSignature(), "Fetch from " + remote)
.then(function() {
if (pruneAfter) {
remote.prune();
}
})
.then(function() {
return remote.disconnect();
}).then(function() {
if (typeof callback === "function") {
callback();
}
});
}, callback);
};
/**
* Fetches from all remotes
* @param {Object|RemoteCallback} remoteCallbacks Any custom callbacks needed
* @param {Bool} pruneAfter will perform a prune after the fetch if true
*/
Repository.prototype.fetchAll = function(
remoteCallbacks,
pruneAfter,
callback)
{
var repo = this;
return repo.getRemotes().then(function(remotes) {
var fetchPromises = [];
remotes.forEach(function(remote) {
fetchPromises.push(
repo.fetch(remote, remoteCallbacks, pruneAfter, callback));
});
return Promise.all(fetchPromises);
}, callback);
};
/**
* Merge a branch onto another branch
*
* @param {String|Ref} to
* @param {String|Ref} from
* @return {Oid|Index} A commit id for a succesful merge or an index for a
* merge with conflicts
*/
Repository.prototype.mergeBranches = function(to, from, signature) {
var repo = this;
var fromBranch;
var toBranch;
signature = signature || repo.defaultSignature();
return Promise.all([
repo.getBranch(to),
repo.getBranch(from)
]).then(function(objects) {
toBranch = objects[0];
fromBranch = objects[1];
return Promise.all([
repo.getBranchCommit(toBranch),
repo.getBranchCommit(fromBranch)
]);
})
.then(function(branchCommits) {
var toCommitOid = branchCommits[0].toString();
var fromCommitOid = branchCommits[1].toString();
return NodeGit.Merge.base(repo, toCommitOid, fromCommitOid)
.then(function(baseCommit) {
if (baseCommit.toString() == fromCommitOid) {
// The commit we're merging to is already in our history.
// nothing to do so just return the commit the branch is on
return toCommitOid;
}
else if (baseCommit.toString() == toCommitOid) {
// fast forward
var message =
"Fast forward branch " +
toBranch.shorthand() +
" to branch " +
fromBranch.shorthand();
return branchCommits[1].getTree()
.then(function(tree) {
if (toBranch.isHead()) {
// Checkout the tree if we're on the branch
var opts = {
checkoutStrategy: NodeGit.Checkout.STRATEGY.SAFE_CREATE
};
return NodeGit.Checkout.tree(repo, tree, opts);
}
})
.then(function() {
return toBranch.setTarget(
fromCommitOid,
signature,
message)
.then(function() {
return fromCommitOid;
});
});
}
else {
// We have to merge. Lets do it!
return NodeGit.Merge.commits(repo, toCommitOid, fromCommitOid)
.then(function(index) {
// if we have conflicts then throw the index
if (index.hasConflicts()) {
throw index;
}
// No conflicts so just go ahead with the merge
index.write();
return index.writeTreeTo(repo);
}).then(function(oid) {
var message =
"Merged " +
fromBranch.shorthand() +
" into " +
toBranch.shorthand();
return repo.createCommit(
toBranch.name(),
signature,
signature,
message,
oid,
[toCommitOid, fromCommitOid]);
});
}
});
});
};
// Override Repository.initExt to normalize initoptions
var initExt = Repository.initExt;
Repository.initExt = function(repo_path, opts) {
opts = normalizeOptions(opts, NodeGit.RepositoryInitOptions);
return initExt(repo_path, opts);
};
/**
* Get the status of a repo to it's working directory
*
* @param {obj} opts
* @return {Array<StatusFile>}
*/
Repository.prototype.getStatus = function(opts) {
var statuses = [];
var statusCallback = function(path, status) {
statuses.push(new StatusFile({path: path, status: status}));
};
if (!opts) {
opts = {
flags: Status.OPT.INCLUDE_UNTRACKED |
Status.OPT.RECURSE_UNTRACKED_DIRS
};
}
return Status.foreachExt(this, opts, statusCallback).then(function() {
return statuses;
});
};
/**
* Get extended statuses of a repo to it's working directory. Status entries
* have `status`, `headToIndex` delta, and `indexToWorkdir` deltas
*
* @param {obj} opts
* @return {Array<StatusEntry>}
*/
Repository.prototype.getStatusExt = function(opts) {
var statuses = [];
if (!opts) {
opts = {
flags: Status.OPT.INCLUDE_UNTRACKED |
Status.OPT.RECURSE_UNTRACKED_DIRS |
Status.OPT.RENAMES_INDEX_TO_WORKDIR |
Status.OPT.RENAMES_HEAD_TO_INDEX |
Status.OPT.RENAMES_FROM_REWRITES
};
}
var list = StatusList.create(this, opts);
for (var i = 0; i < list.entrycount(); i++) {
var entry = Status.byIndex(list, i);
statuses.push(new StatusFile({entry: entry}));
}
return statuses;
};
/**
* This will set the HEAD to point to the local branch and then attempt
* to update the index and working tree to match the content of the
* latest commit on that branch
* @param {String|Reference} branch the branch to checkout
* @param {Object|CheckoutOptions} opts the options to use for the checkout
*/
Repository.prototype.checkoutBranch = function(branch, opts) {
var repo = this;
var reference;
opts = opts || {};
opts.checkoutStrategy = opts.checkoutStrategy ||
Checkout.STRATEGY.SAFE_CREATE;
return repo.getReference(branch)
.then(function(ref) {
if (!ref.isBranch()) {
return false;
}
reference = ref;
return repo.getBranchCommit(ref.name());
})
.then(function(commit) {
return commit.getTree();
})
.then(function(tree) {
return Checkout.tree(repo, tree, opts);
})
.then(function() {
var name = reference.name();
return repo.setHead(name,
repo.defaultSignature(),
"Switch HEAD to " + name);
});
};
var fetchheadForeach = Repository.prototype.fetchheadForeach;
/**
* @async
* @param {FetchheadForeachCb} callback The callback function to be called on
* each entry
*/
Repository.prototype.fetchheadForeach = function(callback) {
return fetchheadForeach.call(this, callback, null);
};
module.exports = Repository;
|
var mopidy = require('./mopidy');
var _ = require('underscore');
var when = require('when');
var LibraryProvider = function () {
this.getArtists = function() {
return mopidy.library.search(null).then(function(results) {
var artists = {};
_.each(results, function(result) {
_.each(result.albums || result.tracks || [], function(item) {
if (item.hasOwnProperty("artists") && item.artists instanceof Array && item.artists.length) {
if (!item.artists[0].name) {
// TODO: Support 'Unknown artist'
// console.warn("Empty artist!");
// console.log(item);
} else {
var artistKey = item.artists[0].name.trim().toLowerCase();
if (artists.hasOwnProperty(artistKey) && artists[artistKey].indexOf(item.artists[0].name) === -1) {
artists[artistKey].push(item.artists[0].name);
} else if (!artists.hasOwnProperty(artistKey)) {
artists[artistKey] = [item.artists[0].name];
}
}
} else {
console.warn("No artist key for item!");
console.log(item);
}
});
});
var res = [];
_.each(Object.keys(artists), function(artistKey) {
res.push(artists[artistKey][0]);
});
return _.sortBy(res, function(name) {
return name;
});
});
};
this.getAlbums = function(filter) {
return mopidy.library.search(filter).then(function(results) {
//var albums = [];
var albumKeys = [];
var albums = [];
_.each(results, function(result) {
_.each(result.albums || result.tracks || [], function(item) {
var artistName = "";
if (filter && filter.artist) {
artistName = filter.artist;
if (item.artists && item.artists instanceof Array && item.artists.length) {
var match = false;
_.each(item.artists, function(artist) {
match = match || artist.name && artist.name.trim().toLowerCase() === filter.artist.trim().toLowerCase();
});
if (!match) {
return;
}
}
}
var albumName = "";
if (item.__model__ === "Track") {
albumName = item.album && item.album.name.trim() && item.album.name || "Unknown album";
} else {
albumName = item.name.trim() && item.name || "Unknown album";
}
if (!artistName) {
if (item.hasOwnProperty("artists") && item.artists instanceof Array && item.artists.length) {
artistName = item.artists[0] && item.artists[0].name.trim() && item.artists[0].name || "Unknown artist";
} else {
artistName = "Unknown artist";
}
}
var albumKey = albumName.trim().toLowerCase() + artistName.trim().toLowerCase();
if (albumKeys.indexOf(albumKey) === -1) {
albumKeys.push(albumKey);
albums.push({
artist: artistName,
album: albumName
});
}
});
});
return _.sortBy(albums, function(albumTuple) {
return albumTuple.album;
});
});
};
this.getTracks = function(filter) {
// TODO support 'Unknown artist' & 'Unknown album'
// Might need backend adaptations though
//
return mopidy.library.search(filter).then(function(results) {
var tracks = [];
var uris = {};
_.each(results, function(result) {
if (result.hasOwnProperty("tracks")) {
_.each(result.tracks, function(item) {
if (filter && filter.artist) {
if (item.artists && item.artists instanceof Array && item.artists.length) {
var match = false;
_.each(item.artists, function(artist) {
match = match || artist.name && artist.name.trim().toLowerCase() === filter.artist.trim().toLowerCase();
});
if (!match) {
return;
}
}
}
if (filter && filter.album) {
if (item.album && !item.album.name.trim().toLowerCase() === filter.album.trim().toLowerCase()) {
return;
}
}
tracks.push(item.name);
if (!uris.hasOwnProperty(item.name)) {
uris[item.name] = [];
}
uris[item.name].push(item.uri);
});
}
});
return {
tracks: _.chain(tracks).uniq().sortBy(function(name) { return name; }).value(),
uris: uris
};
});
};
};
module.exports = new LibraryProvider();
|
/**
* Copyright (c) 2011 Sitelier Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Author: Chris Osborn
* Date: 1/5/12
*/
var Q = require('q');
var Class = require('capsela-util').Class;
var AssertRecord = require('./AssertRecord').AssertRecord;
var format = require('./Colorize').format;
var TestCase = Class.extend(
{
// test phases
SETUP: 'setUp',
TEST: 'test',
TEARDOWN: 'tearDown',
// test result codes
UNTESTED: 'not yet tested',
PASSED: 'passed',
FAILED: 'failed',
SKIPPED: 'skipped',
// failure reason codes
GENERAL_ERROR: 'an error occurred', // includes return promise rejection
SETUP_TEARDOWN_ERROR: 'an error occurred during setUp/tearDown',
ASSERTION_FAIL: 'assertion(s) failed',
ASSERTION_COUNT: 'unexpected number of assertions'
},
{
///////////////////////////////////////////////////////////////////////////
/**
* Initialize test case with name, test function, and optional setUp and
* tearDown functions.
*
* @param name
* @param func
* @param setUp
* @param tearDown
*/
init: function(name, func, setUp, tearDown) {
this.result = TestCase.UNTESTED;
this.name = name;
this.func = func;
this.setUp = setUp;
this.tearDown = tearDown;
// by default, each phase of a test times out if not ended within ten seconds
this.timeout = 10000;
},
///////////////////////////////////////////////////////////////////////////
/**
* Return the name of this test case.
*/
getName: function() {
return this.name;
},
///////////////////////////////////////////////////////////////////////////
/**
* Return the overall result code.
*/
getResult: function() {
return this.result;
},
///////////////////////////////////////////////////////////////////////////
/**
* Return the error object associated with a general error, if there was one. This
* includes an immediate exception on load, an asynchronous uncaught exception during
* the test, or the rejection of a returned promise.
*/
getGeneralError: function() {
return this.generalError;
},
///////////////////////////////////////////////////////////////////////////
/**
* Return true if there was a general error and it bubbled up to the event
* loop without being caught (such an error would cause process exit by default).
*/
getGeneralErrorUncaught: function() {
return this.generalError && this.generalError.uncaught;
},
///////////////////////////////////////////////////////////////////////////
/**
* If there was a general error, this returns the phase at which it occurred, either
* "setUp", "test", or "tearDown".
*/
getGeneralErrorPhase: function() {
return this.generalErrorPhase;
},
///////////////////////////////////////////////////////////////////////////
/**
* If the case failed, return the general type of failure (one of the failure reason
* codes defined above).
*/
getFailure: function() {
return this.failure;
},
///////////////////////////////////////////////////////////////////////////
/**
* Return an array of assertions made in the last run of this case.
*/
getAssertions: function() {
return this.assertions || [];
},
///////////////////////////////////////////////////////////////////////////
/**
* Get the number of assertions expected, or undefined if the test did not
* express an expectation.
*/
getExpectedAssertions: function() {
return this.expectedAssertions;
},
///////////////////////////////////////////////////////////////////////////
/**
* Return the run duration of this test in milliseconds.
*/
getDuration: function() {
var dur = this.endTime - this.startTime;
return isNaN(dur) ? 0 : dur; // only return a number if both start and end occurred
},
///////////////////////////////////////////////////////////////////////////
/**
* Run this case, and update the state to reflect the results. Returns
* a completion promise that in normal circumstances should not be
* rejected (that is, rejection indicates a fault in TestCase, not the
* test itself or the code under test).
*/
run: function(options) {
var t = this;
console.log(' ' + format(this.getName(), 'blue'));
// get untainted versions of setTimeout and Date.now
// before any test has a chance to patch them
var origSetTimeout = setTimeout;
var origDateNow = Date.now;
delete this.expectedAssertions;
this.endTime = NaN;
this.startTime = NaN;
function markStart() {
t.startTime = origDateNow();
}
function markEnd() {
t.endTime = origDateNow();
}
/**
* This utility sets up the given deferred object to monitor both uncaught exceptions
* and a timeout fuse, and rejects it if either occurs before it is otherwise
* resolved or rejected. It has no effect if the deferred is already resolved.
*
* @param def
* @param phase
*/
function setupAsyncMonitors(def, phase) {
// don't bother doing anything if the promise is already resolved
if (Q(def.promise).isPending()) {
// set up an uncaught exception handler
function onErr(err) {
// mark this as an uncaught error
err.uncaught = true;
def.reject(err);
}
process.on('uncaughtException', onErr);
/*
// set up a timeout
// This is implemented as a series of 10ms timeouts rather than a single long span
// because the latter would result in premature timeouts during interactive debugging.
var chunk = 10;
var elapsed = 0;
var to;
function checkTimeout() {
if (elapsed >= t.timeout) {
to = null;
def.reject(new Error('timed out waiting for ' + phase));
} else {
elapsed += chunk;
to = origSetTimeout(checkTimeout, chunk);
}
}
checkTimeout();
*/
// set up a timeout. this is a simpler single-span version of the above,
// here temporarily due to https://github.com/joyent/node/issues/2515
var to = origSetTimeout(function() {
def.reject(new Error('timed out waiting for ' + phase));
}, t.timeout);
// clean up both the timeout and the exception handler as soon
// as the promise settles
def.promise.fin(function() {
process.removeListener('uncaughtException', onErr);
clearTimeout(to);
});
}
}
var phase = TestCase.SETUP;
return Q().then(
function() {
markStart();
// if there is a setup function defined, run it and wait for it to be done
if (t.setUp) {
var setUpDone = Q.defer();
// call the actual setUp function
try {
var retval = t.setUp(setUpDone.resolve);
if (Q.isPromise(retval)) {
setUpDone.resolve(retval);
}
} catch (err) {
setUpDone.reject(err);
}
setupAsyncMonitors(setUpDone, TestCase.SETUP);
return setUpDone.promise;
}
}
).then(
function() {
// any necessary setup complete, we enter the test phase
phase = TestCase.TEST;
var testDone = Q.defer();
// construct an AssertRecord object to be passed in as the function's "test" parameter
t.assertRec = new AssertRecord();
t.assertRec.done = function() {
testDone.resolve();
};
// allows the test to be skipped
t.assertRec.skip = function() {
t.assertRec.close();
t.result = TestCase.SKIPPED;
testDone.resolve();
};
t.assertRec.setTimeout = function(ms) {
t.timeout = ms;
};
// call the actual test function
try {
var retval = t.func(t.assertRec);
if (Q.isPromise(retval)) {
testDone.resolve(retval);
}
} catch (err) {
testDone.reject(err);
}
setupAsyncMonitors(testDone, TestCase.TEST);
return testDone.promise;
}
)
.fail( // test return value rejection counts as an error
function(err) {
t.generalError = err;
t.generalErrorPhase = phase;
t.result = TestCase.FAILED;
t.failure = (phase == TestCase.TEST ? TestCase.GENERAL_ERROR : TestCase.SETUP_TEARDOWN_ERROR);
}
)
.then(
function() {
// we always want to run tearDown if it is defined and setUp was successful,
// whether or not the test was successful
phase = TestCase.TEARDOWN;
if (t.tearDown && t.failure != TestCase.SETUP_TEARDOWN_ERROR) {
var tearDownDone = Q.defer();
// call the actual tearDown function
try {
var retval = t.tearDown(tearDownDone.resolve);
if (Q.isPromise(retval)) {
tearDownDone.resolve(retval);
}
} catch (err) {
tearDownDone.reject(err);
}
setupAsyncMonitors(tearDownDone, TestCase.TEARDOWN);
return tearDownDone.promise.fail(
function(err) {
t.generalError = err;
t.generalErrorPhase = TestCase.TEARDOWN;
t.result = TestCase.FAILED;
t.failure = TestCase.SETUP_TEARDOWN_ERROR;
}
);
}
}
).then(
function() {
markEnd();
// finally, generate a result summary
t.summary = {
passed: true,
errored: false,
skipped: false,
aborted: false,
assertions: {
total: 0,
failed: 0
}
};
if (t.generalError) {
t.summary.passed = false;
t.summary.errored = true;
t.result = TestCase.FAILED;
if (t.failure == TestCase.SETUP_TEARDOWN_ERROR) {
t.summary.aborted = true;
}
}
else if (t.result == TestCase.SKIPPED) {
t.summary.skipped = true;
}
else {
t.result = TestCase.PASSED;
}
if (t.assertRec) {
t.expectedAssertions = t.assertRec.getExpected();
return t.assertRec.getAssertions().then(
function(assertions) {
t.assertions = assertions;
assertions.forEach(
function(assert) {
t.summary.assertions.total++;
if (assert.error) {
// if we haven't already marked failure for some other
// reason, do so now (don't want to overwrite a general
// error)
if (t.result == TestCase.PASSED) {
t.result = TestCase.FAILED;
t.failure = TestCase.ASSERTION_FAIL;
}
t.summary.passed = false;
t.summary.assertions.failed++;
}
}
);
// check the expected number of assertions, but only if nothing
// else has failed (if assertions are actually failing then an
// unexpected count is likely a moot point; first one must fix
// the assertions).
if ((typeof t.expectedAssertions != 'undefined') && (t.result == TestCase.PASSED)) {
if (assertions.length != t.expectedAssertions) {
t.result = TestCase.FAILED;
t.failure = TestCase.ASSERTION_COUNT;
t.summary.errored = true;
t.summary.passed = false;
}
}
return t.summary;
}
)
}
else {
return t.summary;
}
}
);
},
///////////////////////////////////////////////////////////////////////////
/**
* Get the summary produced by the last run.
*/
getSummary: function() {
return this.summary;
},
///////////////////////////////////////////////////////////////////////////
/**
* Set the timeout in ms to be used for this test.
*/
setTimeout: function(ms) {
this.timeout = ms;
}
}
);
exports.TestCase = TestCase;
|
export default (() => {
let o;
return Jymfony.Component.VarExporter.Internal.Hydrator.hydrate(
o = [
(new ReflectionClass('Jymfony.Component.DateTime.Internal.RuleSet')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.RuleSet')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.RuleSet')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.RuleSet')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
(new ReflectionClass('Jymfony.Component.DateTime.Internal.Rule')).newInstanceWithoutConstructor(),
],
null,
{
'Jymfony.Component.DateTime.Internal.RuleSet': {
['_name']: {
['0']: undefined,
['18']: undefined,
['35']: undefined,
['42']: undefined,
},
['_rules']: {
['0']: [
o[1],
o[2],
o[3],
o[4],
o[5],
o[6],
o[7],
o[8],
o[9],
o[10],
o[11],
o[12],
o[13],
o[14],
o[15],
o[16],
o[17],
],
['18']: [
o[19],
o[20],
o[21],
o[22],
o[23],
o[24],
o[25],
o[26],
o[27],
o[28],
o[29],
o[30],
o[31],
o[32],
o[33],
o[34],
],
['35']: [
o[36],
o[37],
o[38],
o[39],
o[40],
o[41],
],
['42']: [
o[43],
o[44],
o[45],
o[46],
o[47],
o[48],
],
},
['_cache']: {
['0']: {
['1917']: [
o[2],
o[3],
o[4],
],
['1918']: [
o[2],
o[3],
o[4],
],
['1919']: [
o[4],
],
['1920']: [
o[4],
],
['1942']: [
o[5],
o[6],
],
['1943']: [
o[6],
o[7],
o[8],
],
['1944']: [
o[8],
o[9],
o[10],
],
['1945']: [
o[10],
o[9],
o[11],
],
['1980']: [
o[14],
o[12],
o[15],
],
['1981']: [
o[14],
o[15],
o[16],
],
['1990']: [
o[14],
o[15],
o[16],
],
['1991']: [
o[14],
o[15],
o[16],
],
['1997']: [
o[15],
o[16],
o[17],
],
['1998']: [
o[15],
o[16],
o[17],
],
},
['18']: {
['1918']: [
o[20],
o[21],
o[22],
],
['1919']: [
o[22],
o[23],
o[24],
o[25],
],
['1920']: [
o[25],
],
['1921']: [
o[25],
o[26],
o[27],
o[28],
o[29],
],
['1922']: [
o[29],
],
['1980']: [
o[29],
],
['1981']: [
o[29],
o[30],
o[31],
],
['1982']: [
o[29],
o[30],
o[31],
],
['1987']: [
o[31],
o[32],
o[33],
],
['1988']: [
o[31],
o[32],
o[33],
],
['1989']: [
o[31],
o[32],
o[33],
],
['1990']: [
o[31],
o[32],
o[33],
],
['1991']: [
o[31],
o[32],
o[33],
],
['1992']: [
o[31],
o[32],
o[33],
],
['1993']: [
o[31],
o[32],
o[33],
],
['1994']: [
o[31],
o[32],
o[33],
],
['1995']: [
o[31],
o[32],
o[33],
],
['1996']: [
o[32],
o[33],
o[34],
],
['1997']: [
o[32],
o[33],
o[34],
],
['2001']: [
o[32],
o[33],
o[34],
],
['2002']: [
o[32],
o[33],
o[34],
],
['2003']: [
o[32],
o[33],
o[34],
],
['2004']: [
o[32],
o[33],
o[34],
],
['2009']: [
o[32],
o[33],
o[34],
],
['2010']: [
o[32],
o[33],
o[34],
],
['2011']: [
o[34],
],
['2019']: [
o[34],
],
['2020']: [
o[34],
],
},
['35']: {
['1993']: [
o[38],
o[39],
o[40],
],
['1994']: [
o[38],
o[39],
o[40],
],
['1995']: [
o[38],
o[39],
o[40],
],
['1996']: [
o[39],
o[40],
o[41],
],
['1997']: [
o[39],
o[40],
o[41],
],
},
['42']: {
['1992']: [
o[45],
o[46],
o[47],
],
['1993']: [
o[45],
o[46],
o[47],
],
['1995']: [
o[45],
o[46],
o[47],
],
['1996']: [
o[46],
o[47],
o[48],
],
['1998']: [
o[46],
o[47],
o[48],
],
['1999']: [
o[46],
o[47],
o[48],
],
['2000']: [
o[46],
o[47],
o[48],
],
['2010']: [
o[46],
o[47],
o[48],
],
['2011']: [
o[46],
o[47],
o[48],
],
['2013']: [
o[46],
o[47],
o[48],
],
['2014']: [
o[46],
o[47],
o[48],
],
['2015']: [
o[46],
o[47],
o[48],
],
['2016']: [
o[46],
o[47],
o[48],
],
},
},
},
'Jymfony.Component.DateTime.Internal.Rule': {
['_fromYear']: {
['1']: 1916,
['2']: 1916,
['3']: 1917,
['4']: 1917,
['5']: 1940,
['6']: 1942,
['7']: 1943,
['8']: 1943,
['9']: 1944,
['10']: 1944,
['11']: 1945,
['12']: 1977,
['13']: 1977,
['14']: 1978,
['15']: 1979,
['16']: 1981,
['17']: 1996,
['19']: 1917,
['20']: 1917,
['21']: 1918,
['22']: 1918,
['23']: 1919,
['24']: 1919,
['25']: 1919,
['26']: 1921,
['27']: 1921,
['28']: 1921,
['29']: 1921,
['30']: 1981,
['31']: 1981,
['32']: 1984,
['33']: 1985,
['34']: 1996,
['36']: 1977,
['37']: 1977,
['38']: 1978,
['39']: 1979,
['40']: 1981,
['41']: 1996,
['43']: 1977,
['44']: 1977,
['45']: 1978,
['46']: 1979,
['47']: 1981,
['48']: 1996,
},
['_toYear']: {
['1']: 1916,
['2']: 1916,
['3']: 1918,
['4']: 1918,
['5']: 1940,
['6']: 1942,
['7']: 1943,
['8']: 1943,
['9']: 1945,
['10']: 1944,
['11']: 1945,
['12']: 1980,
['13']: 1977,
['14']: 1978,
['15']: 1995,
['16']: Infinity,
['17']: Infinity,
['19']: 1917,
['20']: 1917,
['21']: 1918,
['22']: 1918,
['23']: 1919,
['24']: 1919,
['25']: 1919,
['26']: 1921,
['27']: 1921,
['28']: 1921,
['29']: 1921,
['30']: 1984,
['31']: 1983,
['32']: 1995,
['33']: 2010,
['34']: 2010,
['36']: 1980,
['37']: 1977,
['38']: 1978,
['39']: 1995,
['40']: Infinity,
['41']: Infinity,
['43']: 1980,
['44']: 1977,
['45']: 1978,
['46']: 1995,
['47']: Infinity,
['48']: Infinity,
},
['_inMonth']: {
['1']: 4,
['2']: 10,
['3']: 4,
['4']: 9,
['5']: 4,
['6']: 11,
['7']: 3,
['8']: 10,
['9']: 4,
['10']: 10,
['11']: 9,
['12']: 4,
['13']: 9,
['14']: 10,
['15']: 9,
['16']: 3,
['17']: 10,
['19']: 7,
['20']: 12,
['21']: 5,
['22']: 9,
['23']: 5,
['24']: 7,
['25']: 8,
['26']: 2,
['27']: 3,
['28']: 9,
['29']: 10,
['30']: 4,
['31']: 10,
['32']: 9,
['33']: 3,
['34']: 10,
['36']: 4,
['37']: 9,
['38']: 10,
['39']: 9,
['40']: 3,
['41']: 10,
['43']: 4,
['44']: 9,
['45']: 10,
['46']: 9,
['47']: 3,
['48']: 10,
},
['_on']: {
['1']: '30',
['2']: '1',
['3']: '15 %s this mon',
['4']: '15 %s this mon',
['5']: '1',
['6']: '2',
['7']: '29',
['8']: '4',
['9']: '1 %s this mon',
['10']: '2',
['11']: '16',
['12']: '1 %s this sun',
['13']: 'last sun %s',
['14']: '1',
['15']: 'last sun %s',
['16']: 'last sun %s',
['17']: 'last sun %s',
['19']: '1',
['20']: '28',
['21']: '31',
['22']: '16',
['23']: '31',
['24']: '1',
['25']: '16',
['26']: '14',
['27']: '20',
['28']: '1',
['29']: '1',
['30']: '1',
['31']: '1',
['32']: 'last sun %s',
['33']: 'last sun %s',
['34']: 'last sun %s',
['36']: '1 %s this sun',
['37']: 'last sun %s',
['38']: '1',
['39']: 'last sun %s',
['40']: 'last sun %s',
['41']: 'last sun %s',
['43']: '1 %s this sun',
['44']: 'last sun %s',
['45']: '1',
['46']: 'last sun %s',
['47']: 'last sun %s',
['48']: 'last sun %s',
},
['_at']: {
['1']: '23:00',
['2']: '1:00',
['3']: '2:00s',
['4']: '2:00s',
['5']: '2:00s',
['6']: '2:00s',
['7']: '2:00s',
['8']: '2:00s',
['9']: '2:00s',
['10']: '2:00s',
['11']: '2:00s',
['12']: '2:00s',
['13']: '2:00s',
['14']: '2:00s',
['15']: '2:00s',
['16']: '2:00s',
['17']: '2:00s',
['19']: '23:00',
['20']: '0:00',
['21']: '22:00',
['22']: '1:00',
['23']: '23:00',
['24']: '0:00u',
['25']: '0:00',
['26']: '23:00',
['27']: '23:00',
['28']: '0:00',
['29']: '0:00',
['30']: '0:00',
['31']: '0:00',
['32']: '2:00s',
['33']: '2:00s',
['34']: '2:00s',
['36']: '0:00',
['37']: '0:00',
['38']: '0:00',
['39']: '0:00',
['40']: '0:00',
['41']: '0:00',
['43']: '1:00u',
['44']: '1:00u',
['45']: '1:00u',
['46']: '1:00u',
['47']: '1:00u',
['48']: '1:00u',
},
['_save']: {
['1']: 3600,
['2']: 0,
['3']: 3600,
['4']: 0,
['5']: 3600,
['6']: 0,
['7']: 3600,
['8']: 0,
['9']: 3600,
['10']: 0,
['11']: 0,
['12']: 3600,
['13']: 0,
['14']: 0,
['15']: 0,
['16']: 3600,
['17']: 0,
['19']: 3600,
['20']: 0,
['21']: 7200,
['22']: 3600,
['23']: 7200,
['24']: 3600,
['25']: 0,
['26']: 3600,
['27']: 7200,
['28']: 3600,
['29']: 0,
['30']: 3600,
['31']: 0,
['32']: 0,
['33']: 3600,
['34']: 0,
['36']: 3600,
['37']: 0,
['38']: 0,
['39']: 0,
['40']: 3600,
['41']: 0,
['43']: 3600,
['44']: 0,
['45']: 0,
['46']: 0,
['47']: 3600,
['48']: 0,
},
['_letters']: {
['1']: 'S',
['2']: '-',
['3']: 'S',
['4']: '-',
['5']: 'S',
['6']: '-',
['7']: 'S',
['8']: '-',
['9']: 'S',
['10']: '-',
['11']: '-',
['12']: 'S',
['13']: '-',
['14']: '-',
['15']: '-',
['16']: 'S',
['17']: '-',
['19']: 'MST',
['20']: 'MMT',
['21']: 'MDST',
['22']: 'MST',
['23']: 'MDST',
['24']: 'MSD',
['25']: 'MSK',
['26']: 'MSD',
['27']: '+05',
['28']: 'MSD',
['29']: '-',
['30']: 'S',
['31']: '-',
['32']: '-',
['33']: 'S',
['34']: '-',
['36']: 'S',
['37']: '-',
['38']: '-',
['39']: '-',
['40']: 'S',
['41']: '-',
['43']: 'S',
['44']: '-',
['45']: '-',
['46']: '-',
['47']: 'S',
['48']: '-',
},
['_cache']: {
['1']: {},
['2']: {
['1916']: [
'001916-10-01T01:00:00',
'001916-10-01T01:00:00',
],
},
['3']: {
['1917']: [
'001917-04-16T02:00:00',
'001917-04-16T03:00:00',
],
['1918']: [
'001918-04-15T02:00:00',
'001918-04-15T03:00:00',
],
},
['4']: {
['1917']: [
'001917-09-17T02:00:00',
'001917-09-17T02:00:00',
],
['1918']: [
'001918-09-16T02:00:00',
'001918-09-16T02:00:00',
],
},
['5']: {
['1940']: [
'001940-04-01T02:00:00',
'001940-04-01T03:00:00',
],
},
['6']: {
['1942']: [
'001942-11-02T02:00:00',
'001942-11-02T02:00:00',
],
},
['7']: {
['1943']: [
'001943-03-29T02:00:00',
'001943-03-29T03:00:00',
],
},
['8']: {
['1943']: [
'001943-10-04T02:00:00',
'001943-10-04T02:00:00',
],
},
['9']: {
['1944']: [
'001944-04-03T02:00:00',
'001944-04-03T03:00:00',
],
['1945']: [
'001945-04-02T02:00:00',
'001945-04-02T03:00:00',
],
},
['10']: {
['1944']: [
'001944-10-02T02:00:00',
'001944-10-02T02:00:00',
],
},
['11']: {
['1945']: [
'001945-09-16T02:00:00',
'001945-09-16T02:00:00',
],
},
['12']: {
['1980']: [
'001980-04-06T02:00:00',
'001980-04-06T03:00:00',
],
},
['13']: {},
['14']: {
['1978']: [
'001978-10-01T02:00:00',
'001978-10-01T02:00:00',
],
},
['15']: {
['1980']: [
'001980-09-28T02:00:00',
'001980-09-28T02:00:00',
],
['1981']: [
'001981-09-27T02:00:00',
'001981-09-27T02:00:00',
],
['1990']: [
'001990-09-30T02:00:00',
'001990-09-30T02:00:00',
],
['1991']: [
'001991-09-29T02:00:00',
'001991-09-29T02:00:00',
],
['1995']: [
'001995-09-24T02:00:00',
'001995-09-24T02:00:00',
],
},
['16']: {
['1981']: [
'001981-03-29T02:00:00',
'001981-03-29T03:00:00',
],
['1990']: [
'001990-03-25T02:00:00',
'001990-03-25T03:00:00',
],
['1991']: [
'001991-03-31T02:00:00',
'001991-03-31T03:00:00',
],
['1997']: [
'001997-03-30T02:00:00',
'001997-03-30T03:00:00',
],
['1998']: [
'001998-03-29T02:00:00',
'001998-03-29T03:00:00',
],
},
['17']: {
['1997']: [
'001997-10-26T02:00:00',
'001997-10-26T02:00:00',
],
['1998']: [
'001998-10-25T02:00:00',
'001998-10-25T02:00:00',
],
},
['19']: {},
['20']: {
['1917']: [
'001917-12-28T00:00:00',
'001917-12-28T00:00:00',
],
},
['21']: {
['1918']: [
'001918-05-31T22:00:00',
'001918-06-01T00:00:00',
],
},
['22']: {
['1918']: [
'001918-09-16T01:00:00',
'001918-09-16T02:00:00',
],
},
['23']: {
['1919']: [
'001919-05-31T23:00:00',
'001919-06-01T01:00:00',
],
},
['24']: {
['1919']: [
'001919-07-01T00:00:00u',
'001919-07-01T01:00:00',
],
},
['25']: {
['1919']: [
'001919-08-16T00:00:00',
'001919-08-16T00:00:00',
],
},
['26']: {
['1921']: [
'001921-02-14T23:00:00',
'001921-02-15T00:00:00',
],
},
['27']: {
['1921']: [
'001921-03-20T23:00:00',
'001921-03-21T01:00:00',
],
},
['28']: {
['1921']: [
'001921-09-01T00:00:00',
'001921-09-01T01:00:00',
],
},
['29']: {
['1921']: [
'001921-10-01T00:00:00',
'001921-10-01T00:00:00',
],
},
['30']: {
['1981']: [
'001981-04-01T00:00:00',
'001981-04-01T01:00:00',
],
['1982']: [
'001982-04-01T00:00:00',
'001982-04-01T01:00:00',
],
},
['31']: {
['1981']: [
'001981-10-01T00:00:00',
'001981-10-01T00:00:00',
],
['1982']: [
'001982-10-01T00:00:00',
'001982-10-01T00:00:00',
],
['1983']: [
'001983-10-01T00:00:00',
'001983-10-01T00:00:00',
],
},
['32']: {
['1987']: [
'001987-09-27T02:00:00',
'001987-09-27T02:00:00',
],
['1988']: [
'001988-09-25T02:00:00',
'001988-09-25T02:00:00',
],
['1989']: [
'001989-09-24T02:00:00',
'001989-09-24T02:00:00',
],
['1990']: [
'001990-09-30T02:00:00',
'001990-09-30T02:00:00',
],
['1991']: [
'001991-09-29T02:00:00',
'001991-09-29T02:00:00',
],
['1992']: [
'001992-09-27T02:00:00',
'001992-09-27T02:00:00',
],
['1993']: [
'001993-09-26T02:00:00',
'001993-09-26T02:00:00',
],
['1994']: [
'001994-09-25T02:00:00',
'001994-09-25T02:00:00',
],
['1995']: [
'001995-09-24T02:00:00',
'001995-09-24T02:00:00',
],
},
['33']: {
['1987']: [
'001987-03-29T02:00:00',
'001987-03-29T03:00:00',
],
['1988']: [
'001988-03-27T02:00:00',
'001988-03-27T03:00:00',
],
['1989']: [
'001989-03-26T02:00:00',
'001989-03-26T03:00:00',
],
['1990']: [
'001990-03-25T02:00:00',
'001990-03-25T03:00:00',
],
['1991']: [
'001991-03-31T02:00:00',
'001991-03-31T03:00:00',
],
['1992']: [
'001992-03-29T02:00:00',
'001992-03-29T03:00:00',
],
['1993']: [
'001993-03-28T02:00:00',
'001993-03-28T03:00:00',
],
['1994']: [
'001994-03-27T02:00:00',
'001994-03-27T03:00:00',
],
['1995']: [
'001995-03-26T02:00:00',
'001995-03-26T03:00:00',
],
['1996']: [
'001996-03-31T02:00:00',
'001996-03-31T03:00:00',
],
['1997']: [
'001997-03-30T02:00:00',
'001997-03-30T03:00:00',
],
['2001']: [
'002001-03-25T02:00:00',
'002001-03-25T03:00:00',
],
['2002']: [
'002002-03-31T02:00:00',
'002002-03-31T03:00:00',
],
['2003']: [
'002003-03-30T02:00:00',
'002003-03-30T03:00:00',
],
['2004']: [
'002004-03-28T02:00:00',
'002004-03-28T03:00:00',
],
['2009']: [
'002009-03-29T02:00:00',
'002009-03-29T03:00:00',
],
['2010']: [
'002010-03-28T02:00:00',
'002010-03-28T03:00:00',
],
},
['34']: {
['1996']: [
'001996-10-27T02:00:00',
'001996-10-27T02:00:00',
],
['1997']: [
'001997-10-26T02:00:00',
'001997-10-26T02:00:00',
],
['2001']: [
'002001-10-28T02:00:00',
'002001-10-28T02:00:00',
],
['2002']: [
'002002-10-27T02:00:00',
'002002-10-27T02:00:00',
],
['2003']: [
'002003-10-26T02:00:00',
'002003-10-26T02:00:00',
],
['2004']: [
'002004-10-31T02:00:00',
'002004-10-31T02:00:00',
],
['2009']: [
'002009-10-25T02:00:00',
'002009-10-25T02:00:00',
],
['2010']: [
'002010-10-31T02:00:00',
'002010-10-31T02:00:00',
],
},
['36']: {},
['37']: {},
['38']: {
['1978']: [
'001978-10-01T00:00:00',
'001978-10-01T00:00:00',
],
},
['39']: {
['1993']: [
'001993-09-26T00:00:00',
'001993-09-26T00:00:00',
],
['1994']: [
'001994-09-25T00:00:00',
'001994-09-25T00:00:00',
],
['1995']: [
'001995-09-24T00:00:00',
'001995-09-24T00:00:00',
],
},
['40']: {
['1993']: [
'001993-03-28T00:00:00',
'001993-03-28T01:00:00',
],
['1994']: [
'001994-03-27T00:00:00',
'001994-03-27T01:00:00',
],
['1995']: [
'001995-03-26T00:00:00',
'001995-03-26T01:00:00',
],
['1996']: [
'001996-03-31T00:00:00',
'001996-03-31T01:00:00',
],
['1997']: [
'001997-03-30T00:00:00',
'001997-03-30T01:00:00',
],
},
['41']: {
['1996']: [
'001996-10-27T00:00:00',
'001996-10-27T00:00:00',
],
['1997']: [
'001997-10-26T00:00:00',
'001997-10-26T00:00:00',
],
},
['43']: {},
['44']: {},
['45']: {
['1978']: [
'001978-10-01T01:00:00u',
'001978-10-01T01:00:00',
],
},
['46']: {
['1992']: [
'001992-09-27T01:00:00u',
'001992-09-27T01:00:00',
],
['1993']: [
'001993-09-26T01:00:00u',
'001993-09-26T01:00:00',
],
['1995']: [
'001995-09-24T01:00:00u',
'001995-09-24T01:00:00',
],
},
['47']: {
['1992']: [
'001992-03-29T01:00:00u',
'001992-03-29T02:00:00',
],
['1993']: [
'001993-03-28T01:00:00u',
'001993-03-28T02:00:00',
],
['1995']: [
'001995-03-26T01:00:00u',
'001995-03-26T02:00:00',
],
['1996']: [
'001996-03-31T01:00:00u',
'001996-03-31T02:00:00',
],
['1998']: [
'001998-03-29T01:00:00u',
'001998-03-29T02:00:00',
],
['1999']: [
'001999-03-28T01:00:00u',
'001999-03-28T02:00:00',
],
['2000']: [
'002000-03-26T01:00:00u',
'002000-03-26T02:00:00',
],
['2010']: [
'002010-03-28T01:00:00u',
'002010-03-28T02:00:00',
],
['2011']: [
'002011-03-27T01:00:00u',
'002011-03-27T02:00:00',
],
['2013']: [
'002013-03-31T01:00:00u',
'002013-03-31T02:00:00',
],
['2014']: [
'002014-03-30T01:00:00u',
'002014-03-30T02:00:00',
],
['2015']: [
'002015-03-29T01:00:00u',
'002015-03-29T02:00:00',
],
['2016']: [
'002016-03-27T01:00:00u',
'002016-03-27T02:00:00',
],
},
['48']: {
['1996']: [
'001996-10-27T01:00:00u',
'001996-10-27T01:00:00',
],
['1998']: [
'001998-10-25T01:00:00u',
'001998-10-25T01:00:00',
],
['1999']: [
'001999-10-31T01:00:00u',
'001999-10-31T01:00:00',
],
['2000']: [
'002000-10-29T01:00:00u',
'002000-10-29T01:00:00',
],
['2010']: [
'002010-10-31T01:00:00u',
'002010-10-31T01:00:00',
],
['2011']: [
'002011-10-30T01:00:00u',
'002011-10-30T01:00:00',
],
['2013']: [
'002013-10-27T01:00:00u',
'002013-10-27T01:00:00',
],
['2014']: [
'002014-10-26T01:00:00u',
'002014-10-26T01:00:00',
],
['2015']: [
'002015-10-25T01:00:00u',
'002015-10-25T01:00:00',
],
['2016']: [
'002016-10-30T01:00:00u',
'002016-10-30T01:00:00',
],
},
},
},
},
[
{
['offset']: 7324,
['dst']: false,
['abbrev']: 'LMT',
['until']: -2840148124,
['format']: 'LMT',
},
{
['offset']: 7324,
['dst']: false,
['abbrev']: 'KMT',
['until']: -1441159324,
['format']: 'KMT',
},
{
['offset']: 7200,
['dst']: false,
['abbrev']: 'EET',
['until']: -1247536800,
['format']: 'EET',
},
{
['offset']: 10800,
['dst']: false,
['abbrev']: 'MSK',
['until']: -892522800,
['format']: 'MSK',
},
{
['until']: -825382800,
['ruleSet']: o[0],
['offset']: 3600,
['abbrev']: 'CE%sT',
},
{
['until']: 646783200,
['ruleSet']: o[18],
['offset']: 10800,
['abbrev']: 'MSK/MSD',
},
{
['until']: 686106000,
['ruleSet']: undefined,
['offset']: 7200,
['abbrev']: 'EEST',
},
{
['until']: 788911200,
['ruleSet']: o[35],
['offset']: 7200,
['abbrev']: 'EE%sT',
},
{
['until']: Infinity,
['ruleSet']: o[42],
['offset']: 7200,
['abbrev']: 'EE%sT',
},
],
[
0,
18,
35,
42,
]
);
})();
;
|
var co = require('co');
var extend = require('extend-merge').extend;
var merge = require('extend-merge').merge;
class Fixture {
/**
* Constructor.
*
* @param Object config Possible options are:
* - `'connection'` _Function_ : The connection instance.
* - `'model'` _Function_ : The class model.
* - `'meta'` _Object_ : Some meta data.
* - `'alters'` _Object_ : The alters.
*/
constructor(config) {
var defaults = {
connection: undefined,
model: this._model,
meta: {},
alters: {}
};
config = extend({}, defaults, config);
/**
* The connection to the datasource.
*
* @var Function
*/
this._connection = config.connection;
/**
* The meta definition.
*
* @var Object
*/
this._meta = config.meta;
/**
* The alter definitions.
*
* @var array
*/
this._alters = config.alters;
/**
* The model.
*
* @var string
*/
this._model = config.model;
/**
* The schema definition.
*
* @var Object
*/
this._schema = {};
/**
* The cached schema instance.
*
* @var Function
*/
this._cache = undefined;
this._model.connection(this.connection());
}
/**
* Gets/sets the connection object to which this schema is bound.
*
* @param Function connection The connection to set or nothing to get the current one.
* @return Function Returns a connection instance.
*/
connection(connection) {
if (arguments.length) {
return this._connection = connection;
}
if (!this._connection) {
throw new Error("Error, missing connection for this schema.");
}
return this._connection;
}
/**
* Returns a dynamically created model based on the model class name passed as parameter.
*
* @return Function A model class name.
*/
model() {
return this._model;
}
/**
* Gets the associated schema.
*
* @return Function The associated schema instance.
*/
schema() {
if (this._cache) {
return this._cache;
}
this._cache = this.model().definition();
this._alterFields(this._cache);
return this._cache;
}
/**
* Populates some records.
*
* @return Promise
*/
populate(records) {
return co(function*() {
if(!Array.isArray(records)) {
records = [records];
}
for (var record of records) {
var data = this._alterRecord(record);
var entity = this.model().create(data);
yield entity.save();
}
}.bind(this));
}
/**
* Formats fields according the alter configuration.
*
* @param Object fields An object of fields
* @return Object Returns the modified fields.
*/
_alterFields(schema) {
for (var mode in this._alters) {
var values = this._alters[mode];
for (var key in values) {
var value = values[key];
switch(mode) {
case 'add':
schema.column(key, value);
break;
case 'change':
if (!schema.has(key)) {
throw new Error("Can't change the following unexisting field: `'" + key + "'`.");
}
var field = schema.field(key);
if (value['to'] !== undefined) {
schema.remove(key);
var to = value.to;
delete value.to;
delete value.value;
schema.column(to, extend({}, field, value));
}
break;
case 'drop':
schema.remove(key);
break;
}
}
}
}
/**
* Formats values according the alter configuration.
*
* @param Object record The record.
* @return Object Returns the modified record.
*/
_alterRecord(record) {
var result = {};
for (var name in record) {
var value = record[name];
if (this._alters.change && this._alters.change[name] !== undefined) {
var alter = this._alters.change[name];
if (alter.value) {
var fnct = alter.value;
value = fnct(record[name]);
} else {
value = record[name];
}
if (alter.to !== undefined) {
result[alter.to] = value;
} else {
result[name] = value;
}
} else {
result[name] = value;
}
}
return result;
}
create() {
return this.schema().create();
}
drop() {
return this.schema().drop();
}
}
module.exports = Fixture;
|
var attregexg=/([^"\s?>\/]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
var tagregex=/<[^>]*>/g;
var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
function parsexmltag(tag/*:string*/, skip_root/*:?boolean*/)/*:any*/ {
var z = ({}/*:any*/);
var eq = 0, c = 0;
for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
if(!skip_root) z[0] = tag.substr(0, eq);
if(eq === tag.length) return z;
var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
if(m) for(i = 0; i != m.length; ++i) {
cc = m[i];
for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
q = cc.substr(0,c);
quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
v = cc.substring(c+1+quot, cc.length-quot);
for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
if(j===q.length) {
if(q.indexOf("_") > 0) q = q.substr(0, q.indexOf("_")); // from ods
z[q] = v;
}
else {
var k = (j===5 && q.substr(0,5)==="xmlns"?"xmlns":"")+q.substr(j+1);
if(z[k] && q.substr(j-3,3) == "ext") continue; // from ods
z[k] = v;
}
}
return z;
}
function strip_ns(x/*:string*/)/*:string*/ { return x.replace(nsregex2, "<$1"); }
var encodings = {
'"': '"',
''': "'",
'>': '>',
'<': '<',
'&': '&'
};
var rencoding = evert(encodings);
var rencstr = "&<>'\"".split("");
// TODO: CP remap (need to read file version to determine OS)
var unescapexml/*:StringConv*/ = (function() {
/* 22.4.2.4 bstr (Basic String) */
var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/g, coderegex = /_x([\da-fA-F]{4})_/g;
return function unescapexml(text/*:string*/)/*:string*/ {
var s = text + '';
return s.replace(encregex, function($$, $1) { return encodings[$$]||String.fromCharCode(parseInt($1,$$.indexOf("x")>-1?16:10))||$$; }).replace(coderegex,function(m,c) {return String.fromCharCode(parseInt(c,16));});
};
})();
var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
function escapexml(text/*:string*/, xml/*:?boolean*/)/*:string*/{
var s = text + '';
return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
}
function escapexmltag(text/*:string*/)/*:string*/{ return escapexml(text).replace(/ /g,"_x0020_"); }
var htmlcharegex = /[\u0000-\u001f]/g;
function escapehtml(text){
var s = text + '';
return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + ";"; });
}
/* TODO: handle codepages */
var xlml_fixstr/*:StringConv*/ = (function() {
var entregex = /&#(\d+);/g;
function entrepl($$/*:string*/,$1/*:string*/)/*:string*/ { return String.fromCharCode(parseInt($1,10)); }
return function xlml_fixstr(str/*:string*/)/*:string*/ { return str.replace(entregex,entrepl); };
})();
var xlml_unfixstr/*:StringConv*/ = (function() {
return function xlml_unfixstr(str/*:string*/)/*:string*/ { return str.replace(/(\r\n|[\r\n])/g,"\ "); };
})();
function parsexmlbool(value/*:any*/, tag/*:?string*/)/*:boolean*/ {
switch(value) {
case '1': case 'true': case 'TRUE': return true;
/* case '0': case 'false': case 'FALSE':*/
default: return false;
}
}
var utf8read/*:StringConv*/ = function utf8reada(orig) {
var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
while (i < orig.length) {
c = orig.charCodeAt(i++);
if (c < 128) { out += String.fromCharCode(c); continue; }
d = orig.charCodeAt(i++);
if (c>191 && c<224) { out += String.fromCharCode(((c & 31) << 6) | (d & 63)); continue; }
e = orig.charCodeAt(i++);
if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
f = orig.charCodeAt(i++);
w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
out += String.fromCharCode(0xDC00 + (w&1023));
}
return out;
};
if(has_buf) {
var utf8readb = function utf8readb(data) {
var out = new Buffer(2*data.length), w, i, j = 1, k = 0, ww=0, c;
for(i = 0; i < data.length; i+=j) {
j = 1;
if((c=data.charCodeAt(i)) < 128) w = c;
else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
else { j = 4;
w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
}
if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
out[k++] = w%256; out[k++] = w>>>8;
}
out.length = k;
return out.toString('ucs2');
};
var corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
if(utf8read(corpus) == utf8readb(corpus)) utf8read = utf8readb;
// $FlowIgnore
var utf8readc = function utf8readc(data) { return Buffer(data, 'binary').toString('utf8'); };
if(utf8read(corpus) == utf8readc(corpus)) utf8read = utf8readc;
}
// matches <foo>...</foo> extracts content
var matchtag = (function() {
var mtcache/*:{[k:string]:RegExp}*/ = ({}/*:any*/);
return function matchtag(f,g/*:?string*/)/*:RegExp*/ {
var t = f+"|"+(g||"");
if(mtcache[t]) return mtcache[t];
return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([^\u2603]*)</(?:\\w+:)?'+f+'>',((g||"")/*:any*/)));
};
})();
var vtregex = (function(){ var vt_cache = {};
return function vt_regex(bt) {
if(vt_cache[bt] !== undefined) return vt_cache[bt];
return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">(.*?)</(?:vt:)?" + bt + ">", 'g') );
};})();
var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>(.*)</;
function parseVector(data) {
var h = parsexmltag(data);
var matches = data.match(vtregex(h.baseType))||[];
if(matches.length != h.size) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
var res = [];
matches.forEach(function(x) {
var v = x.replace(vtvregex,"").match(vtmregex);
res.push({v:utf8read(v[2]), t:v[1]});
});
return res;
}
var wtregex = /(^\s|\s$|\n)/;
function writetag(f,g) {return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>';}
function wxt_helper(h)/*:string*/ { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
function writextag(f,g,h) { return '<' + f + (isval(h) /*:: && h */? wxt_helper(h) : "") + (isval(g) /*:: && g */? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
function write_w3cdtf(d/*:Date*/, t/*:?boolean*/)/*:string*/ { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }
function write_vt(s) {
switch(typeof s) {
case 'string': return writextag('vt:lpwstr', s);
case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', String(s));
case 'boolean': return writextag('vt:bool',s?'true':'false');
}
if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
throw new Error("Unable to serialize " + s);
}
var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
var XMLNS = ({
'dc': 'http://purl.org/dc/elements/1.1/',
'dcterms': 'http://purl.org/dc/terms/',
'dcmitype': 'http://purl.org/dc/dcmitype/',
'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsd': 'http://www.w3.org/2001/XMLSchema'
}/*:any*/);
XMLNS.main = [
'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
'http://purl.oclc.org/ooxml/spreadsheetml/main',
'http://schemas.microsoft.com/office/excel/2006/main',
'http://schemas.microsoft.com/office/excel/2006/2'
];
var XLMLNS = ({
'o': 'urn:schemas-microsoft-com:office:office',
'x': 'urn:schemas-microsoft-com:office:excel',
'ss': 'urn:schemas-microsoft-com:office:spreadsheet',
'dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
'mv': 'http://macVmlSchemaUri',
'v': 'urn:schemas-microsoft-com:vml',
'html': 'http://www.w3.org/TR/REC-html40'
}/*:any*/);
|
'use strict';
const $ = require('jquery');
const electron = require('electron');
const remote = electron.remote;
const dialog = remote.dialog;
const BrowserWindow = remote.BrowserWindow;
const path = require('path');
const DockerCompose = require('./../src/docker_compose');
let dcmp = null;
// View functions.
function showDcmpErrorDialog() {
dialog.showErrorBox(
'ERROR: Failed to load docker_compose.yml',
'Error: You need to select a docker-compose.yml first.');
}
function setLoading(now_loading){
let elem_loader = $('#loading_indicator');
let elem_staus_content = $('#runtime_info_contents');
if (now_loading) {
elem_loader.removeClass('hidden');
elem_staus_content.addClass('hidden');
} else {
elem_loader.addClass('hidden');
elem_staus_content.removeClass('hidden');
}
}
function loadingStart() { setLoading(true); }
function loadingFinish() { setLoading(false); }
function setupDcmpPathElem(dcmp_path) {
let elem_dcmp_dir_path = $('#dcmp_dir_path');
let elem_dcmp_yml_file = $('#dcmp_yml_file');
if (!dcmp_path) {
elem_dcmp_dir_path.html('None');
elem_dcmp_yml_file.html('None');
} else {
elem_dcmp_dir_path.html(path.dirname(dcmp_path));
elem_dcmp_yml_file.html(path.basename(dcmp_path));
}
}
function foreachDcmpButtons(targets, func) {
let all_flag = false;
if (typeof targets == 'string' && targets.toLowerCase() == 'all') {
all_flag = true;
} else if (!Array.isArray(targets)) {
targets = [targets];
}
$('#dcmp_control_buttons .btn').each((index, elem) => {
let cmd = $(elem).attr('id').split('_').pop();
for (let i = 0; i < targets.length; ++i) {
if (all_flag || targets[i] == cmd) {
func(elem);
}
}
});
}
function setDcmpButtonsVisible(targets, is_visible = true) {
foreachDcmpButtons(targets, (elem) => {
if (is_visible) $(elem).show();
else $(elem).hide();
});
}
function setDcmpButtonsEnable(targets, is_able = true) {
foreachDcmpButtons(targets, (elem) => {
$(elem).prop('disabled', !is_able);
});
}
function setupDcmpButtons(state) {
let config = {
'None': {
// UP, [D]STOP, [D]RESTART, [D]DOWN
'enabled': ['up'],
'disabled': ['stop', 'restart', 'down'],
'show': ['up', 'stop', 'restart', 'down'],
'hide': ['start', 'pause', 'unpause'],
},
'Exit': {
// START, [D]STOP, [D]RESTART, DOWN
'enabled': ['start', 'down'],
'disabled': ['stop', 'restart'],
'show': ['start', 'stop', 'restart', 'down'],
'hide': ['up', 'pause', 'unpause'],
},
'Up': {
// PAUSE, STOP, RESTART, DOWN
'enabled': ['pause', 'stop', 'restart', 'down'],
'disabled': [],
'show': ['pause', 'stop', 'restart', 'down'],
'hide': ['up', 'start', 'unpause'],
},
'Paused': {
// UNPAUSE, [D]STOP, [D]RESTART, [D]DOWN
'enabled': ['unpause'],
'disabled': ['stop', 'restart', 'down'],
'show': ['unpause', 'stop', 'restart', 'down'],
'hide': ['up', 'start', 'pause'],
}
};
setDcmpButtonsEnable(config[state].enabled, true);
setDcmpButtonsEnable(config[state].disabled, false);
setDcmpButtonsVisible(config[state].show, true);
setDcmpButtonsVisible(config[state].hide, false);
}
// Helper functions
function buildStatusTableHTML(status) {
let html = '<table class="table">';
html += '<thead><tr><th>#</th>' +
'<th>Name</th><th>Command</th><th>State</th><th>Ports</th>';
html += '</tr></thead><tbody>';
for (let i = 0; i < status.length; ++i) {
html += `<tr><th>${i}</th>` +
`<td>${status[i].Name}</td>` +
`<td>${status[i].Command}</td>` +
`<td>${status[i].State}</td>` +
`<td>${status[i].Ports}</td>` +
'</tr>';
}
html += '</tbody></table>'
return html;
}
function fetchStatus(callback) {
if (!dcmp) {
showDcmpErrorDialog();
return;
}
dcmp.fetchStatus((status) => {
let state = dcmp.getState(status);
setupDcmpButtons(state);
$('#dcmp_state').html(state);
$('#runtime_info_contents #status').html(buildStatusTableHTML(status));
if (callback) callback();
});
}
function fetchLogs(callback) {
if (!dcmp) {
showDcmpErrorDialog();
return;
}
dcmp.logs((stdout, stderr) => {
$('#runtime_info_contents #logs').html(`<code>${stdout}</code>`);
if (callback) callback();
});
}
function execDcmpCommand(cmd, callback) {
if (!dcmp) {
console.log('Error: You need to select a docker-compose.yml first.');
return;
}
loadingStart();
dcmp[cmd]((stdout, stderr) => {
if (callback) callback(stdout, stderr);
fetchStatus(() => { loadingFinish(); });
});
}
$(() => {
setDcmpButtonsVisible('all', false); // init by all hide.
// docker-compose.yml selector.
$('#dcmposer_selector').click(() => {
dialog.showOpenDialog(null, {
properties: ['openFile'],
title: 'Select docker-compose.yml',
defaultPath: '.',
filters: [{name: 'docker-compose.yml', extensions: ['yml']}]
}, (file_paths) => {
if (file_paths && file_paths.length > 0) {
let dcmp_file_path = file_paths[0];
dcmp = new DockerCompose(dcmp_file_path);
setupDcmpPathElem(dcmp_file_path);
loadingStart();
fetchStatus(() => { loadingFinish(); });
}
});
});
// docker-compose.yml canceler.
$('#dcmposer_resetter').click(() => {
setupDcmpPathElem(null);
});
// docker-compose command button.
$('#dcmp_up').click(() => {
console.log('dcmp_up button clicked');
execDcmpCommand('up');
});
$('#dcmp_start').click(() => {
console.log('dcmp_start button clicked');
execDcmpCommand('start');
});
$('#dcmp_pause').click(() => {
console.log('dcmp_pause button clicked');
execDcmpCommand('pause');
});
$('#dcmp_unpause').click(() => {
console.log('dcmp_unpause button clicked');
execDcmpCommand('unpause');
});
$('#dcmp_stop').click(() => {
console.log('dcmp_stop button clicked');
execDcmpCommand('stop');
});
$('#dcmp_restart').click(() => {
console.log('dcmp_restart button clicked');
execDcmpCommand('restart');
});
$('#dcmp_down').click(() => {
console.log('dcmp_down clicked');
execDcmpCommand('down');
});
// Runtime Info Tabs.
$('#runtime_info_panel #runtime_info_tabs a').click((event) => {
event.preventDefault();
$(this).tab('show');
// Execute tab
if (event.target.id == 'status-tab') {
loadingStart();
fetchStatus(() => { loadingFinish(); });
} else if (event.target.id == 'logs-tab') {
loadingStart();
fetchLogs(() => { loadingFinish(); }); // TODO: is it possible to support follow options?
}
});
});
|
'use strict';
//dependencies
const mongoose = require('mongoose');
const Role = mongoose.model('Role');
/**
* Role Controller
*
* @description :: Server-side logic for managing Role.
*/
module.exports = {
/**
* @function
* @name roles.index()
* @description display a list of all roles
* @param {HttpRequest} request a http request
* @param {HttpResponse} response a http response
*/
index: function (request, response, next) {
Role
.list(request, function (error, results) {
if (error) {
next(error);
} else {
response.ok(results);
}
});
},
/**
* @function
* @name roles.create()
* @description create a new role
* @param {HttpRequest} request a http request
* @param {HttpResponse} response a http response
*/
create: function (request, response, next) {
Role
.create(request.body, function (error, role) {
if (error) {
next(error);
} else {
response.created(role);
}
});
},
/**
* @function
* @name roles.show()
* @description display a specific role
* @param {HttpRequest} request a http request
* @param {HttpResponse} response a http response
*/
show: function (request, response, next) {
Role
.show(request, function (error, role) {
if (error) {
next(error);
} else {
response.ok(role);
}
});
},
/**
* @function
* @name roles.update()
* @description update a specific role
* @param {HttpRequest} request a http request
* @param {HttpResponse} response a http response
*/
update: function (request, response, next) {
Role
.findByIdAndUpdate(
request.params.id,
request.body, {
upsert: true,
new: true
},
function (error, role) {
if (error) {
next(error);
} else {
response.ok(role);
}
});
},
/**
* @function
* @name roles.destroy()
* @description delete a specific role
* @param {HttpRequest} request a http request
* @param {HttpResponse} response a http response
*/
destroy: function (request, response, next) {
Role
.findByIdAndRemove(
request.params.id,
function (error, role) {
if (error) {
next(error);
} else {
response.ok(role);
}
});
}
};
|
// copied from http://freenet.msp.mn.us/people/calguire/morse.html
var morse_map = {
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
'L': '.-..',
'M': '--',
'N': '-.',
'O': '---',
'P': '.--.',
'Q': '--.-',
'R': '.-.',
'S': '...',
'T': '-',
'U': '..-',
'V': '...-',
'W': '.--',
'X': '-..-',
'Y': '-.--',
'Z': '--..',
'Á': '.--.-', // A with acute accent
'Ä': '.-.-', // A with diaeresis
'É': '..-..', // E with acute accent
'Ñ': '--.--', // N with tilde
'Ö': '---.', // O with diaeresis
'Ü': '..--', // U with diaeresis
'1': '.----',
'2': '..---',
'3': '...--',
'4': '....-',
'5': '.....',
'6': '-....',
'7': '--...',
'8': '---..',
'9': '----.',
'0': '-----',
',': '--..--', // comma
'.': '.-.-.-', // period
'?': '..--..', // question mark
';': '-.-.-', // semicolon
':': '---...', // colon
'/': '-..-.', // slash
'-': '-....-', // dash
"'": '.----.', // apostrophe
'()': '-.--.-', // parenthesis
'_': '..--.-', // underline
'@': '.--.-.', // at symbol from http://www.learnmorsecode.com/
' ': '.......'
};
// might be the dumbest idea I've ever had
var morse_tree= {
'.': {
stop: 'E',
'.': {
stop: 'I',
'.': {
stop: 'S',
'.': {
stop: 'H',
'.': {
stop: '5'
},
'-': {
stop: '4'
}
},
'-': {
stop: 'V',
'.': {
stop: 'Ś'
},
'-': {
stop: '3'
}
}
},
'-': {
stop: 'U',
'.': {
stop: 'F',
// note lack of -
'.': {
stop: 'É'
}
},
'_': {
stop: 'Ü',
'.': {
stop: 'Ð',
'.': {
stop: '?'
},
'-': {
stop: '_'
}
},
'-': {
stop: '2'
}
}
}
},
'-': {
stop: 'A',
'.': {
stop: 'R',
'.': {
stop: 'L',
// note lack of .
'-': {
stop: 'È',
'.': {
stop: '"'
}
}
},
'-': {
stop: 'Ä',
// note lack of -
'.': {
stop: '+',
// note lack of .
'-': {
stop: '.'
}
}
}
},
'-': {
stop: 'W',
'.': {
stop: 'P',
// '.': {},
// TODO can't replicate character -_-
'-': {
stop: 'À',
// note lack of -
'.': {
stop: '@'
}
}
},
'-': {
stop: 'J',
'.': {
stop: 'Ĵ'
},
'-': {
stop: '1',
// note lack of -
'.': {
stop: "'"
}
}
}
}
}
},
'-': {
stop: 'T',
'.': {
stop: 'N',
'.': {
stop: 'D',
'.': {
stop: 'B',
'.': {
stop: '6',
// notive lack of .
'-': {
stop: '-'
}
},
'-': {
stop: '='
}
},
'-': {
stop: 'X',
// notice lack of -
'.': {
stop: '/'
}
}
},
'-': {
stop: 'K',
'.': {
stop: 'C',
'.': {
stop: 'Ç'
},
'-': {
// notice lack of stop
'.': {
stop: ';'
},
'-': {
stop: '!'
}
}
},
'-': {
stop: 'Y',
// notice lack of -
'.': {
stop: 'Ĥ',
// notice lack of .
'-': {
stop: '()'
}
}
}
}
},
'-': {
stop: 'M',
'.': {
stop: 'G',
'.': {
stop: 'Z',
'.': {
stop: '7'
},
'-': {
// note lack of stop
// note lack of .
'-': {
stop: ','
}
}
},
'-': {
stop: 'Q',
'.': {
stop: 'Ĝ'
},
'-': {
stop: 'Ñ'
}
}
},
'-': {
stop: 'O',
'.': {
stop: 'Ö',
// note lack of -
'.': {
stop: '8',
// note lack of -
'.': {
stop: ':'
}
}
},
'-': {
stop: 'CH', // is there a digraph for this?
'.': {
stop: '9'
},
'-': {
stop: '0'
}
}
}
}
}
};
function maybeRecurse (obj, func) {
if (!obj.pop) {
return func(obj);
}
var clone = [];
var i = 0;
for (; i < obj.length; i++) {
clone[i] = func(obj[i]);
}
return clone;
}
function decodeCharacterByMap (char) {
for (var i in morse_map) {
if (morse_map[i] == char) {
return i;
}
}
return ' ';
}
function decodeCharacterByDichotomy (char) {
var sub = char.split('');
return traverseNodeWithCharacters(tree, sub);
function traverseNodeWithCharacters (node, chars) {
var cur = chars.shift();
if (!node[cur]) {
return node.stop || '?';
}
return traverseNodeWithCharacters(node[cur], chars);
}
}
var morse={
encode:function encode (obj) {
return maybeRecurse(obj, encodeMorseString);
function encodeMorseString (str) {
var ret = str.split('');
for (var j in ret) {
ret[j] = morse_map[ret[j].toUpperCase()] || '?';
}
return ret.join(' ');
}
}
,decode:
function decode (obj, dichotomic) {
return maybeRecurse(obj, decodeMorseString);
function decodeMorseString (str) {
var ret = str.split(' ');
for (var i in ret) {
if (!dichotomic) {
ret[i] = decodeCharacterByMap(ret[i]);
} else {
ret[i] = decodeCharacterByDichotomy(ret[i]);
}
}
return ret.join('');
}
}
,map: morse_map
,tree: morse_tree
}; |
var app = angular.module('AngularBIRT');
app.directive('birtParameters', function() {
return {
restrict: 'A',
templateUrl: 'directives/parameters/html/0.0.1/parameters.html'
}
}); |
// col 列
module.exports = {
empty: true,
attributes: 'span',
parent: 'colgroup'
};
|
// @flow
/**
* This file provides support to domTree.js
* It's a storehouse of path geometry for SVG images.
*/
const path: {[string]: string} = {
// sqrtMain path geometry is from glyph U221A in the font KaTeX Main
sqrtMain: `M95 622c-2.667 0-7.167-2.667-13.5
-8S72 604 72 600c0-2 .333-3.333 1-4 1.333-2.667 23.833-20.667 67.5-54s
65.833-50.333 66.5-51c1.333-1.333 3-2 5-2 4.667 0 8.667 3.333 12 10l173
378c.667 0 35.333-71 104-213s137.5-285 206.5-429S812 17.333 812 14c5.333
-9.333 12-14 20-14h399166v40H845.272L620 507 385 993c-2.667 4.667-9 7-19
7-6 0-10-1-12-3L160 575l-65 47zM834 0h399166v40H845z`,
// size1 is from glyph U221A in the font KaTeX_Size1-Regular
sqrtSize1: `M263 601c.667 0 18 39.667 52 119s68.167
158.667 102.5 238 51.833 119.333 52.5 120C810 373.333 980.667 17.667 982 11
c4.667-7.333 11-11 19-11h398999v40H1012.333L741 607c-38.667 80.667-84 175-136
283s-89.167 185.333-111.5 232-33.833 70.333-34.5 71c-4.667 4.667-12.333 7-23
7l-12-1-109-253c-72.667-168-109.333-252-110-252-10.667 8-22 16.667-34 26-22
17.333-33.333 26-34 26l-26-26 76-59 76-60zM1001 0h398999v40H1012z`,
// size2 is from glyph U221A in the font KaTeX_Size2-Regular
sqrtSize2: `M1001 0h398999v40H1013.084S929.667 308 749
880s-277 876.333-289 913c-4.667 4.667-12.667 7-24 7h-12c-1.333-3.333-3.667
-11.667-7-25-35.333-125.333-106.667-373.333-214-744-10 12-21 25-33 39l-32 39
c-6-5.333-15-14-27-26l25-30c26.667-32.667 52-63 76-91l52-60 208 722c56-175.333
126.333-397.333 211-666s153.833-488.167 207.5-658.5C944.167 129.167 975 32.667
983 10c4-6.667 10-10 18-10zm0 0h398999v40H1013z`,
// size3 is from glyph U221A in the font KaTeX_Size3-Regular
sqrtSize3: `M424 2398c-1.333-.667-38.5-172-111.5-514 S202.667 1370.667 202
1370c0-2-10.667 14.333-32 49-4.667 7.333-9.833 15.667-15.5 25s-9.833 16-12.5
20l-5 7c-4-3.333-8.333-7.667-13-13l-13-13 76-122 77-121 209 968c0-2 84.667
-361.667 254-1079C896.333 373.667 981.667 13.333 983 10c4-6.667 10-10 18-10
h398999v40H1014.622S927.332 418.667 742 1206c-185.333 787.333-279.333 1182.333
-282 1185-2 6-10 9-24 9-8 0-12-.667-12-2zM1001 0h398999v40H1014z`,
// size4 is from glyph U221A in the font KaTeX_Size4-Regular
sqrtSize4: `M473 2713C812.333 913.667 982.333 13 983 11c3.333-7.333 9.333
-11 18-11h399110v40H1017.698S927.168 518 741.5 1506C555.833 2494 462 2989 460
2991c-2 6-10 9-24 9-8 0-12-.667-12-2s-5.333-32-16-92c-50.667-293.333-119.667
-693.333-207-1200 0-1.333-5.333 8.667-16 30l-32 64-16 33-26-26 76-153 77-151
c.667.667 35.667 202 105 604 67.333 400.667 102 602.667 104 606z
M1001 0h398999v40H1017z`,
// The doubleleftarrow geometry is from glyph U+21D0 in the font KaTeX Main
doubleleftarrow: `M262 157
l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3
0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28
14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5
c2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5
157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87
-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7
-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z
m8 0v40h399730v-40zm0 194v40h399730v-40z`,
// doublerightarrow is from glyph U+21D2 in font KaTeX Main
doublerightarrow: `M399738 392l
-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5
14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88
-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68
-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18
-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782
c-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3
-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z`,
// leftarrow is from glyph U+2190 in font KaTeX Main
leftarrow: `M400000 241H110l3-3c68.7-52.7 113.7-120
135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8
-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247
c-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208
490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3
1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202
l-3-3h399890zM100 241v40h399900v-40z`,
// overbrace is from glyphs U+23A9/23A8/23A7 in font KaTeX_Size4-Regular
leftbrace: `M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117
-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7
5-6 9-10 13-.7 1-7.3 1-20 1H6z`,
leftbraceunder: `M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13
35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688
0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7
-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z`,
// overgroup is from the MnSymbol package (public domain)
leftgroup: `M400000 80
H435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0
435 0h399565z`,
leftgroupunder: `M400000 262
H435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219
435 219h399565z`,
// Harpoons are from glyph U+21BD in font KaTeX Main
leftharpoon: `M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3
-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5
-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7
-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z`,
leftharpoonplus: `M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5
20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3
-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7
-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z
m0 0v40h400000v-40z`,
leftharpoondown: `M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333
5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5
1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667
-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z`,
leftharpoondownplus: `M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12
10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7
-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0
v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,
// hook is from glyph U+21A9 in font KaTeX Main
lefthook: `M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5
-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3
-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21
71.5 23h399859zM103 281v-40h399897v40z`,
leftlinesegment: `M40 281 V428 H0 V94 H40 V241 H400000 v40z
M40 281 V428 H0 V94 H40 V241 H400000 v40z`,
leftmapsto: `M40 281 V448H0V74H40V241H400000v40z
M40 281 V448H0V74H40V241H400000v40z`,
// tofrom is from glyph U+21C4 in font KaTeX AMS Regular
leftToFrom: `M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8
c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,
longequal: `M0 50 h400000 v40H0z m0 194h40000v40H0z
M0 50 h400000 v40H0z m0 194h40000v40H0z`,
midbrace: `M200428 334
c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14
-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7
311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11
12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z`,
midbraceunder: `M199572 214
c100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14
53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3
11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0
-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z`,
rightarrow: `M0 241v40h399891c-47.3 35.3-84 78-110 128
-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20
11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7
39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85
-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5
-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67
151.7 139 205zm0 0v40h399900v-40z`,
rightbrace: `M400000 542l
-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5
s-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1
c124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z`,
rightbraceunder: `M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3
28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237
-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z`,
rightgroup: `M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0
3-1 3-3v-38c-76-158-257-219-435-219H0z`,
rightgroupunder: `M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18
0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z`,
rightharpoon: `M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3
-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2
-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58
69.2 92 94.5zm0 0v40h399900v-40z`,
rightharpoonplus: `M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11
-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7
2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z
m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,
rightharpoondown: `M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8
8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5
-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95
-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z`,
rightharpoondownplus: `M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8
15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3
8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3
-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z
m0-194v40h400000v-40zm0 0v40h400000v-40z`,
righthook: `M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3
15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0
-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,
rightlinesegment: `M399960 241 V94 h40 V428 h-40 V281 H0 v-40z
M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`,
rightToFrom: `M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32
-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142
-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,
// twoheadleftarrow is from glyph U+219E in font KaTeX AMS Regular
twoheadleftarrow: `M0 167c68 40
115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69
-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3
-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19
-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101
10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z`,
twoheadrightarrow: `M400000 167
c-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3
41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42
18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333
-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70
101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z`,
// tilde1 is a modified version of a glyph from the MnSymbol package
tilde1: `M200 55.538c-77 0-168 73.953-177 73.953-3 0-7
-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0
114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0
4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128
-68.267.847-113-73.952-191-73.952z`,
// ditto tilde2, tilde3, & tilde4
tilde2: `M344 55.266c-142 0-300.638 81.316-311.5 86.418
-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9
31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114
c1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751
181.476 676 181.476c-149 0-189-126.21-332-126.21z`,
tilde3: `M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457
-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0
411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697
16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696
-338 0-409-156.573-744-156.573z`,
tilde4: `M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345
-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409
177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9
14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409
-175.236-744-175.236z`,
// widehat1 is a modified version of a glyph from the MnSymbol package
widehat1: `M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22
c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z`,
// ditto widehat2, widehat3, & widehat4
widehat2: `M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10
-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,
widehat3: `M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10
-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,
widehat4: `M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10
-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,
};
export default {path};
|
YUI.add('model-spinner-test', function (Y) {
var Assert = Y.Assert,
suite;
suite = new Y.Test.Suite('Model.Spinner');
suite.add(new Y.Test.Case({
name: 'Basic',
setUp: function () {
var Model = Y.Base.create('model', Y.Model, [ Y.Rednose.Model.Spinner ], {
sync: function (action, options, callback) {
var data = {};
Y.later(50, this, function () {
callback(null, data);
});
}
});
this.model = new Model();
},
tearDown: function () {
this.model.destroy();
this.model = null;
},
'Spinner should show when a model is destroyed': function () {
this.model.destroy({ remove: true });
Assert.isInstanceOf(Y.Node, Y.one('.rednose-spinner'));
},
'Spinner should hide after a model is destroyed': function () {
this.model.destroy({ remove: true });
this.wait(function(){
Assert.isNull(Y.one('.rednose-spinner'));
}, 100);
},
'Spinner should show when a model is saved': function () {
this.model.save();
Assert.isInstanceOf(Y.Node, Y.one('.rednose-spinner'));
},
'Spinner should hide after a model is saved': function () {
this.model.save();
this.wait(function(){
Assert.isNull(Y.one('.rednose-spinner'));
}, 100);
},
'Spinner should show when a model is loaded': function () {
this.model.load();
Assert.isInstanceOf(Y.Node, Y.one('.rednose-spinner'));
},
'Spinner should hide after a model is loaded': function () {
this.model.load();
this.wait(function(){
Assert.isNull(Y.one('.rednose-spinner'));
}, 100);
}
}));
Y.Test.Runner.add(suite);
}, '@VERSION@', {
requires: ['rednose-model-spinner', 'test']
});
|
import React from 'react'
import '../scss/main.scss'
class EmptyLayout extends React.Component {
constructor(props) {
super(props);
}
render() { return this.props.children(); }
}
export default EmptyLayout;
|
import ngeoPrintService from 'ngeo/print/Service.js';
import * as olBase from 'ol/index.js';
import olFeature from 'ol/Feature.js';
import olMap from 'ol/Map.js';
import olView from 'ol/View.js';
import * as olExtent from 'ol/extent.js';
import * as olProj from 'ol/proj.js';
import olGeomLineString from 'ol/geom/LineString.js';
import olGeomPoint from 'ol/geom/Point.js';
import olGeomPolygon from 'ol/geom/Polygon.js';
import olLayerImage from 'ol/layer/Image.js';
import olLayerTile from 'ol/layer/Tile.js';
import olLayerVector from 'ol/layer/Vector.js';
import olSourceImageWMS from 'ol/source/ImageWMS.js';
import olSourceTileWMS from 'ol/source/TileWMS.js';
import olSourceVector from 'ol/source/Vector.js';
import olSourceWMTS from 'ol/source/WMTS.js';
import olStyleCircle from 'ol/style/Circle.js';
import olStyleStroke from 'ol/style/Stroke.js';
import olStyleStyle from 'ol/style/Style.js';
import olStyleText from 'ol/style/Text.js';
import olStyleFill from 'ol/style/Fill.js';
import olTilegridWMTS from 'ol/tilegrid/WMTS.js';
describe('ngeo.print.Service', () => {
let ngeoCreatePrint;
beforeEach(() => {
angular.mock.inject((_ngeoCreatePrint_) => {
ngeoCreatePrint = _ngeoCreatePrint_;
});
});
it('creates an ngeo.print.Service instance', () => {
const print = ngeoCreatePrint('http://example.com/print');
expect(print instanceof ngeoPrintService).toBe(true);
});
describe('#createSpec', () => {
let print;
let map;
beforeEach(() => {
print = ngeoCreatePrint('http://example.com/print');
map = new olMap({
view: new olView({
center: [3000, 4000],
zoom: 0
})
});
});
describe('rotation', () => {
beforeEach(() => {
const view = map.getView();
view.rotate(Math.PI);
});
it('rotation angle is correct', () => {
const scale = 500;
const dpi = 72;
const layout = 'foo layout';
const format = 'pdf';
const customAttributes = {'foo': 'fooval', 'bar': 'barval'};
const spec = print.createSpec(map, scale, dpi, layout, format,
customAttributes);
expect(spec.attributes.map.rotation).toEqual(180);
});
});
describe('ImageWMS', () => {
beforeEach(() => {
map.addLayer(new olLayerImage({
source: new olSourceImageWMS({
url: 'http://example.com/wms',
params: {
'LAYERS': 'foo,bar',
'FORMAT': 'image/jpeg'
}
})
}));
});
it('creates a valid spec object', () => {
const scale = 500;
const dpi = 72;
const layout = 'foo layout';
const format = 'pdf';
const customAttributes = {'foo': 'fooval', 'bar': 'barval'};
const spec = print.createSpec(map, scale, dpi, layout, format,
customAttributes);
expect(spec).toEqual({
attributes: {
map: {
dpi: 72,
center: [3000, 4000],
projection: 'EPSG:3857',
rotation: 0,
scale: 500,
layers: [{
baseURL: 'http://example.com/wms',
imageFormat: 'image/jpeg',
customParams: {
TRANSPARENT: true
},
layers: ['foo', 'bar'],
type: 'wms',
opacity: 1,
serverType: undefined,
version: undefined,
useNativeAngle: true
}]
},
foo: 'fooval',
bar: 'barval'
},
lang: 'en',
format: 'pdf',
layout: 'foo layout'
});
});
});
describe('TileWMS', () => {
beforeEach(() => {
map.addLayer(new olLayerTile({
source: new olSourceTileWMS({
url: 'http://example.com/wms',
params: {
'LAYERS': 'foo,bar',
'FORMAT': 'image/jpeg'
}
})
}));
});
it('creates a valid spec object', () => {
const scale = 500;
const dpi = 72;
const layout = 'foo layout';
const format = 'pdf';
const customAttributes = {'foo': 'fooval', 'bar': 'barval'};
const spec = print.createSpec(map, scale, dpi, layout, format,
customAttributes);
expect(spec).toEqual({
attributes: {
map: {
dpi: 72,
center: [3000, 4000],
projection: 'EPSG:3857',
scale: 500,
rotation: 0,
layers: [{
baseURL: 'http://example.com/wms',
imageFormat: 'image/jpeg',
customParams: {
TRANSPARENT: true
},
layers: ['foo', 'bar'],
type: 'wms',
opacity: 1,
serverType: undefined,
version: undefined,
useNativeAngle: true
}]
},
foo: 'fooval',
bar: 'barval'
},
lang: 'en',
format: 'pdf',
layout: 'foo layout'
});
});
});
describe('WMTS', () => {
beforeEach(() => {
const projection = olProj.get('EPSG:3857');
const extent = projection.getExtent();
map.addLayer(new olLayerTile({
opacity: 0.5,
source: new olSourceWMTS({
dimensions: {'TIME': 'time'},
format: 'image/jpeg',
layer: 'layer',
matrixSet: 'matrixset',
projection: projection,
requestEncoding: 'REST',
style: 'style',
tileGrid: new olTilegridWMTS({
matrixIds: ['00', '01', '02'],
extent: extent,
origin: olExtent.getTopLeft(extent),
resolutions: [2000, 1000, 500],
tileSize: 512
}),
url: 'http://example.com/wmts/{Layer}/{Style}/{TileMatrixSet}/' +
'{TileMatrix}/{TileRow}/{TileCol}.jpeg',
version: '1.1.0'
})
}));
});
it('creates a valid spec object', () => {
const scale = 500;
const dpi = 72;
const layout = 'foo layout';
const format = 'pdf';
const customAttributes = {'foo': 'fooval', 'bar': 'barval'};
const spec = print.createSpec(map, scale, dpi, layout, format,
customAttributes);
expect(spec).toEqual({
attributes: {
map: {
dpi: 72,
center: [3000, 4000],
projection: 'EPSG:3857',
rotation: 0,
scale: 500,
layers: [{
baseURL: 'http://example.com/wmts/{Layer}/{Style}/' +
'{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg',
dimensions: ['TIME'],
dimensionParams: {'TIME': 'time'},
imageFormat: 'image/jpeg',
layer: 'layer',
matrices: [{
identifier: '00',
scaleDenominator: 7142857.142857144,
tileSize: [512, 512],
topLeftCorner: olExtent.getTopLeft(
olProj.get('EPSG:3857').getExtent()),
matrixSize: [39, 39]
}, {
identifier: '01',
scaleDenominator: 3571428.571428572,
tileSize: [512, 512],
topLeftCorner: olExtent.getTopLeft(
olProj.get('EPSG:3857').getExtent()),
matrixSize: [78, 78]
}, {
identifier: '02',
scaleDenominator: 1785714.285714286,
tileSize: [512, 512],
topLeftCorner: olExtent.getTopLeft(
olProj.get('EPSG:3857').getExtent()),
matrixSize: [156, 156]
}],
matrixSet: 'matrixset',
opacity: 0.5,
requestEncoding: 'REST',
style: 'style',
type: 'WMTS',
version: '1.1.0'
}]
},
foo: 'fooval',
bar: 'barval'
},
lang: 'en',
format: 'pdf',
layout: 'foo layout'
});
});
});
describe('Vector', () => {
let style0, style1, style2, style3, style4;
beforeEach(() => {
const feature0 = new olFeature({
geometry: new olGeomPoint([0, 0]),
foo: '0'
});
const feature1 = new olFeature({
geometry: new olGeomLineString([[0, 0], [1, 1]]),
foo: '1'
});
const feature2 = new olFeature({
geometry: new olGeomPolygon([[[0, 0], [1, 1], [1, 0], [0, 0]]]),
foo: '2'
});
const feature3 = new olFeature({
geometry: new olGeomPoint([0, 0]),
foo: '3'
});
style0 = new olStyleStyle({
fill: new olStyleFill({
color: [1, 1, 1, 0.1]
}),
image: new olStyleCircle({
radius: 1,
stroke: new olStyleStroke({
width: 1,
color: [1, 1, 1, 0.1]
})
}),
stroke: new olStyleStroke({
width: 1,
color: [1, 1, 1, 0.1]
})
});
// styles for feature0
const styles0 = [style0];
style1 = new olStyleStyle({
stroke: new olStyleStroke({
width: 2,
color: [2, 2, 2, 0.2]
})
});
// styles for feature1
const styles1 = [style0, style1];
style2 = new olStyleStyle({
fill: new olStyleFill({
color: [3, 3, 3, 0.3]
}),
stroke: new olStyleStroke({
width: 3,
color: [3, 3, 3, 0.3]
})
});
// styles for features2
const styles2 = [style0, style2];
style3 = new olStyleStyle({
text: new olStyleText({
font: 'normal 16px "sans serif"',
text: 'Ngeo',
textAlign: 'left',
offsetX: 42,
offsetY: -42,
fill: new olStyleFill({
color: [3, 3, 3, 0.3]
})
})
});
// Here to check that textAlign default value is set.
style4 = new olStyleStyle({
text: new olStyleText({
font: 'normal 16px "sans serif"',
text: 'Ngeo',
offsetX: 42,
offsetY: -42,
fill: new olStyleFill({
color: [3, 3, 3, 0.3]
})
})
});
// styles for features3
const styles3 = [style3, style4];
const styleFunction = function(feature, resolution) {
const v = feature.get('foo');
if (v == '0') {
return styles0;
} else if (v == '1') {
return styles1;
} else if (v == '2') {
return styles2;
} else if (v == '3') {
return styles3;
}
};
map.addLayer(new olLayerVector({
opacity: 0.8,
source: new olSourceVector({
features: [feature0, feature1, feature2, feature3]
}),
style: styleFunction
}));
});
it('creates a valid spec object', () => {
const scale = 500;
const dpi = 72;
const layout = 'foo layout';
const format = 'pdf';
const customAttributes = {'foo': 'fooval', 'bar': 'barval'};
const spec = print.createSpec(map, scale, dpi, layout, format,
customAttributes);
const styleId0 = olBase.getUid(style0).toString();
const styleId1 = olBase.getUid(style1).toString();
const styleId2 = olBase.getUid(style2).toString();
const styleId3 = olBase.getUid(style3).toString();
const styleId4 = olBase.getUid(style4).toString();
const expectedStyle = {
version: 2
};
expectedStyle[`[_ngeo_style_0 = '${styleId0}-Point']`] = {
symbolizers: [{
type: 'point',
pointRadius: 1,
strokeColor: '#010101',
strokeOpacity: 0.1,
strokeWidth: 1
}]
};
expectedStyle[`[_ngeo_style_0 = '${styleId0}-LineString']`] = {
symbolizers: [{
type: 'line',
strokeColor: '#010101',
strokeOpacity: 0.1,
strokeWidth: 1
}]
};
expectedStyle[`[_ngeo_style_1 = '${styleId1}-LineString']`] = {
symbolizers: [{
type: 'line',
strokeColor: '#020202',
strokeOpacity: 0.2,
strokeWidth: 2
}]
};
expectedStyle[`[_ngeo_style_0 = '${styleId0}-Polygon']`] = {
symbolizers: [{
type: 'polygon',
fillColor: '#010101',
fillOpacity: 0.1,
strokeColor: '#010101',
strokeOpacity: 0.1,
strokeWidth: 1
}]
};
expectedStyle[`[_ngeo_style_1 = '${styleId2}-Polygon']`] = {
symbolizers: [{
type: 'polygon',
fillColor: '#030303',
fillOpacity: 0.3,
strokeColor: '#030303',
strokeOpacity: 0.3,
strokeWidth: 3
}]
};
expectedStyle[`[_ngeo_style_0 = '${styleId3}-Point']`] = {
symbolizers: [{
type: 'Text',
fontColor: '#030303',
fontWeight: 'normal',
fontSize: '16px',
fontFamily: '"sans serif"',
label: 'Ngeo',
labelAlign: 'lm',
labelXOffset: 42,
labelYOffset: 42
}]
};
expectedStyle[`[_ngeo_style_1 = '${styleId4}-Point']`] = {
symbolizers: [{
type: 'Text',
fontColor: '#030303',
fontWeight: 'normal',
fontSize: '16px',
fontFamily: '"sans serif"',
label: 'Ngeo',
labelAlign: 'cm',
labelXOffset: 42,
labelYOffset: 42
}]
};
// the expected properties of feature0
const properties0 = {
foo: '0',
'_ngeo_style_0': `${styleId0}-Point`,
};
// the expected properties of feature1
const properties1 = {
foo: '1',
'_ngeo_style_0': `${styleId0}-LineString`,
'_ngeo_style_1': `${styleId1}-LineString`,
};
// the expected properties of feature2
const properties2 = {
foo: '2',
'_ngeo_style_0': `${styleId0}-Polygon`,
'_ngeo_style_1': `${styleId2}-Polygon`,
};
// the expected properties of feature3
const properties3 = {
foo: '3',
'_ngeo_style_0': `${styleId3}-Point`,
'_ngeo_style_1': `${styleId4}-Point`,
};
expect(spec).toEqual({
attributes: {
map: {
dpi: 72,
center: [3000, 4000],
projection: 'EPSG:3857',
rotation: 0,
scale: 500,
layers: [{
geoJson: {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0, 0]
},
properties: properties0
}, {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [[0, 0], [1, 1]]
},
properties: properties1
}, {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[[0, 0], [1, 1], [1, 0], [0, 0]]]
},
properties: properties2
}, {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0, 0]
},
properties: properties3
}]
},
opacity: 0.8,
style: expectedStyle,
type: 'geojson'
}]
},
foo: 'fooval',
bar: 'barval'
},
lang: 'en',
format: 'pdf',
layout: 'foo layout'
});
});
});
describe('layer order', () => {
beforeEach(() => {
map.addLayer(new olLayerImage({
source: new olSourceImageWMS({
url: 'http://example.com/wms/bottom',
params: {
'LAYERS': 'foo,bar',
'FORMAT': 'image/jpeg'
}
})
}));
map.addLayer(new olLayerImage({
source: new olSourceImageWMS({
url: 'http://example.com/wms/top',
params: {
'LAYERS': 'foo,bar',
'FORMAT': 'image/jpeg'
}
})
}));
});
it('reverses the layer order', () => {
const scale = 500;
const dpi = 72;
const layout = 'foo layout';
const format = 'pdf';
const customAttributes = {'foo': 'fooval', 'bar': 'barval'};
const spec = print.createSpec(map, scale, dpi, layout, format,
customAttributes);
const layers = spec.attributes.map.layers;
expect(layers.length).toBe(2);
expect(layers[0].baseURL).toBe('http://example.com/wms/top');
expect(layers[1].baseURL).toBe('http://example.com/wms/bottom');
});
});
});
describe('#createReport', () => {
let print;
let spec;
let $httpBackend;
beforeEach(() => {
print = ngeoCreatePrint('http://example.com/print');
spec = {
attributes: {
map: {
dpi: 72,
center: [3000, 4000],
projection: 'EPSG:3857',
scale: 500,
layers: [{
baseURL: 'http://example.com/wms',
imageFormat: 'image/jpeg',
layers: ['foo', 'bar'],
type: 'wms'
}]
},
foo: 'fooval',
bar: 'barval'
},
layout: 'foo layout'
};
angular.mock.inject(($injector) => {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('POST', 'http://example.com/print/report.pdf')
.respond({
ref: 'deadbeef',
statusURL: '/print/status/deadbeef.json',
downloadURL: '/print/report/deadbeef.json'
});
});
});
afterEach(() => {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('triggers the report request and resolves the promise', () => {
$httpBackend.expectPOST('http://example.com/print/report.pdf');
const promise = print.createReport(spec);
const spy = jasmine.createSpy();
promise.then(spy);
$httpBackend.flush();
expect(spy.calls.count()).toBe(1);
expect(spy.calls.mostRecent().args[0].data).toEqual({
ref: 'deadbeef',
statusURL: '/print/status/deadbeef.json',
downloadURL: '/print/report/deadbeef.json'
});
});
/* describe('cancel report request', () => {
it('cancels the request', angular.mock.inject(($q) => {
$httpBackend.expectPOST('http://example.com/print/report.pdf');
const canceler = $q.defer();
print.createReport(spec, {
timeout: canceler.promise
});
canceler.resolve(); // abort the $http request
// We will get an "Unflushed requests: 1" error in afterEach when
// calling verifyNoOutstandingRequest if the aborting did not work.
}));
});*/
});
describe('#getStatus', () => {
let print;
let $httpBackend;
beforeEach(() => {
print = ngeoCreatePrint('http://example.com/print');
angular.mock.inject(($injector) => {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('GET',
'http://example.com/print/status/deadbeef.json').respond({
done: false,
downloadURL: '/print/report/deadbeef.json'
});
});
});
afterEach(() => {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('triggers the status request and resolves the promise', () => {
$httpBackend.expectGET('http://example.com/print/status/deadbeef.json');
const promise = print.getStatus('deadbeef');
const spy = jasmine.createSpy();
promise.then(spy);
$httpBackend.flush();
expect(spy.calls.count()).toBe(1);
expect(spy.calls.mostRecent().args[0].data).toEqual({
done: false,
downloadURL: '/print/report/deadbeef.json'
});
});
});
describe('#getReportUrl', () => {
let print;
beforeEach(() => {
print = ngeoCreatePrint('http://example.com/print');
});
it('returns the report URL', () => {
const url = print.getReportUrl('deadbeef');
expect(url).toBe('http://example.com/print/report/deadbeef');
});
});
describe('#getCapabilities', () => {
let print;
let $httpBackend;
// Only used to test that getCapabilities fetch the json from the proper url
let capabilities;
beforeEach(angular.mock.inject((_$httpBackend_) => {
$httpBackend = _$httpBackend_;
capabilities = {
'test': true
};
$httpBackend.when('GET', 'http://example.com/print/capabilities.json')
.respond(capabilities);
}));
beforeEach(() => {
print = ngeoCreatePrint('http://example.com/print');
});
it('gets the correct capabilities', () => {
let resp;
print.getCapabilities().then((response) => {
resp = response.data;
});
$httpBackend.flush();
expect(resp).toEqual(capabilities);
});
});
describe('#cancel', () => {
let print;
let $httpBackend;
beforeEach(angular.mock.inject((_$httpBackend_) => {
print = ngeoCreatePrint('http://example.com/print');
$httpBackend = _$httpBackend_;
$httpBackend.when('DELETE', 'http://example.com/print/cancel/deadbeef')
.respond(200);
}));
afterEach(() => {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('triggers the cancel request and resolves the promise', () => {
$httpBackend.expectDELETE('http://example.com/print/cancel/deadbeef');
const promise = print.cancel('deadbeef');
const spy = jasmine.createSpy();
promise.then(spy);
$httpBackend.flush();
expect(spy.calls.count()).toBe(1);
expect(spy.calls.mostRecent().args[0].status).toEqual(200);
});
});
});
|
/*
* PLUGIN CHECK_PORT
*
* Ukrainian language file.
*
* Author: Oleksandr Natalenko (pfactum@gmail.com)
*/
theUILang.checkPort = "Перевірити стан порту";
theUILang.portStatus = [
"Стан порту невідомий",
"Порт закрито",
"Порт відкрито"
];
thePlugins.get("check_port").langLoaded(); |
'use strict';
describe('Directive: rdMovieRating', function () {
beforeEach(module('angularjsRundownApp'));
var element;
// it('should make hidden element visible', inject(function ($rootScope, $compile) {
// element = angular.element('<rd-movie-rating></rd-movie-rating>');
// element = $compile(element)($rootScope);
// expect(element.text()).toBe('this is the rdMovieRating directive');
// }));
});
|
'use strict';
var servicesModule = require('./_index.js');
/**
* @ngInject
*/
servicesModule.service('dataService', function ($q, $timeout, sqliteService, $log) {
var service = {};
service.getCurrentElements = function () {
var query = "SELECT e.Id, e.Name, e.Description, e.Image, p.CurrentEnergy, ce.Location, ce.Id AS CeId FROM CurrentElement AS ce " +
"JOIN Player AS p ON p.Id = ce.PlayerId " +
"JOIN Element AS e ON e.Id = ce.ElementId " +
"WHERE p.Id = 1" +
";";
return sqliteService.query(query, []);
};
service.getAllElements = function () {
var query = "SELECT * FROM Element ";
return sqliteService.query(query);
};
service.getCombinedElement = function (element1, element2) {
var parameters = [element1.Id, element2.Id, element1.Id, element2.Id];
var query = "SELECT e.Id, e.Name, e.Description, e.Image, r.EnergyUsage,r.Id as RecipeId FROM Element AS e " +
"JOIN Recipe AS r ON r.ResultId = e.Id " +
"WHERE (r.Element1Id = ? AND r.Element2Id = ?) OR (r.Element2Id = ? AND r.Element1Id = ?)";
return sqliteService.query(query, parameters);
};
service.getElementParts = function (element) {
var parameters = [element.Id];
var query = "SELECT e.Id, e.Name, e.Description, e.Image, r.EnergyUsage FROM Element AS e " +
"JOIN Recipe AS r ON r.Element1Id = e.Id OR r.Element2Id = e.Id " +
"WHERE r.ResultId = ?";
return sqliteService.query(query, parameters);
};
service.getBaseElements = function () {
var parameters = [];
var query = "SELECT e.Id, e.Name, e.Description, e.Image, r.EnergyUsage FROM Element AS e " +
"LEFT JOIN Recipe AS r ON r.ResultId = e.Id " +
"WHERE r.ResultId IS NULL";
return sqliteService.query(query, parameters);
};
service.getBaseElementsExcept = function (elementId) {
var parameters = [elementId];
var query = "SELECT e.Id, e.Name, e.Description, e.Image, r.EnergyUsage FROM Element AS e " +
"LEFT JOIN Recipe AS r ON r.ResultId = e.Id " +
"WHERE r.ResultId IS NULL AND e.Id != ?";
return sqliteService.query(query, parameters);
};
service.isBaseElement = function (element) {
var deferred = $q.defer();
var parameters = [element.Id];
var query = "SELECT COUNT(*) AS count FROM Element AS e \
LEFT JOIN Recipe AS r ON r.ResultId = e.Id\
WHERE r.ResultId IS NULL AND e.Id = ?\
";
sqliteService.query(query, parameters).then(function (result) {
deferred.resolve(result[0].count == 1);
});
return deferred.promise;
};
service.getBaseElements = function () {
var parameters = [];
var query = "SELECT e.Id,e.Name,e.Image,e.Description,1 as isBaseElement FROM Element AS e \
LEFT JOIN Recipe AS r ON r.ResultId = e.Id\
WHERE r.ResultId IS NULL\
";
return sqliteService.query(query, parameters);
};
service.restoreBaseElements = function () {
var deferred = $q.defer();
service.getBaseElements().then(function (baseElements) {
var queries = [];
queries.push("DELETE FROM CurrentElement");
var location = {x: 100, y: 100};
for (var i = 0; i < baseElements.length; i++) {
var element = baseElements[i];
queries.push("INSERT INTO CurrentElement\
(PlayerId, ElementId, Location)\
VALUES\
(1, " + element.Id + ", '" + JSON.stringify(location) + "')\
");
location.x = location.x + 100;
if (i == 3) {
location.y = 200;
location.x = 200;
}
if (i == 4) {
location.y = 200;
location.x = 300;
}
}
sqliteService.chain(queries).then(function () {
deferred.resolve();
});
});
return deferred.promise;
};
service.updateCurrentElement = function (element) {
var parameters = [element.Id, JSON.stringify(element.Location), element.CeId];
var query = "UPDATE CurrentElement SET \
ElementId = ?, Location = ?\
WHERE Id = ?\
";
return sqliteService.query(query, parameters);
};
service.updateCurrentEnergy = function (energy) {
var parameters = [energy];
var query = "UPDATE Player SET CurrentEnergy = ? WHERE Id = 1";
return sqliteService.query(query, parameters);
};
service.getUnlockedRecipes = function () {
var parameters = [];
var query = "SELECT r.Id as RecipeId,r.Element1Id,r.Element2Id,r.ResultId as Id,r.EnergyUsage,e.Description,e.Name,e.Image FROM Recipe AS r \
JOIN Element AS e ON e.Id = r.ResultId\
JOIN UnlockedRecipe AS ur ON ur.RecipeId = r.Id\
JOIN Player AS p ON p.Id = ur.PlayerId";
return sqliteService.query(query, parameters);
};
service.unlockRecipe = function (recipeId) {
var deferred = $q.defer();
if (recipeId != null) {
sqliteService.query("SELECT count(*) AS count FROM UnlockedRecipe WHERE RecipeId = ?", [recipeId]).then(function (data) {
if (data[0].count >= 1) {
deferred.reject();
return;
}
var query = "INSERT INTO UnlockedRecipe(RecipeId,PlayerId) VALUES (?,?) ";
console.log(recipeId);
sqliteService.query(query, [recipeId, 1]).then(deferred.resolve
, deferred.reject);
}, deferred.reject);
}
else
{
deferred.reject("Id cannot be null!");
}
return deferred.promise;
};
return service;
});
|
module.exports = { prefix: 'fal', iconName: 'comment-alt', icon: [576, 512, [], "f27a", "M288 32C129 32 0 125.1 0 240c0 50.2 24.6 96.3 65.6 132.2-10.4 36.3-29.7 45.9-52.3 62.1-27.6 19.7-7.9 47.6 17.4 45.6 58.7-4.7 113.3-19.9 159.2-44.2 30.6 8 63.6 12.3 98 12.3 159.1 0 288-93 288-208C576 125.1 447.1 32 288 32zm0 384c-35.4 0-69.7-4.9-102-14.7-40.9 24-90 46.7-154 54.7 48-32 62.5-56.9 69.1-96.3C61.6 330.6 32 289.2 32 240c0-96.5 115.7-176 256-176 141.5 0 256 80.2 256 176 0 96.5-115.6 176-256 176zm32-176c0 17.7-14.3 32-32 32s-32-14.3-32-32 14.3-32 32-32 32 14.3 32 32zm96 0c0 17.7-14.3 32-32 32s-32-14.3-32-32 14.3-32 32-32 32 14.3 32 32zm-192 0c0 17.7-14.3 32-32 32s-32-14.3-32-32 14.3-32 32-32 32 14.3 32 32z"] }; |
module.exports = function Brake(){}
module.exports.prototype.engage = function(){ throw 'unimplemented' }
|
import React from 'react';
import ReactDOM from 'react-dom';
import { LocaleProvider } from 'antd';
import { AppContainer } from 'react-hot-loader';
import { store } from './store/configure-store';
import Application from './application';
import './index.css';
const rootEl = document.querySelector('#root');
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<LocaleProvider locale={require('antd/lib/locale-provider/pt_BR')}>
<Component store={store} />
</LocaleProvider>
</AppContainer>,
rootEl,
);
};
render(Application);
if (module.hot) {
module.hot.accept('./application', () => {
const NextApp = require('./application').default;
render(NextApp);
});
}
|
import Immutable from 'immutable';
import trim from 'trim';
import * as su from '../utils/string_utils';
export function country(countryCode) {
return countryCode.get(0);
}
export function isoCode(countryCode) {
return countryCode.get(1);
}
// TODO: fix misspelling, it's dialling
export function dialingCode(countryCode) {
return countryCode.get(2);
}
export function locationString(m) {
return `${dialingCode(m)} ${country(m)}`;
}
export const defaultLocation = Immutable.fromJS(["United States", "US", "+1"]);
export function findByIsoCode(str) {
return countryCodes.filter(x => isoCode(x) === str).get(0);
}
export function find(str) {
let query = trim(str);
let by;
if (/^\+?\d+$/.test(query)) {
by = "diallingCode";
query = query[0] === "+" ? query : `+${query}`;
query = query.toLowerCase();
} else if (query.length <= 2) {
by = "isoCode";
query = query.toUpperCase()
} else {
by = "country";
query = query.toLowerCase();
}
return countryCodes.filter(x => {
switch(by) {
case "diallingCode":
return su.startsWith(dialingCode(x), query);
case "isoCode":
return su.startsWith(isoCode(x), query);
case "country":
return su.startsWith(country(x).toLowerCase(), query);
}
});
}
// TODO: rename this, and the file, to "locations"
export const countryCodes = Immutable.fromJS([
[
"Afghanistan",
"AF",
"+93"
],
[
"Albania",
"AL",
"+355"
],
[
"Algeria",
"DZ",
"+213"
],
[
"American Samoa",
"AS",
"+1684"
],
[
"Andorra",
"AD",
"+376"
],
[
"Angola",
"AO",
"+244"
],
[
"Anguilla",
"AI",
"+1264"
],
[
"Antarctica",
"AQ",
"+672"
],
[
"Antigua and Barbuda",
"AG",
"+1268"
],
[
"Argentina",
"AR",
"+54 9"
],
[
"Armenia",
"AM",
"+374"
],
[
"Aruba",
"AW",
"+297"
],
[
"Australia",
"AU",
"+61"
],
[
"Austria",
"AT",
"+43"
],
[
"Azerbaijan",
"AZ",
"+994"
],
[
"Bahamas",
"BS",
"+1242"
],
[
"Bahrain",
"BH",
"+973"
],
[
"Bangladesh",
"BD",
"+880"
],
[
"Barbados",
"BB",
"+1246"
],
[
"Belarus",
"BY",
"+375"
],
[
"Belgium",
"BE",
"+32"
],
[
"Belize",
"BZ",
"+501"
],
[
"Benin",
"BJ",
"+229"
],
[
"Bermuda",
"BM",
"+1441"
],
[
"Bhutan",
"BT",
"+975"
],
[
"Bolivia, Plurinational State of",
"BO",
"+591"
],
[
"Bonaire, Sint Eustatius and Saba",
"BQ",
"+599"
],
[
"Bosnia and Herzegovina",
"BA",
"+387"
],
[
"Botswana",
"BW",
"+267"
],
[
"Bouvet Island",
"BV",
"+47"
],
[
"Brazil",
"BR",
"+55"
],
[
"British Indian Ocean Territory",
"IO",
"+246"
],
[
"Brunei Darussalam",
"BN",
"+673"
],
[
"Bulgaria",
"BG",
"+359"
],
[
"Burkina Faso",
"BF",
"+226"
],
[
"Burundi",
"BI",
"+257"
],
[
"Cambodia",
"KH",
"+855"
],
[
"Cameroon",
"CM",
"+237"
],
[
"Canada",
"CA",
"+1"
],
[
"Cape Verde",
"CV",
"+238"
],
[
"Cayman Islands",
"KY",
"+1345"
],
[
"Central African Republic",
"CF",
"+236"
],
[
"Chad",
"TD",
"+235"
],
[
"Chile",
"CL",
"+56"
],
[
"China",
"CN",
"+86"
],
[
"Christmas Island",
"CX",
"+61"
],
[
"Cocos (Keeling) Islands",
"CC",
"+61"
],
[
"Colombia",
"CO",
"+57"
],
[
"Comoros",
"KM",
"+269"
],
[
"Congo",
"CG",
"+242"
],
[
"Congo, the Democratic Republic of the",
"CD",
"+243"
],
[
"Cook Islands",
"CK",
"+682"
],
[
"Costa Rica",
"CR",
"+506"
],
[
"Croatia",
"HR",
"+385"
],
[
"Cuba",
"CU",
"+53"
],
[
"Curaçao",
"CW",
"+599"
],
[
"Cyprus",
"CY",
"+357"
],
[
"Czech Republic",
"CZ",
"+420"
],
[
"Côte d'Ivoire",
"CI",
"+225"
],
[
"Denmark",
"DK",
"+45"
],
[
"Djibouti",
"DJ",
"+253"
],
[
"Dominica",
"DM",
"+1767"
],
[
"Dominican Republic",
"DO",
"+1809"
],
[
"Dominican Republic",
"DO",
"+1829"
],
[
"Dominican Republic",
"DO",
"+1849"
],
[
"Ecuador",
"EC",
"+593"
],
[
"Egypt",
"EG",
"+20"
],
[
"El Salvador",
"SV",
"+503"
],
[
"Equatorial Guinea",
"GQ",
"+240"
],
[
"Eritrea",
"ER",
"+291"
],
[
"Estonia",
"EE",
"+372"
],
[
"Ethiopia",
"ET",
"+251"
],
[
"Falkland Islands (Malvinas)",
"FK",
"+500"
],
[
"Faroe Islands",
"FO",
"+298"
],
[
"Fiji",
"FJ",
"+679"
],
[
"Finland",
"FI",
"+358"
],
[
"France",
"FR",
"+33"
],
[
"French Guiana",
"GF",
"+594"
],
[
"French Polynesia",
"PF",
"+689"
],
[
"French Southern Territories",
"TF",
"+262"
],
[
"Gabon",
"GA",
"+241"
],
[
"Gambia",
"GM",
"+220"
],
[
"Georgia",
"GE",
"+995"
],
[
"Germany",
"DE",
"+49"
],
[
"Ghana",
"GH",
"+233"
],
[
"Gibraltar",
"GI",
"+350"
],
[
"Greece",
"GR",
"+30"
],
[
"Greenland",
"GL",
"+299"
],
[
"Grenada",
"GD",
"+1473"
],
[
"Guadeloupe",
"GP",
"+590"
],
[
"Guam",
"GU",
"+1671"
],
[
"Guatemala",
"GT",
"+502"
],
[
"Guernsey",
"GG",
"+44"
],
[
"Guinea",
"GN",
"+224"
],
[
"Guinea-Bissau",
"GW",
"+245"
],
[
"Guyana",
"GY",
"+592"
],
[
"Haiti",
"HT",
"+509"
],
[
"Heard Island and McDonald Mcdonald Islands",
"HM",
"+672"
],
[
"Holy See (Vatican City State)",
"VA",
"+3906"
],
[
"Honduras",
"HN",
"+504"
],
[
"Hong Kong",
"HK",
"+852"
],
[
"Hungary",
"HU",
"+36"
],
[
"Iceland",
"IS",
"+354"
],
[
"India",
"IN",
"+91"
],
[
"Indonesia",
"ID",
"+62"
],
[
"Iran, Islamic Republic of",
"IR",
"+98"
],
[
"Iraq",
"IQ",
"+964"
],
[
"Ireland",
"IE",
"+353"
],
[
"Isle of Man",
"IM",
"+44"
],
[
"Israel",
"IL",
"+972"
],
[
"Italy",
"IT",
"+39"
],
[
"Jamaica",
"JM",
"+1876"
],
[
"Japan",
"JP",
"+81"
],
[
"Jersey",
"JE",
"+44"
],
[
"Jordan",
"JO",
"+962"
],
[
"Kazakhstan",
"KZ",
"+7"
],
[
"Kenya",
"KE",
"+254"
],
[
"Kiribati",
"KI",
"+686"
],
[
"Korea, Democratic People's Republic of",
"KP",
"+850"
],
[
"Korea, Republic of",
"KR",
"+82"
],
[
"Kuwait",
"KW",
"+965"
],
[
"Kyrgyzstan",
"KG",
"+996"
],
[
"Lao People's Democratic Republic",
"LA",
"+856"
],
[
"Latvia",
"LV",
"+371"
],
[
"Lebanon",
"LB",
"+961"
],
[
"Lesotho",
"LS",
"+266"
],
[
"Liberia",
"LR",
"+231"
],
[
"Libya",
"LY",
"+218"
],
[
"Liechtenstein",
"LI",
"+423"
],
[
"Lithuania",
"LT",
"+370"
],
[
"Luxembourg",
"LU",
"+352"
],
[
"Macao",
"MO",
"+853"
],
[
"Macedonia, the Former Yugoslav Republic of",
"MK",
"+389"
],
[
"Madagascar",
"MG",
"+261"
],
[
"Malawi",
"MW",
"+265"
],
[
"Malaysia",
"MY",
"+60"
],
[
"Maldives",
"MV",
"+960"
],
[
"Mali",
"ML",
"+223"
],
[
"Malta",
"MT",
"+356"
],
[
"Marshall Islands",
"MH",
"+692"
],
[
"Martinique",
"MQ",
"+596"
],
[
"Mauritania",
"MR",
"+222"
],
[
"Mauritius",
"MU",
"+230"
],
[
"Mayotte",
"YT",
"+262"
],
[
"Mexico",
"MX",
"+52"
],
[
"Micronesia, Federated States of",
"FM",
"+691"
],
[
"Moldova, Republic of",
"MD",
"+373"
],
[
"Monaco",
"MC",
"+377"
],
[
"Mongolia",
"MN",
"+976"
],
[
"Montenegro",
"ME",
"+382"
],
[
"Montserrat",
"MS",
"+1664"
],
[
"Morocco",
"MA",
"+212"
],
[
"Mozambique",
"MZ",
"+258"
],
[
"Myanmar",
"MM",
"+95"
],
[
"Namibia",
"NA",
"+264"
],
[
"Nauru",
"NR",
"+674"
],
[
"Nepal",
"NP",
"+977"
],
[
"Netherlands",
"NL",
"+31"
],
[
"New Caledonia",
"NC",
"+687"
],
[
"New Zealand",
"NZ",
"+64"
],
[
"Nicaragua",
"NI",
"+505"
],
[
"Niger",
"NE",
"+227"
],
[
"Nigeria",
"NG",
"+234"
],
[
"Niue",
"NU",
"+683"
],
[
"Norfolk Island",
"NF",
"+672"
],
[
"Northern Mariana Islands",
"MP",
"+1670"
],
[
"Norway",
"NO",
"+47"
],
[
"Oman",
"OM",
"+968"
],
[
"Pakistan",
"PK",
"+92"
],
[
"Palau",
"PW",
"+680"
],
[
"Palestine, State of",
"PS",
"+970"
],
[
"Panama",
"PA",
"+507"
],
[
"Papua New Guinea",
"PG",
"+675"
],
[
"Paraguay",
"PY",
"+595"
],
[
"Peru",
"PE",
"+51"
],
[
"Philippines",
"PH",
"+63"
],
[
"Pitcairn",
"PN",
"+870"
],
[
"Poland",
"PL",
"+48"
],
[
"Portugal",
"PT",
"+351"
],
[
"Puerto Rico",
"PR",
"+1"
],
[
"Qatar",
"QA",
"+974"
],
[
"Romania",
"RO",
"+40"
],
[
"Russian Federation",
"RU",
"+7"
],
[
"Rwanda",
"RW",
"+250"
],
[
"Réunion",
"RE",
"+262"
],
[
"Saint Barthélemy",
"BL",
"+590"
],
[
"Saint Helena, Ascension and Tristan da Cunha",
"SH",
"+290"
],
[
"Saint Kitts and Nevis",
"KN",
"+1869"
],
[
"Saint Lucia",
"LC",
"+1758"
],
[
"Saint Martin (French part)",
"MF",
"+590"
],
[
"Saint Pierre and Miquelon",
"PM",
"+508"
],
[
"Saint Vincent and the Grenadines",
"VC",
"+1784"
],
[
"Samoa",
"WS",
"+685"
],
[
"San Marino",
"SM",
"+378"
],
[
"Sao Tome and Principe",
"ST",
"+239"
],
[
"Saudi Arabia",
"SA",
"+966"
],
[
"Senegal",
"SN",
"+221"
],
[
"Serbia",
"RS",
"+381"
],
[
"Seychelles",
"SC",
"+248"
],
[
"Sierra Leone",
"SL",
"+232"
],
[
"Singapore",
"SG",
"+65"
],
[
"Sint Maarten (Dutch part)",
"SX",
"+1721"
],
[
"Slovakia",
"SK",
"+421"
],
[
"Slovenia",
"SI",
"+386"
],
[
"Solomon Islands",
"SB",
"+677"
],
[
"Somalia",
"SO",
"+252"
],
[
"South Africa",
"ZA",
"+27"
],
[
"South Georgia and the South Sandwich Islands",
"GS",
"+500"
],
[
"South Sudan",
"SS",
"+211"
],
[
"Spain",
"ES",
"+34"
],
[
"Sri Lanka",
"LK",
"+94"
],
[
"Sudan",
"SD",
"+249"
],
[
"Suriname",
"SR",
"+597"
],
[
"Svalbard and Jan Mayen",
"SJ",
"+47"
],
[
"Swaziland",
"SZ",
"+268"
],
[
"Sweden",
"SE",
"+46"
],
[
"Switzerland",
"CH",
"+41"
],
[
"Syrian Arab Republic",
"SY",
"+963"
],
[
"Taiwan, Province of China",
"TW",
"+886"
],
[
"Tajikistan",
"TJ",
"+992"
],
[
"Tanzania, United Republic of",
"TZ",
"+255"
],
[
"Thailand",
"TH",
"+66"
],
[
"Timor-Leste",
"TL",
"+670"
],
[
"Togo",
"TG",
"+228"
],
[
"Tokelau",
"TK",
"+690"
],
[
"Tonga",
"TO",
"+676"
],
[
"Trinidad and Tobago",
"TT",
"+1868"
],
[
"Tunisia",
"TN",
"+216"
],
[
"Turkey",
"TR",
"+90"
],
[
"Turkmenistan",
"TM",
"+993"
],
[
"Turks and Caicos Islands",
"TC",
"+1649"
],
[
"Tuvalu",
"TV",
"+688"
],
[
"Uganda",
"UG",
"+256"
],
[
"Ukraine",
"UA",
"+380"
],
[
"United Arab Emirates",
"AE",
"+971"
],
[
"United Kingdom",
"GB",
"+44"
],
[
"United States",
"US",
"+1"
],
[
"Uruguay",
"UY",
"+598"
],
[
"Uzbekistan",
"UZ",
"+998"
],
[
"Vanuatu",
"VU",
"+678"
],
[
"Venezuela, Bolivarian Republic of",
"VE",
"+58"
],
[
"Viet Nam",
"VN",
"+84"
],
[
"Virgin Islands, British",
"VG",
"+1284"
],
[
"Virgin Islands, U.S.",
"VI",
"+1340"
],
[
"Wallis and Futuna",
"WF",
"+681"
],
[
"Western Sahara",
"EH",
"+212"
],
[
"Yemen",
"YE",
"+967"
],
[
"Zambia",
"ZM",
"+260"
],
[
"Zimbabwe",
"ZW",
"+263"
],
[
"Åland Islands",
"AX",
"+358"
]
]);
|
/** @jsx jsx */
import { jsx } from 'slate-hyperscript'
export const input = (
<element>
<element />
</element>
)
export const output = {
children: [
{
children: [],
},
],
}
|
var packageName = 'flemay:less-autoprefixer';
Package.describe({
name: packageName,
version: '1.0.2',
summary: 'The dynamic stylesheet language + Autoprefixer',
git: 'https://github.com/flemay/less-autoprefixer',
documentation: 'README.md'
});
Package.registerBuildPlugin({
name: "compileLessAddAutoprefixer",
use: [],
sources: [
'lib/plugin/compile-less.js'
],
npmDependencies: {
"less": "2.5.1",
"less-plugin-autoprefix": "1.4.2"
}
});
Package.onTest(function(api) {
api.use([packageName, 'test-helpers', 'tinytest', 'templating']);
api.add_files(['test/less_tests.less', 'test/less_tests.js', 'test/less_tests.html',
'test/less_tests_empty.less', 'test/autoprefixer_tests.import.less'
], 'client');
});
|
function demo(data, xaxis, yaxis, graphType) {
//console.log(data);
//console.log(axisx);
//console.log(axisy);
//create the canvas chart instance
var chartingCanvas = new CanvasCharts();
if(chartingCanvas.isCanvasSupported()){
var obj = {
"gradientColor1": "#cd9603",
"gradientColor2": "#f1de3f",
"bgFillStyle": "#efefef",
"borderStrokeStyle": "#000",
"textFillStyle": "#000",
"font": "Normal 12pt Helvetica Nueue Light",
"lineStrokeStyle": "#000",
"chartType": graphType
};
chartingCanvas.configure(obj);
//it is a good idea to set the height and width of the canvas based on your data array length
//var height = (data.length < 5) ? data.length * 80 : data.length * 50;
//but for an example...
var height = (data.length < 5) ? 300 : 500;
var width = xaxis.length * 80;
//#graph is the id of the div that will hold the graph as either an img or canvas element itself...see showChart() in the source to modify it's behavior as needed
chartingCanvas.createCanvas(document.getElementById("graph"), width, height);
if(graphType == "" || graphType == "hbar"){
chartingCanvas.drawChart(xaxis, 90, yaxis, 35, data);
}
else if(graphType == "line"){
chartingCanvas.drawChart(yaxis, 50, xaxis, 35, data);
}
else if(graphType == "vbar"){
chartingCanvas.drawChart(yaxis, 50, xaxis, 35, data);
}
chartingCanvas.showChart();
}
else{
alert("canvas not supported! Please use a decent browser..");
console.log("canvas not supported! Please use a decent browser..");
}
}
|
import React, {Component} from 'react';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
}
}
render() {
return (
<div className="text-center">
<h2>Sign In</h2>
<hr />
<div>
<div className="form-group">
<input className="form-control" placeholder="Username" name="user" type="text" onChange={(event) => {
this.setState({
username: event.target.value
});
}}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Password" name="password" type="password" onChange={(event) => {
this.setState({
password: event.target.value
});
}}/>
</div>
<button className="btn btn-md btn-success" onClick={() => {
this.props.login(this.state.username, this.state.password);
this.props.close();
}}>Sign in</button>
<button className="btn btn-md btn-danger" onClick={() => {this.props.close()}}>Cancel</button>
</div>
</div>
);
};
}
export default Login
|
'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('enrollments'); |
// mocha/suite.js
console.log('suite');
var assert = assert;
if (typeof require == 'function') {
require('../../stringtemplate');
assert = require('assert');
}
/* TESTS START HERE */
suite('string#template');
test('is method', function () {
assert(typeof ''.template == 'function');
});
test('returns unmodified when argument is not an object', function () {
var s = '';
assert(s.template() === s);
assert(s.template(1) === s);
assert(s.template(true) === s);
});
test('returns unmodified when data is empty object or array', function () {
var s = '';
assert(s.template(null) === s);
assert(s.template({}) === s);
assert(s.template([]) === s);
});
suite('inline values');
test('inline value regex', function () {
var s = '<p>$placeholder$</p>';
var tokens = s.match(/\$[^\$^\s]+\$/g);
assert(tokens.toString() === "$placeholder$");
});
test('replaces $placeholder$ token with corresponding value', function () {
var s = '<p>$placeholder$</p>';
assert(s.template({ placeholder: 'matched' }) === '<p>matched</p>');
});
test('replaces tokens without re-formatting or trimming', function () {
var s = ' $space$ ';
assert(s.template({ space: '[space]'}) === ' [space] ');
});
test('does not escape/unescape html/xml tags', function () {
var s = '<p>$value$</p>';
assert(s.template({ value: 'placeholder' }) === '<p>placeholder</p>');
});
test('does not replace un-matched $placeholder$ data', function () {
var s = '<p>$value$</p>';
assert(s.template({ wrongName: 'placeholder' }) === s);
});
test('does not replace tokens with empty data', function () {
var s = '<p>$value$</p>';
assert(s.template({ value: '' }) === s);
});
test('"$" chars inside $placeholder$ data are preserved', function () {
var s = '<p>$dollar$</p>';
assert(s.template({ dollar: '$<b>1.00</b>' }) === '<p>$<b>1.00</b></p>');
});
test('replaces $dot.value$ data', function () {
var s = '<p>$dot.value$</p>';
assert(s.template({
dot: {
value: 'placeholder'
}
}) === '<p>placeholder</p>');
});
test('replaces multiple $dot.value$ references', function () {
var s = '<p>$dot.value$</p><p>$dot.name$</p>' +
'<p>$dot.value$</p><p>$dot.name$</p>';
assert(s.template({
dot: {
value: 'placeholder',
name: 'match'
}
}) === '<p>placeholder</p><p>match</p><p>placeholder</p><p>match</p>');
});
suite('blocks');
test('handle path to object hash values', function () {
var s = [
'$#object.inner$',
' + $.$',
'$/object.inner$'
].join('\n');
var data = {
object: {
inner: {
name: 'match name',
value: 'match value'
}
}
};
var expected = [
"",
" + match name",
"",
" + match value",
""
].join('\n');
var actual = s.template(data);
// console.warn( actual );
// console.log( expected );
assert(actual === expected);
});
test('handle nested object hash values', function () {
var s = [
'$#object$',
'$#inner$',
' + $.$',
'$/inner$',
'$/object$'
].join('\n');
var data = {
object: {
inner: {
name: 'match name',
value: 'match value'
}
}
};
var expected = [
"",
" + match name",
"",
" + match value",
""
].join('\n');
var actual = s.template(data);
// console.warn( actual );
// console.log( expected );
assert(actual === expected);
});
test('handle nested object hash keys', function () {
var s = [
'$#object$',
'$#inner$',
' + $.name$',
' + $.value$',
'$/inner$',
'$/object$'
].join('\n');
var data = {
object: {
inner: {
name: 'match name',
value: 'match value'
}
}
};
var expected = [
"",
" + match name",
" + match value",
""
].join('\n');
var actual = s.template(data);
// console.warn( actual );
// console.warn( expected );
assert(actual === expected);
});
test('handle array hash values', function () {
var s = [
'$#names$',
' + $.$',
'$/names$'
].join('\n');
var data = {
names: ['don', 'key', 'ho-tay']
};
var expected = [
"",
" + don",
"",
" + key",
"",
" + ho-tay",
""
].join('\n');
var actual = s.template(data);
// console.warn( actual );
// console.log( expected );
assert(actual === expected);
});
test('hash path regex', function () {
var s = [
'$#object$',
'$#inner$',
' + $.name$',
'$/inner$',
'$/object$'
].join('\n');
var tokens = s.match(/\$\#[^\$^\s]+\$/g);
assert(tokens.toString() === "$#object$,$#inner$");
});
test('handle array hash key values', function () {
var s = [
'$#names$',
' + $.first$',
' + $.last$',
'$/names$'
].join('\n');
var data = {
names: [
{ first: 'david', last: 'cake' },
{ first: 'robert', last: 'donut' }, // get it?
{ first: 'nathaniel', last: 'bacon' }
]
};
var expected = [
"",
" + david",
" + cake",
"",
" + robert",
" + donut",
"",
" + nathaniel",
" + bacon",
""
].join('\n');
var actual = s.template(data);
// console.warn( actual );
// console.log( expected );
assert(actual === expected);
});
suite('complex blocks');
test('replaces $object$ $.$ $/object$ data', function () {
var s = [
'$#object$',
' <p>$.$</p> ',
'$/object$'
].join('');
var data = {
object: {
value: 'value',
name: 'name'
}
};
var expected = ' <p>value</p> <p>name</p> ';
var actual = s.template(data);
// console.warn( actual );
// console.log( expected );
assert(actual === expected);
});
test('deeply nested arrays', function () {
var s = [
'$arrayTitle$',
'<ul>',
'<li>',
'$#three$',
'<ul>',
'<li>',
'$#.$',
'<ul>',
'<li>',
'$#.$',
'<ul>',
'<li>',
'$.$',
'</li>',
'</ul>',
'$/.$',
'</li>',
'</ul>',
'$/.$',
'</li>',
'</ul>',
'$/three$',
'</li>',
'</ul>'
].join('\n');
var data = {
arrayTitle: 'deeply nested array',
three: [
[
[ 2, 4, 6 ],
[ 'z', 'q', 'x' ],
[ 'horse', 'shoe', 'corral', 'saddle', 'bit' ]
]
]
};
var expected = [
'deeply nested array',
'<ul>', '<li>', '',
'<ul>', '<li>', '',
'<ul>', '<li>', '',
'<ul>', '<li>', '2', '</li>', '</ul>', '',
'<ul>', '<li>', '4', '</li>', '</ul>', '',
'<ul>', '<li>', '6', '</li>', '</ul>', '',
'</li>', '</ul>', '',
'<ul>', '<li>', '',
'<ul>', '<li>', 'z', '</li>', '</ul>', '',
'<ul>', '<li>', 'q', '</li>', '</ul>', '',
'<ul>', '<li>', 'x', '</li>', '</ul>', '',
'</li>', '</ul>', '',
'<ul>', '<li>', '',
'<ul>', '<li>', 'horse', '</li>', '</ul>', '',
'<ul>', '<li>', 'shoe', '</li>', '</ul>', '',
'<ul>', '<li>', 'corral', '</li>', '</ul>', '',
'<ul>', '<li>', 'saddle', '</li>', '</ul>', '',
'<ul>', '<li>', 'bit', '</li>', '</ul>', '',
'</li>', '</ul>', '',
'</li>', '</ul>', '',
'</li>', '</ul>'
].join('\n');
var actual = s.template(data);
// console.warn( actual ); // split('\n')
// console.log( expected ); // split('\n')
assert(actual === expected);
});
test('deeply nested arrays in objects', function () {
var s4 = [
"<p>$title$</p>",
"<ul>",
"$#one$",
"<li>",
"<p>$title$</p>", // is this a valid case???
"<ul>",
"$#.one$",
"<li>",
"$.inner$",
"</li>",
"$/.one$",
"</ul>",
"</li>",
"$/one$",
"</ul>",
"<p>$one.innerTitle$</p>", // is this a valid case???
"<ul>",
"$#one$",
"<li>",
"<ul>",
"$#.two$",
"<li>",
"<ul>",
"$#.three$",
"<li>",
"<ul>",
"$#.four$",
"<li>",
"$.inner$",
"</li>",
"$/.four$",
"</ul>",
"</li>",
"$/.three$",
"</ul>",
"</li>",
"$/.two$",
"</ul>",
"</li>",
"$/one$",
"</ul>",
"<ul>",
"$#one$",
"<li>",
"<p>$one.arrayTitle$</p>", // is this a valid case???
"<ul>",
"$#.three$",
"<li>",
"<ul>",
"$#.$",
"<li>",
"$.$",
"</li>",
"$/.$",
"</ul>",
"</li>",
"$/.three$",
"</ul>",
"</li>",
"$/one$",
"</ul>"
].join('');
var d4 = {
title: 'nested example',
one: {
innerTitle: 'inner title',
one: [
{ inner: '*one*' },
{ inner: '*one*' },
{ inner: '*one*' },
{ inner: '*one*' }
],
two: {
three: {
four: [
{ inner: '*four*' },
{ inner: '*four*' },
{ inner: '*four*' },
{ inner: '*four*' }
]
}
},
arrayTitle: 'three: array',
three: [
[ 2, 4, 6 ],
[ 'z', 'q', 'x' ],
[ {}, [] ]
]
}
};
var expected = [
"<p>nested example</p>",
"<ul><li>",
"<p>nested example</p>",
"<ul><li>*one*</li><li>*one*</li><li>*one*</li><li>*one*</li></ul>",
"</li></ul>",
"<p>inner title</p>",
"<ul><li>",
"<ul><li>",
"<ul><li>",
"<ul>",
"<li>*four*</li><li>*four*</li><li>*four*</li><li>*four*</li>",
"</ul>",
"</li></ul>",
"</li></ul>",
"</li></ul>",
"<ul><li>",
"<p>three: array</p>",
"<ul>",
"<li><ul>",
"<li>2</li><li>4</li><li>6</li>",
"</ul></li>",
"<li><ul>",
"<li>z</li><li>q</li><li>x</li>",
"</ul></li>",
"<li><ul>",
"<li>[object Object]</li><li></li>",
"</ul></li>",
"</ul>",
"</li></ul>"
].join('');
var actual = s4.template(d4);
// console.warn( actual );
// console.warn( expected );
assert(actual === expected);
});
test('replaces indexed array data', function () {
var s = [
'$#.$',
'<li>$.$</li>',
'$/.$'
].join('\n');
var data = [ 33, false ];
var expected = [
'',
'<li>33</li>',
'',
'<li>false</li>',
''
].join('\n');
var actual = s.template(data);
// console.warn( actual );
// console.warn( expected );
assert(actual === expected);
});
test('replaces duplicated nested arrays of arrays', function () {
var s = [
'FIRST:',
'$#.$',
'$#.$',
'<p>$.$</p>',
'$/.$',
'$/.$',
'SECOND:',
'$#.$',
'$#.$',
'<p>$.$</p>',
'$/.$',
'$/.$'
].join('\n');
var data = [
[
[ 1, 2 ],
[ 3, 4, 5]
],
[
[ 6, 7],
[ 8, 9]
]
];
var expected = [
"FIRST:",
"",
"",
"<p>1,2</p>",
"",
"<p>3,4,5</p>",
"",
"",
"",
"<p>6,7</p>",
"",
"<p>8,9</p>",
"",
"",
"SECOND:",
"",
"",
"<p>1,2</p>",
"",
"<p>3,4,5</p>",
"",
"",
"",
"<p>6,7</p>",
"",
"<p>8,9</p>",
"",
""
].join('\n');
var actual = s.template(data);
// console.warn( actual ); // split('\n')
// console.log( expected ); // split('\n')
assert(actual === expected);
});
test('replaces indexed object key-value data', function () {
var s = [
'$#.$',
'<li>$.name$</li>',
'$/.$'
].join('\n');
var data = [
{ name: 'charlize' },
{ name: 'zora neale' }
];
var expected = [
'',
'<li>charlize</li>',
'',
'<li>zora neale</li>',
''
].join('\n');
assert(s.template(data) === expected);
});
test('replaces array index values using $#array$ $.$ and $/array$', function () {
var s = [
'<ul>',
'$#array$',
'<li>$.$</li>',
'$/array$',
'</ul>'
].join('\n');
var data = {
array: [ 'three', 'four', 'five' ]
};
assert(s.template(data).replace(/\n\n/g, '\n') === [
'<ul>',
'<li>three</li>',
'<li>four</li>',
'<li>five</li>',
'</ul>'
].join('\n'));
});
test('replaces hashed array item values using $#array$ $.item$ and $/array$', function () {
var s = [
'<ul>',
'$#array$',
'<li>$.item$</li>',
'$/array$',
'</ul>'
].join('\n');
var data = {
array: [
{ item: 'one' },
{ item: 'two' }
]
};
var expected = [
'<ul>',
'<li>one</li>',
'<li>two</li>',
'</ul>'
].join('\n');
// replace blank 'rows' in result
assert(s.template(data).replace(/\n\n/g, '\n') === expected);
});
test('prints array item values sequentially if not hashed', function () {
var s = [
'$#array$',
' + $.nested$',
'$/array$'
].join('');
var data = {
array: [
{ nested: [ 2, 4, 6, 8] }
]
};
var expected = ' + 2,4,6,8';
var actual = s.template(data);
// console.warn( actual ); // split()
// console.log( expected ); // split()
assert(actual === expected);
});
test('groups multi-row key-value data by array index', function () {
var s = [
'<ul>',
'$#addresses$',
'<li>$.street$</li>',
'<li>$.city$, $.state$</li>',
'$/addresses$',
'</ul>'
].join('\n');
var data = {
addresses: [
{ street: '123 fourth street', city: 'cityburgh', state: 'aa' },
{ street: '567 eighth street', city: 'burgville', state: 'bb' },
{ street: '910 twelfth street', city: 'villetown', state: 'cc' }
]
};
var expected = [
'<ul>',
'',
'<li>123 fourth street</li>',
'<li>cityburgh, aa</li>',
'',
'<li>567 eighth street</li>',
'<li>burgville, bb</li>',
'',
'<li>910 twelfth street</li>',
'<li>villetown, cc</li>',
'',
'</ul>'
].join('\n');
var actual = s.template(data);
// console.warn( actual ); // split('\n')
// console.log( expected ); // split('\n')
assert(actual === expected);
});
test('replace deeply nested arrays on object keys', function () {
var s = [
'<ul>',
'$#array$',
'$#.nested$',
'<li>$.name$</li>',
'$/.nested$',
'$/array$',
'</ul>',
].join('\n');
var data = {
array: [
{ nested: [
{ name: 'david' },
{ name: 'lawrence' },
{ name: 'charlie' },
{ name: 'john' }
]
}
]
};
var expected = [
'<ul>',
'',
'',
'<li>david</li>',
'',
'<li>lawrence</li>',
'',
'<li>charlie</li>',
'',
'<li>john</li>',
'',
'',
'</ul>'
].join('\n');
var actual = s.template(data);
// console.warn( actual )//.split('\n') )
// console.log( expected )//.split('\n') )
assert(actual === expected);
});
suite('bad arrays');
test('does not replace collection members when missing $.$ token', function () {
var s = ['$#array$', '<li>$item$</li>', '$/array$'].join('');
var data = {
array: [
{ item: 'one' },
{ item: 'two' }
]
};
var expected = ['$#array$', '<li>$item$</li>', '$/array$'].join('');
var actual = s.template(data);
// console.warn( actual ); // split('\n')
// console.log( expected ); // split('\n')
assert(actual === expected);
});
test('does not replace collection when missing end ($/..$) token', function () {
var s = [
'<ul>',
'$#missingEndTag$',
'<li>$.item$</li>',
'</ul>'
].join('\n');
var data = {
missingEndTag: [
{ item: 'one' },
{ item: 'two' }
]
};
var expected = [
'<ul>',
'$#missingEndTag$',
'<li>$.item$</li>',
'</ul>'
].join('\n');
var actual = s.template(data);
// console.warn( actual ); // split('\n')
// console.log( expected ); // split('\n')
assert(actual === expected);
});
/*** function#template ***/
suite('function#template for heredoc support');
test('is method', function () {
assert(typeof (function(){}).template == 'function');
});
test('returns empty string when function has no /*** and ***/ delimiters', function () {
function temp() {}
assert(temp.template() === '');
});
test('returns docstring between /*** and ***/ delimiters', function () {
function temp() {
/***Hello. I am a docstring, inside a function.***/
}
assert(temp.template() === 'Hello. I am a docstring, inside a function.');
});
test('preserves whitespace in /*** docstring ***/', function () {
function temp() {
/***
Hello.
I am a docstring,
with indentation and blank lines.
***/
}
var expected = [
'',
' Hello.',
' ',
' I am a docstring,',
' ',
' with indentation and blank lines.',
' ',
].join('\n');
assert(temp.template() === expected);
});
test('removes line comments found within /*** docstring ***/', function () {
function temp() {
/***
Hello. // I am a comment
I am a docstring,
inside a function.
***/
}
//
assert(-1 === temp.template().indexOf('I am a comment'));
});
test('calls docstring#template when data argument is specified', function () {
function temp() {
/***
<p>$title$</p>
***/
}
var data = { title: 'data test' };
var expected = [
'',
' <p>data test</p>',
' '
].join('\n');
// console.warn( temp.template(data).split('\n') );
// console.warn( expected.split('\n') );
assert(temp.template(data) === expected);
});
test('returns unprocessed docstring when data is not an object', function () {
function temp() {
/***
<p>$title$</p>
***/
}
var expected = ['', ' <p>$title$</p>', ' '].join('\n');
// console.warn( temp.template('data test').split('\n') );
// console.warn( expected.split('\n') );
assert(temp.template('data test') === expected);
});
/*** mixed data examples ***/
suite('mixed data examples');
test('mixed data map', function () {
// left-aligned to avoid all the whitespace comparisons...
function f() {
/***
<p>$title$</p>
<p>$object.main.property$ for $object.main.name$</p>
<ul>
$#items$
<li>$.name$, $.age$</li>
<li>$.address$</li>
$/items$
</ul>
<p>$title2$</p>
<ul>
$#list$
<li>$.$</li>
$/list$
</ul>
***/
}
var data = {
title: 'mixed data test',
object: {
main: {
property: 'property value at $object.main.property$',
name: 'sarah winchester'
}
},
items: [
{
name: 'david',
age: 28,
address: 'home'
},
{
name: 'divad',
age: 82,
address: 'away'
}
],
title2: 'list',
list: [ 'foo', 'bar', 'baz', 'quux' ]
};
var expected = [
'',
'<p>mixed data test</p>',
'<p>property value at $object.main.property$ for sarah winchester</p>',
'<ul>',
'',
'<li>david, 28</li>',
'<li>home</li>',
'',
'<li>divad, 82</li>',
'<li>away</li>',
'',
'</ul>',
'<p>list</p>',
'<ul>',
'',
'<li>foo</li>',
'',
'<li>bar</li>',
'',
'<li>baz</li>',
'',
'<li>quux</li>',
'',
'</ul>',
''
].join('\n');
var actual = f.template(data);
// console.warn( actual ); // split('\n')
// console.log( expected ); // split('\n')
assert(actual === expected);
});
test('combining template output', function () {
var list = [
'<ul>',
'$addresses$', // this is a string.template result
'</ul>'
].join('\n');
var address = [
'$#.$',
'<li>$.street$</li>',
'<li>$.city$, $.state$</li>',
'$/.$'
].join('\n');
var data = {
addresses: address.template([
{ street: '123 fourth street', city: 'cityburgh', state: 'aa' },
{ street: '567 eighth street', city: 'burgville', state: 'bb' },
{ street: '910 twelfth street', city: 'villetown', state: 'cc' }
])
};
var expected = [
'<ul>',
'',
'<li>123 fourth street</li>',
'<li>cityburgh, aa</li>',
'',
'<li>567 eighth street</li>',
'<li>burgville, bb</li>',
'',
'<li>910 twelfth street</li>',
'<li>villetown, cc</li>',
'',
'</ul>'
].join('\n');
var actual = list.template(data);
// console.warn( actual ); // split('\n')
// console.log( expected ); // split('\n')
assert(actual === expected);
});
test('css template example', function () {
// heredoc css
function cssruleset() {
/***
$selector$ {
$declarations$
}
***/
}
function declarations() {
/***
basic: 10px;
color: $color$;
background-color: $bgcolor$;
***/
}
var css = cssruleset.template({
selector: ".class ~ whatever::after",
declarations: declarations.template({
color: '#345',
bgcolor: 'rgb(34, 0, 53)'
})
});
var expected = (function () {
/***
.class ~ whatever::after {
basic: 10px;
color: #345;
background-color: rgb(34, 0, 53);
}
***/
}).template();
// console.warn(css)//.split('\n'));
// console.log(expected)//.split('\n'));
assert(css === expected);
});
test('conditioned template data', function () {
var rule = 'width: $width$';
var maxWidth = 600;
var pixel = 'px';
function condition(width, unit) {
return (width >= maxWidth ? maxWidth : width) + (unit || pixel);
}
assert(rule.template({ width: condition(300, 'em') }) === 'width: 300em');
assert(rule.template({ width: condition(800) }) === 'width: 600px');
}); |
/*
客户端自定义基类
*/
var BaseClass = cc.Class({
extends: cc.Class,
ctor:function(){
var argList = Array.prototype.slice.call(arguments);
this.JS_Name = "BaseClass";
this.Init.apply(this, argList);
},
Init:function(){
},
});
module.exports = BaseClass;
|
'use strict';
var path = require('path');
var _ = require('lodash');
var Handlebars = require('handlebars');
var sourceMapModule = require('source-map');
var SourceMapGenerator = sourceMapModule.SourceMapGenerator;
var SourceMapConsumer = sourceMapModule.SourceMapConsumer;
var Batch = require('../batch');
var File = require('../file');
var hbsUtil = require('../hbs-util');
var minimatches = require('../minimatches');
var Processor = require('../processor');
var processor = new Processor('http://handlebarsjs.com');
var runtimeFile = new File(path.join(__dirname, '..', '..', 'res', 'handlebars', 'handlebars.runtime.js'));
processor.getBatches = function(inputPaths) {
if (inputPaths.length === 0) {
return [];
}
var config = this.config;
var runtimeOutput = config.runtime;
return inputPaths.map(function(inputPath) {
return new Batch(
[ inputPath ],
[ inputPath + '.js', { path: inputPath + '.js.map', type: 'json' } ],
{ multiCore: true }
);
}).concat(runtimeOutput ? [ new Batch([], [ runtimeOutput ]) ] : []);
};
processor.process = function(inputs, outputs) {
/*jshint maxstatements:50*/
var log = this.log;
var config = this.config;
var partialPatterns = config.partialFiles;
var input = inputs[0];
var output = outputs[0];
var mapOutput = outputs[1];
// Handlebars runtime output batch
if (!input) {
return runtimeFile.getText().then(function(runtime) {
// Runtime does not initialize Handlebars.templates for some reason (it does for Handlebars.partials)
output.resolve(runtime + 'Handlebars.templates = {};\n');
});
}
var inputPath = input.path;
var inputData = input.data;
var collection = minimatches(inputPath, partialPatterns) ? 'partials' : 'templates';
var name = hbsUtil.getName(inputPath, config.nameRegex);
var options = config.options;
options = _.extend({}, options, {
srcName: inputPath, // For SourceMap
knownHelpers: _.transform(options.knownHelpers, function(map, name) {
map[name] = true; // Convert array to hash
})
});
try {
var prefix = 'Handlebars.' + collection + '[' + JSON.stringify(name) + '] = Handlebars.template(';
var precompiled = Handlebars.precompile(inputData, options);
var suffix = ');\n';
// Adapt SourceMap to compensate for code prefix and suffix
var generator = new SourceMapGenerator({ file: output.path });
// Handlebars source maps do not include source content; add it
generator.setSourceContent(inputPath, inputData);
var sourceMapConsumer = new SourceMapConsumer(precompiled.map);
sourceMapConsumer.eachMapping(function(mapping) {
try {
var generatedLine = mapping.generatedLine;
generator.addMapping({
source: mapping.source,
name: mapping.name,
original: { line: mapping.originalLine, column: mapping.originalColumn },
generated: {
line: generatedLine,
column: mapping.generatedColumn + (generatedLine === 1 ? prefix.length : 0)
}
});
} catch (error) {
// Handlebars sometimes returns invalid mappings for some reason; warn and discard those
log.warn('%s [%s]', error.message, inputPath);
}
});
output.resolve(prefix + precompiled.code + suffix);
mapOutput.resolve(generator);
} catch (error) {
output.reject(hbsUtil.improveError(error, inputPath));
}
};
module.exports = processor;
|
module.exports = function bar(){
return 'baz';
} |
module.exports = {
entry: './ui/main.js',
output: {
path: './public',
filename: 'build.js'
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
} |
const distance = require('../point/distance')
const transformMany = require('../point/transformMany')
module.exports = (tr, domain, range) => {
// Get an array of residuals i.e. the distances
// between the range points and transformed domain points.
//
// Parameters
// tr
// an estimated transform
// domain
// an array of points. The domain used in the estimation.
// range
// an array of points. The range used in the estimation.
//
// Return
// array of numbers, distances
//
const n = Math.min(domain.length, range.length)
const codomain = transformMany(domain, tr)
// Collect point-pair distances to array.
const arr = []
for (let i = 0; i < n; i += 1) {
arr.push(distance(codomain[i], range[i]))
}
return arr
}
|
module.exports = function(app) {
/*===============================================================================
************ Handle clicks and make them fast (on tap); ************
===============================================================================*/
app.initClickEvents = function () {
function handleClicks(e) {
/*jshint validthis:true */
var clicked = $(this);
// Close Modal
if (clicked.hasClass('modal-overlay')) {
if ($('.modal.modal-in').length > 0 && app.params.modalCloseByOutside)
app.closeModal('.modal.modal-in');
if ($('.actions-modal.modal-in').length > 0 && app.params.actionsCloseByOutside)
app.closeModal('.actions-modal.modal-in');
if ($('.popover.modal-in').length > 0) app.closeModal('.popover.modal-in');
}
if (clicked.hasClass('popup-overlay')) {
if ($('.popup.modal-in').length > 0 && app.params.popupCloseByOutside)
app.closeModal('.popup.modal-in');
}
if (clicked.hasClass('picker-modal-overlay')) {
if ($('.picker-modal.modal-in').length > 0)
app.closeModal('.picker-modal.modal-in');
}
// Picker
if (clicked.hasClass('close-picker')) {
var pickerToClose = $('.picker-modal.modal-in');
if (pickerToClose.length > 0) {
app.closeModal(pickerToClose);
}
else {
pickerToClose = $('.popover.modal-in .picker-modal');
if (pickerToClose.length > 0) {
app.closeModal(pickerToClose.parents('.popover'));
}
}
}
// Close Panel
if (clicked.hasClass('close-panel')) {
app.closePanel();
}
if (clicked.hasClass('panel-overlay') && app.params.panelsCloseByOutside) {
app.closePanel();
}
// Popup
var popup;
if (clicked.hasClass('close-popup')) {
app.closeModal('.popup.modal-in');
}
// Popover
if (clicked.hasClass('close-popover')) {
app.closeModal('.popover.modal-in');
}
}
$(document).on('click', '.modal-overlay, .popup-overlay, .picker-modal-overlay, .close-picker, .close-panel, .panel-overlay, .close-popup, .close-popover', handleClicks);
// Prevent scrolling on overlays
function preventScrolling(e) {
e.preventDefault();
}
if (app.support.touch && !app.device.android) {
$(document).on((app.params.fastClicks ? 'touchstart' : 'touchmove'), '.panel-overlay, .modal-overlay, .preloader-indicator-overlay, .popup-overlay, .searchbar-overlay', preventScrolling);
}
};
return app;
}; |
/**
* # Require
*
* Wrapper around `require` for injection purpose.
*/
module.exports = function() {
return {
/**
* Call the real require method
*
* @param {String} moduleName The module to require
* @param {*} The result returned by require
*/
require: function(moduleName) {
return require(moduleName);
}
};
};
module.exports['@singleton'] = true;
module.exports['@require'] = [];
|
// Create a zip archive of the built app
var fs = require('fs');
var archiver = require('archiver');
var packageData = require('./package.json');
var output = fs.createWriteStream(__dirname + '/' + packageData.name + '.zip');
var archive = archiver('zip');
output.on('close', function() {
console.log(archive.pointer() + ' total bytes');
});
archive.on('error', function(err) {
throw err;
});
archive.pipe(output);
archive
// Grab everything in the dist folder
.bulk({expand: true, cwd: 'dist/', src: './*', dest: '.'})
.finalize();
|
/**
* Copyright 2018-present Tuan Le.
*
* Licensed under the MIT License.
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*------------------------------------------------------------------------
*
* @module DomainFactory
* @description - A domain factory.
*
* @author Tuan Le (tuan.t.lei@gmail.com)
*
* @flow
*/
'use strict'; // eslint-disable-line
import {
ENV,
isNonEmptyString,
isString,
isFunction,
isObject,
isArray,
isNonEmptyObject,
isNonEmptyArray,
isSchema,
fallback,
log
} from '../../libs/utils/common-util';
import Composer from '../composer';
import EventStreamComposite from '../../libs/composites/event-stream-composite';
/* slow mode buffer timings */
const SLOW_MODE_BUFFER_TIME_SPAN_IN_MS = 500;
const SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS = 500;
/* time waiting for factory setup/teardown to complete */
const DEFAULT_SETUP_WAIT_TIME_IN_MS = 10000;
const DEFAULT_TEARDOWN_WAIT_TIME_IN_MS = 10000;
export default Composer({
composites: [
EventStreamComposite
],
static: {
type: `domain`
},
DomainFactory () {
/* flag indicates start method has called */
let _started = false;
/* domain interface and store */
let _intf;
let _store;
/* service cache */
let _serviceCache = {};
/* child and peer domain caches */
let _childDomainCache = {};
let _peerDomainCache = {};
/**
* @description - Initialize interface, store, and child domains to this domain.
*
* @method $init
* @return void
*/
this.$init = function () {
log(`warn0`, `DomainFactory.$init - Method is not implemented by default.`);
};
/**
* @description - Setup domain event stream.
*
* @method setup
* @param {function} done
* @return void
*/
this.setup = function (done) { // eslint-disable-line
if (ENV.DEVELOPMENT) {
if (!isFunction(done)) {
log(`error`, `DomainFactory.setup - Input done function is invalid.`);
}
}
done();
};
/**
* @description - Teardown domain event stream.
*
* @method teardown
* @param {function} done
* @return void
*/
this.teardown = function (done) { // eslint-disable-line
if (ENV.DEVELOPMENT) {
if (!isFunction(done)) {
log(`error`, `DomainFactory.teardown - Input done function is invalid.`);
}
}
done();
};
/**
* @description - Check if domain has a registered interface.
*
* @method hasInterface
* @return {object}
*/
this.hasInterface = function () {
return isObject(_intf);
};
/**
* @description - Check if domain has a registered store.
*
* @method hasStore
* @return {object}
*/
this.hasStore = function () {
return isObject(_store);
};
/**
* @description - Check if domain has a registered service.
*
* @method hasService
* @param {string} serviceName
* @return {object}
*/
this.hasService = function (serviceName) {
if (ENV.DEVELOPMENT) {
if (!isString(serviceName)) {
log(`error`, `DomainFactory.hasService - Input service name is invalid.`);
}
}
return Object.prototype.hasOwnProperty.call(_serviceCache, serviceName);
};
/**
* @description - Check if domain has a registered child domain.
*
* @method hasChildDomain
* @param {string} domainName
* @return {object}
*/
this.hasChildDomain = function (domainName) {
if (ENV.DEVELOPMENT) {
if (!isString(domainName)) {
log(`error`, `DomainFactory.hasChildDomain - Input domain name is invalid.`);
}
}
return Object.prototype.hasOwnProperty.call(_childDomainCache, domainName);
};
/**
* @description - Check if domain has a registered peer domain.
*
* @method hasPeerDomain
* @param {string} domainName
* @return {object}
*/
this.hasPeerDomain = function (domainName) {
if (ENV.DEVELOPMENT) {
if (!isString(domainName)) {
log(`error`, `DomainFactory.hasPeerDomain - Input domain name is invalid.`);
}
}
return Object.prototype.hasOwnProperty.call(_peerDomainCache, domainName);
};
/**
* @description - Check if domain has started.
*
* @method hasStarted
* @return {boolean}
*/
this.hasStarted = function () {
return _started;
};
/**
* @description - Get domain interface.
*
* @method getInterface
* @return {object}
*/
this.getInterface = function () {
const domain = this;
if (ENV.DEVELOPMENT) {
if (!isObject(_intf)) {
log(`warn0`, `DomainFactory.getInterface - Domain:${domain.name} is not registered with an interface.`);
}
}
return _intf;
};
/**
* @description - Get domain store.
*
* @method getStore
* @return {object}
*/
this.getStore = function () {
const domain = this;
if (ENV.DEVELOPMENT) {
if (!isObject(_store)) {
log(`warn0`, `DomainFactory.getStore - Domain:${domain.name} is not registered with a store.`);
}
}
return _store;
};
/**
* @description - Get domain registered services.
*
* @method getServices
* @param {array} serviceNames
* @return {array}
*/
this.getServices = function (...serviceNames) {
let services = [];
if (isNonEmptyObject(_serviceCache)) {
if (isNonEmptyArray(serviceNames)) {
if (ENV.DEVELOPMENT) {
if (!serviceNames.every((serviceName) => isString(serviceName))) {
log(`error`, `DomainFactory.getServices - Input service name is invalid.`);
} else if (!serviceNames.every((serviceName) => Object.prototype.hasOwnProperty.call(_serviceCache, serviceName))) {
log(`error`, `DomainFactory.getServices - Service is not found.`);
}
}
services = Object.entries(_serviceCache).filter(([ serviceName, service ]) => { // eslint-disable-line
return serviceNames.includes(serviceName);
}).map(([ serviceName, service ]) => service); // eslint-disable-line
} else {
services = Object.values(_serviceCache);
}
}
return services;
};
/**
* @description - Get registered child domains.
*
* @method getChildDomains
* @param {array} domainNames
* @return {array}
*/
this.getChildDomains = function (...domainNames) {
let childDomains = [];
if (isNonEmptyObject(_childDomainCache)) {
if (isNonEmptyArray(domainNames)) {
if (ENV.DEVELOPMENT) {
if (!domainNames.every((domainName) => isString(domainName))) {
log(`error`, `DomainFactory.getChildDomains - Input domain name is invalid.`);
} else if (!domainNames.every((domainName) => Object.prototype.hasOwnProperty.call(_childDomainCache, domainName))) {
log(`error`, `DomainFactory.getChildDomains - Domain is not found.`);
}
}
childDomains = Object.entries(_childDomainCache).filter(([ domainName, childDomain ]) => { // eslint-disable-line
return domainNames.includes(domainName);
}).map(([ domainName, childDomain ]) => childDomain); // eslint-disable-line
} else {
childDomains = Object.values(_childDomainCache);
}
}
return childDomains;
};
/**
* @description - Get registered peer domains.
*
* @method getPeerDomains
* @param {array} domainNames
* @return {array}
*/
this.getPeerDomains = function (...domainNames) {
let peerDomains = [];
if (isNonEmptyObject(_peerDomainCache)) {
if (isNonEmptyArray(domainNames)) {
if (ENV.DEVELOPMENT) {
if (!domainNames.every((domainName) => isString(domainName))) {
log(`error`, `DomainFactory.getPeerDomains - Input domain name is invalid.`);
} else if (!domainNames.every((domainName) => Object.prototype.hasOwnProperty.call(_peerDomainCache, domainName))) {
log(`error`, `DomainFactory.getPeerDomains - Domain is not found.`);
}
}
peerDomains = Object.entries(_peerDomainCache).filter(([ domainName, peerDomain ]) => { // eslint-disable-line
return domainNames.includes(domainName);
}).map(([ domainName, peerDomain ]) => peerDomain); // eslint-disable-line
} else {
peerDomains = Object.values(_peerDomainCache);
}
}
return peerDomains;
};
/**
* @description - Register child/peers domains, services, store and interface.
*
* @method register
* @param {object} definition - Domain registration definition for interface (required), child domains, and store.
* @return {object}
*/
this.register = function (definition) {
const domain = this;
if (ENV.DEVELOPMENT) {
// if (domain.isInitialized()) {
// log(`error`, `DomaninFactory.register - Domain:${domain.name} registration cannot be call after initialization.`);
// }
if (domain.isStreamActivated()) {
log(`error`, `DomaninFactory.register - Domain:${domain.name} registration cannot be call after event stream activation.`);
}
if (!isSchema({
interface: `object|undefined`,
store: `object|undefined`,
services: `array|undefined`,
peerDomains: `array|undefined`,
childDomains: `array|undefined`
}).of(definition)) {
log(`error`, `DomainFactory.register - Input definition is invalid.`);
}
}
const {
interface: intf,
store,
services,
peerDomains,
childDomains
} = definition;
if (isObject(intf)) {
if (ENV.DEVELOPMENT) {
if (!isSchema({
name: `string`,
type: `string`,
setup: `function`,
teardown: `function`,
observe: `function`,
activateIncomingStream: `function`,
activateOutgoingStream: `function`,
deactivateIncomingStream: `function`,
deactivateOutgoingStream: `function`,
renderToTarget: `function`
}).of(intf) || intf.type !== `interface`) {
log(`error`, `DomainFactory.register - Input interface is invalid.`);
} else if (isObject(_intf)) {
log(`warn1`, `DomainFactory.register - Domain:${domain.name} already registered interface:${_intf.name}.`);
}
}
_intf = intf;
if (isObject(_store)) {
_intf.register({
store: _store
});
}
log(`info1`, `Domain:${domain.name} registered interface:${_intf.name}.`);
}
if (isObject(store)) {
if (ENV.DEVELOPMENT) {
if (!isSchema({
name: `string`,
type: `string`,
setup: `function`,
teardown: `function`,
observe: `function`,
reset: `function`,
activateIncomingStream: `function`,
activateOutgoingStream: `function`,
deactivateIncomingStream: `function`,
deactivateOutgoingStream: `function`,
getStateAsObject: `function`
}).of(store) || store.type !== `store`) {
log(`error`, `DomainFactory.register - Input store is invalid.`);
} else if (isObject(_store)) {
log(`warn1`, `DomainFactory.register - Domain:${domain.name} already registered store:${_store.name}.`);
}
}
_store = store;
if (isObject(_intf)) {
_intf.register({
store: _store
});
}
log(`info1`, `Domain:${domain.name} registered store:${_store.name}.`);
}
if (isArray(services)) {
if (ENV.DEVELOPMENT) {
if (!services.every((service) => isSchema({
name: `string`,
type: `string`,
setup: `function`,
teardown: `function`,
observe: `function`,
reset: `function`,
activateIncomingStream: `function`,
activateOutgoingStream: `function`,
deactivateIncomingStream: `function`,
deactivateOutgoingStream: `function`
}).of(service) && service.type === `service`)) {
log(`error`, `DomainFactory.register - Input services are invalid.`);
}
}
_serviceCache = services.reduce((__serviceCache, service) => {
if (Object.prototype.hasOwnProperty.call(__serviceCache, service.name)) {
log(`warn1`, `DomainFactory.register - Domain:${domain.name} already has service:${service.name} registered.`);
} else {
__serviceCache[service.name] = service;
log(`info1`, `Domain:${domain.name} registered service:${service.name}.`);
}
return __serviceCache;
}, _serviceCache);
}
if (isArray(childDomains)) {
if (ENV.DEVELOPMENT) {
if (!childDomains.every((childDomain) => isSchema({
name: `string`,
type: `string`,
start: `function`,
stop: `function`,
observe: `function`,
getInterface: `function`
}).of(childDomain) && childDomain.type === `domain`)) {
log(`error`, `DomainFactory.register - Input child domains are invalid.`);
}
}
_childDomainCache = childDomains.reduce((__childDomainCache, childDomain) => {
if (domain.name === childDomain.name) {
log(`warn1`, `DomainFactory.register - Cannot register domain:${childDomain.name} as a child of itself.`);
} else if (Object.prototype.hasOwnProperty.call(__childDomainCache, childDomain.name)) {
log(`warn1`, `DomainFactory.register - Domain:${domain.name} already has child domain:${childDomain.name} registered.`);
} else {
__childDomainCache[childDomain.name] = childDomain;
log(`info1`, `Domain:${domain.name} registered child domain:${childDomain.name}.`);
}
return __childDomainCache;
}, _childDomainCache);
}
if (isObject(_intf) && isNonEmptyObject(_childDomainCache)) {
_intf.register({
childInterfaces: Object.values(_childDomainCache).filter((childDomain) => childDomain.hasInterface()).map((childDomain) => childDomain.getInterface())
});
}
if (isArray(peerDomains)) {
if (ENV.DEVELOPMENT) {
if (!peerDomains.every((peerDomain) => isSchema({
name: `string`,
type: `string`,
start: `function`,
stop: `function`,
observe: `function`,
getInterface: `function`
}).of(peerDomain) && peerDomain.type === `domain`)) {
log(`error`, `DomainFactory.register - Input peer domains are invalid.`);
}
}
_peerDomainCache = peerDomains.reduce((__peerDomainCache, peerDomain) => {
if (domain.name === peerDomain.name) {
log(`warn1`, `DomainFactory.register - Cannot register domain:${peerDomain.name} as a peer of itself.`);
} else if (Object.prototype.hasOwnProperty.call(__peerDomainCache, peerDomain.name)) {
log(`warn1`, `DomainFactory.register - Domain:${domain.name} already has peer domain:${peerDomain.name} registered.`);
} else {
__peerDomainCache[peerDomain.name] = peerDomain;
log(`info1`, `Domain:${domain.name} registered peer domain:${peerDomain.name}.`);
}
return __peerDomainCache;
}, _peerDomainCache);
}
return domain;
};
/**
* @description - Start domain.
*
* @method start
* @param {string} targetId
* @param {function} done
* @param {object} option
* @return void
*/
this.start = function (targetId, done, option = {
renderToTarget: true,
slowRunMode: false,
waitTime: DEFAULT_SETUP_WAIT_TIME_IN_MS
}) {
const domain = this;
if (ENV.DEVELOPMENT) {
// if (!domain.isInitialized()) {
// log(`error`, `DomainFactory.start - Domain:${domain.name} start cannot be call before initialization.`);
// }
if (domain.isStreamActivated()) {
log(`error`, `DomainFactory.start - Domain:${domain.name} start cannot be call after event stream activation..`);
}
if (!isNonEmptyString(targetId)) {
log(`error`, `DomainFactory.start - Domain:${domain.name} target Id key is invalid.`);
}
if (!isFunction(done)) {
log(`error`, `DomainFactory.start - Input done function is invalid.`);
}
}
const {
renderToTarget,
slowRunMode,
waitTime,
timeout
} = fallback({
renderToTarget: true,
slowRunMode: false,
waitTime: DEFAULT_SETUP_WAIT_TIME_IN_MS
}).of(option);
const services = Object.values(_serviceCache);
const childDomains = Object.values(_childDomainCache);
const peerDomains = Object.values(_peerDomainCache);
if (!domain.hasStarted()) {
if (ENV.DEVELOPMENT) {
if (!isObject(_intf) && isObject(_store)) {
log(`warn1`, `DomainFactory.start - Domain:${domain.name} has store:${_store.name} resistered without an interface.`);
}
}
const domainTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.start - Domain:${domain.name} is taking longer than ${waitTime}ms to setup.`);
if (isFunction(timeout)) {
timeout(domain.name);
}
}, waitTime);
log(`info1`, `Starting domain:${domain.name}...`);
/* setup event stream observation duplex between domain and servies and children of services */
if (isNonEmptyArray(services)) {
// TODO: why the 1ms delay is needed here?
domain.observe(...services).delay(1);
services.forEach((service) => service.observe(domain));
}
/* setup event stream with domain observing interface */
if (isObject(_intf)) {
domain.observe(_intf);
}
/* setup event stream observation duplex between domain and store */
if (isObject(_store)) {
domain.observe(_store);
_store.observe(domain);
/* setup event stream with interface observing store */
if (isObject(_intf)) {
_intf.observe(_store);
}
}
/* setup event stream observation duplex between domain and children */
if (isNonEmptyArray(childDomains)) {
domain.observe(...childDomains);
childDomains.forEach((childDomain) => childDomain.observe(domain));
}
/* setup event stream observation duplex between domain and peers */
if (isNonEmptyArray(peerDomains)) {
let index = 0;
while (index < peerDomains.length - 1) {
peerDomains[index].observe(...peerDomains.slice(index + 1));
peerDomains.slice(index + 1).forEach((peerDomain) => peerDomain.observe(peerDomains[index])); // eslint-disable-line
index++;
}
domain.observe(...peerDomains);
peerDomains.forEach((peerDomain) => peerDomain.observe(domain));
}
domain.setup(() => {
/* first activate parent domain incoming stream */
domain.activateIncomingStream({
forceBufferingOnAllIncomingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
/* then startup child domains... */
if (isNonEmptyArray(childDomains)) {
childDomains.forEach((childDomain) => {
const childDomainTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.start - Child domain:${childDomain.name} is taking longer than ${waitTime}ms to start.`);
if (isFunction(timeout)) {
timeout(childDomain.name);
}
}, waitTime);
childDomain.start(targetId, () => clearTimeout(childDomainTimeoutId), {
...option,
renderToTarget: false
});
});
}
/* then startup peer domains... */
if (isNonEmptyArray(peerDomains)) {
peerDomains.forEach((peerDomain) => {
const peerDomainTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.start - Peer domain:${peerDomain.name} is taking longer than ${waitTime}ms to start.`);
if (isFunction(timeout)) {
timeout(peerDomain.name);
}
}, waitTime);
peerDomain.start(targetId, () => clearTimeout(peerDomainTimeoutId), {
...option,
renderToTarget: false
});
});
}
/* then activate services... */
if (isNonEmptyArray(services)) {
services.forEach((service) => {
const serviceTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.start - Service:${service.name} is taking longer than ${waitTime}ms to setup.`);
if (isFunction(timeout)) {
timeout(service.name);
}
}, waitTime);
service.setup(() => {
service.activateIncomingStream({
forceBufferingOnAllIncomingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
service.activateOutgoingStream({
bufferOutgoingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
log(`info1`, `Activated service:${service.name}.`);
clearTimeout(serviceTimeoutId);
});
});
}
/* then activate parent to child interfaces... */
if (isObject(_intf)) {
const intfTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.start - Interface:${_intf.name} is taking longer than ${waitTime}ms to setup.`);
if (isFunction(timeout)) {
timeout(_intf.name);
}
}, waitTime);
_intf.setup(() => {
_intf.activateIncomingStream({
forceBufferingOnAllIncomingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
_intf.activateOutgoingStream({
bufferOutgoingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
log(`info1`, `Activated interface:${_intf.name}.`);
clearTimeout(intfTimeoutId);
});
} else {
log(`warn0`, `DomainFactory.start - Domain:${domain.name} is not registered with an interface.`);
}
/* then activate store... */
if (isObject(_store)) {
const storeTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.start - Store:${_store.name} is taking longer than ${waitTime}ms to setup.`);
if (isFunction(timeout)) {
timeout(_store.name);
}
}, waitTime);
_store.setup(() => {
_store.activateIncomingStream({
forceBufferingOnAllIncomingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
_store.activateOutgoingStream({
bufferOutgoingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
log(`info1`, `Activated store:${_store.name}.`);
clearTimeout(storeTimeoutId);
});
}
/* then finally activate domain... */
domain.activateOutgoingStream({
bufferOutgoingStreams: slowRunMode,
bufferTimeSpan: SLOW_MODE_BUFFER_TIME_SPAN_IN_MS,
bufferTimeShift: SLOW_MODE_BUFFER_TIME_SHIFT_IN_MS
});
_started = true;
log(`info1`, `Domain:${domain.name} has started.`);
clearTimeout(domainTimeoutId);
done();
if (renderToTarget && isObject(_intf)) {
_intf.renderToTarget(targetId, option);
}
});
} else {
domain.restart(done, option);
}
};
/**
* @description - Stop domain.
*
* @method stop
* @param {function} done
* @param {object} option
* @return void
*/
this.stop = function (done, option = {
resetStore: true,
resetServices: true,
waitTime: DEFAULT_TEARDOWN_WAIT_TIME_IN_MS
}) {
const domain = this;
if (ENV.DEVELOPMENT) {
// if (!domain.isInitialized()) {
// log(`error`, `DomainFactory.stop - Domain:${domain.name} stop cannot be call before initialization.`);
// }
if (!domain.isStreamActivated()) {
log(`error`, `DomainFactory.stop - Domain:${domain.name} stop cannot be call before event stream activation..`);
}
if (!isFunction(done)) {
log(`error`, `DomainFactory.stop - DomainFactory.stop - Input done function is invalid.`);
}
}
const {
resetStore,
resetServices,
waitTime,
timeout
} = fallback({
resetStore: true,
resetServices: true,
waitTime: DEFAULT_TEARDOWN_WAIT_TIME_IN_MS
}).of(option);
const services = Object.values(_serviceCache);
const childDomains = Object.values(_childDomainCache);
const peerDomains = Object.values(_peerDomainCache);
if (domain.hasStarted()) {
const domainTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.stop - Domain:${domain.name} is taking longer than ${waitTime}ms to teardown.`);
if (isFunction(timeout)) {
timeout(domain.name);
}
}, waitTime);
log(`info1`, `Stopping domain:${domain.name}...`);
domain.teardown(() => {
/* first stop child domains... */
if (isNonEmptyArray(childDomains)) {
childDomains.forEach((childDomain) => {
const childDomainTimeoutId = setTimeout(() => {
log(`warn1`, `Child domain:${childDomain.name} is taking longer than ${waitTime}ms to stop.`);
if (isFunction(timeout)) {
timeout(childDomain.name);
}
}, waitTime);
childDomain.stop(() => clearTimeout(childDomainTimeoutId), option);
});
}
/* then peer domains... */
if (isNonEmptyArray(peerDomains)) {
peerDomains.forEach((peerDomain) => {
const peerDomainTimeoutId = setTimeout(() => {
log(`warn1`, `Peer domain:${peerDomain.name} is taking longer than ${waitTime}ms to stop.`);
if (isFunction(timeout)) {
timeout(peerDomain.name);
}
}, waitTime);
peerDomain.stop(() => clearTimeout(peerDomainTimeoutId), option);
});
}
/* then stop child to parent interfaces... */
if (isObject(_intf)) {
const intfTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.stop - Interface:${_intf.name} is taking longer than ${waitTime}ms to teardown.`);
if (isFunction(timeout)) {
timeout(_intf.name);
}
}, waitTime);
_intf.teardown(() => {
_intf.deactivateIncomingStream();
_intf.deactivateOutgoingStream();
log(`info1`, `Deactivated interface:${_intf.name}.`);
clearTimeout(intfTimeoutId);
});
}
/* then store... */
if (isObject(_store)) {
const storeTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.stop - Store:${_store.name} is taking longer than ${waitTime}ms to teardown.`);
if (isFunction(timeout)) {
timeout(_store.name);
}
}, waitTime);
_store.teardown(() => {
_store.deactivateIncomingStream();
_store.deactivateOutgoingStream();
if (resetStore && isFunction(_store.reset)) {
/* reset store state */
_store.reset();
}
log(`info1`, `Deactivated store:${_store.name}.`);
clearTimeout(storeTimeoutId);
});
}
/* then services... */
if (isNonEmptyArray(services)) {
services.forEach((service) => {
const serviceTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.stop - Service:${service.name} is taking longer than ${waitTime}ms to teardown.`);
if (isFunction(timeout)) {
timeout(service.name);
}
}, waitTime);
service.teardown(() => {
service.deactivateIncomingStream();
service.deactivateOutgoingStream();
if (resetServices && isFunction(service.reset)) {
/* reset service state */
service.reset();
}
log(`info1`, `Deactivated service:${service.name}.`);
clearTimeout(serviceTimeoutId);
});
});
}
/* then finally parent domain. */
domain.deactivateIncomingStream();
domain.deactivateOutgoingStream();
_started = false;
log(`info1`, `Domain:${domain.name} has stopped.`);
clearTimeout(domainTimeoutId);
done();
});
}
};
/**
* @description - Restart domain.
*
* @method restart
* @param {string} targetId
* @param {function} done,
* @param {object} option,
* @return void
*/
this.restart = function (targetId, done, option = {
waitTime: DEFAULT_SETUP_WAIT_TIME_IN_MS
}) {
const domain = this;
const {
waitTime,
timeout
} = fallback({
waitTime: DEFAULT_SETUP_WAIT_TIME_IN_MS
}).of(option);
if (ENV.DEVELOPMENT) {
if (!isFunction(done)) {
log(`error`, `DomainFactory.restart - Input done function is invalid.`);
}
}
const domainTimeoutId = setTimeout(() => {
log(`warn1`, `DomainFactory.restart - Domain:${domain.name} is taking longer than ${waitTime} seconds to stop and restart.`);
if (isFunction(timeout)) {
timeout(domain.name);
}
}, waitTime);
domain.stop(() => {
clearTimeout(domainTimeoutId);
domain.start(targetId, done, option);
}, option);
};
}
});
|
'use strict';
var extend = require('xtend/mutable')
, descriptors = require('./lib/descriptors');
module.exports = extend(cobble, descriptors)
/**
* compose objects into a new object, leaving the original objects untouched
* @param {...object} an object to be composed.
* @return {object}
*/
function cobble(){
var args = [], last;
for(var i = 0; i < arguments.length; ++i) {
last = arguments[i];
if( isArray(last) ) args = args.concat(last)
else args[args.length] = last
}
return cobble.into({}, args)
}
/**
* compose arguments into the first arg, mutating it
* @param {object} target object; is mutated.
* @param {...objects} object to merge into the target object
* @return {object}
*/
cobble.into = function into() {
var args = []
, propHash = {}
, target, last;
for(var i = 0; i < arguments.length; ++i) {
last = arguments[i];
if( isArray(last) ) args = args.concat(last)
else args[args.length] = last
}
if(args.length === 1)
return args[0]
target = args.shift()
for( i = 0; i < args.length; i++)
for(var key in args[i]) {
var value = args[i][key]
, inTarget = key in target
, isRequired = descriptors.isRequired(value);
if ( !isRequired && inTarget && ( !propHash.hasOwnProperty(key) || propHash[key].indexOf(target[key]) === -1 ))
add(propHash, key, target[key])
defineKey(value, key, target, propHash)
}
return target
}
cobble.assert = function (obj){
var required = []
for (var k in obj)
if( obj.hasOwnProperty(k) && descriptors.isRequired(obj[k]))
required.push(k)
if( required.length !== 0 ){
var err = new TypeError("Unmet required properties: " + required.join(', '))
err.required = required
throw err
}
}
/**
* adds a property to the src object or expands the value if it is a decorator
* @param {*} value
* @param {string} key
* @param {object} src
*/
function defineKey(value, key, src, propHash){
var isDescriptor = descriptors.isDescriptor(value)
, isRequired = descriptors.isRequired(value)
, prev;
if (isRequired && (key in src)) return
if ( !isRequired ) {
if ( isDescriptor) {
prev = (propHash.hasOwnProperty(key) ? propHash[key] : []).splice(0)
return defineKey(value.resolve.call(src, key, prev), key, src, propHash)
}
else
add(propHash, key, value)
}
src[key] = value
}
function add(obj, key, value) {
obj[key] = obj.hasOwnProperty(key) ? obj[key] : []
obj[key].push(value)
}
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
} |
/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, strict:true, trailing:true, white:true */
/*global X:true, XM:true */
(function () {
"use strict";
var _fs = X.fs, _path = X.path;
/**
Defines the authentication route.
@extends X.Route
@class
*/
X.oauth2tokenRoute = X.Route.create({
handle: function (xtr) {
var data = xtr.get("payload"),
options = {},
message = "OAuth 2.0 Token endpoint",
that = this;
//X.debugging = true;
//X.debug(data);
// Server to Server Grant:
// This extended grant type comes from Google:
// https://developers.google.com/accounts/docs/OAuth2ServiceAccount
// This grant type is used by xTuple's Drupal sites to gain access to the REST API.
// This grant type also allows for delegated access where Drupal can request resources
// as a specific user. This enforces that user's permissions when performaing any CRUD.
// 1. Admin user registers the client server (Drupal) as an xTuple OAuth "Service Account".
// 2. A private key and client_id are returned to the Admin user.
// 3. The Admin user save the private key and client_id where Drupal can access it.
// 4. Application code on Drupal creates a JWT and signs it with the private key.
// 5. Application code on Drupal submits the JWT as an access token request to the auth server.
// 6. If the JWT is valid, auth server responds with a Access Token.
// 7. Drupal uses the Access Token for all further requests.
// 8. When the access token expires, application code on Drupal repeats step 4 - 7.
options.success = function () {
xtr.write(session.get("details")).close();
};
options.error = function (err) {
xtr.error({isError: true, reason: message});
};
//options.id = data.id;
options.username = X.options.globalDatabase.nodeUsername;
//user.fetch(options);
xtr.write(message).close();
},
handles: "/oauth2/token".w(),
needsSession: false
});
}());
|
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
routes = require('./routes/index'),
app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s, env', host, port, app.get('env'));
});
module.exports = app;
|
/*global BigBlock, document */
/**
RenderManager object
Renders pixels to the grid.
@author Vince Allen 12-05-2009
Big Block Framework
Copyright (C) 2011 Foldi, LLC
*/
BigBlock.RenderMgr = (function () {
return {
last_rendered_div: null,
grid_static_fragment: null,
grid_text_fragment: null,
render_rate_test_array : [],
renderBlocks : function (blocksToRender) {
var i, i_max, start, div_id, obj, blk, y, y_max;
if (BigBlock.Timer.debug_frame_rate) {
start = new Date().getTime();
}
// BLOCKS LOOP
this.grid_static_fragment = document.createDocumentFragment();
this.grid_text_fragment = document.createDocumentFragment();
// loop thru all existing non-text objects
div_id = 0;
for (i = 0, i_max = blocksToRender.length; i < i_max; i += 1) {
obj = blocksToRender[i];
if (obj.img === false) { // if BlockSmall;
if (obj.pix_index !== false) { // if BlockSmall is on screen
if (obj.render_static) {
switch (obj.className) {
case 'Character':
this.renderChar(div_id, obj, obj.color_index, 0);
break;
default:
this.renderStaticBlock(obj, obj.color_index, 0);
break;
}
} else {
this.renderActiveBlock(div_id, obj, obj.color_index, 0);
div_id += 1; // increment the div_id
}
}
} else { // BlockAnim or BlockBig
for (y = 0, y_max = obj.img.pix.length; y < y_max; y += 1) { // loop thru blocks attached to this Object
blk = obj.img.pix[y];
if (obj.render_static) {
this.renderStaticBlock(obj, blk.c, blk.i);
} else {
this.renderActiveBlock(div_id, obj, blk.c, blk.i);
div_id += 1; // increment the div_id
}
}
}
if (obj.render_static && typeof obj.img !== "undefined") { // if this is a static object and the object has its img property
obj.render_static = false; // MUST set the static property = 0; static Blocks will not be deleted
obj.destroy(); // destroy the Block
}
}
document.getElementById(BigBlock.GridStatic.viewport.id).appendChild(this.grid_static_fragment); // append the static block to the Static Grid
document.getElementById(BigBlock.GridText.viewport.id).appendChild(this.grid_text_fragment); // add character to dom
this.last_rendered_div = BigBlock.GridActive.viewport.last_el; // store the last rendered id; will use for cleanup
BigBlock.GridActive.viewport.last_el = false; // reset viewport's last element
// reset the remaining live divs
if (this.last_rendered_div) {
while (this.last_rendered_div.nextSibling !== null) { // while the last rendered div has a sibling
i = this.last_rendered_div.nextSibling; // get the sibling
this.setBlockAttribute(i, "class", "pix color i0"); // reset its class
this.last_rendered_div = i; // set this.last_rendered_div equal to the div we just reset; this.last_rendered_div should eventually run out of siblings
}
}
},
renderActiveBlock: function (id, obj, color, offset) {
var x, y, index, d;
if ((obj.img !== false && obj.is_position_updated) !== false || obj.is_anim_updated !== false) { // only Block Anim should call getPixLoc
x = BigBlock.Utils.getPixLoc('x', obj.x, offset); // get global x, y coords based on parent Block's coords
y = BigBlock.Utils.getPixLoc('y', obj.y, offset);
index = BigBlock.Utils.getPixIndex(x, y);
} else {
x = obj.x;
y = obj.y;
index = obj.pix_index;
}
if (BigBlock.Utils.ptInsideRect(x, y, 0, BigBlock.Grid.width, 0, BigBlock.Grid.height)) { // check that block is on screen
if (obj.is_position_updated || obj.is_anim_updated || obj.is_color_updated) { // always redrawing active blocks even if they do not move or change color; uncomment to check for is_ properties
if (BigBlock.GridActive.viewport.last_el) {
d = BigBlock.GridActive.viewport.last_el.nextSibling;
} else {
d = BigBlock.GridActive.viewport.dom_ref.firstChild;
}
BigBlock.GridActive.viewport.last_el = d;
this.setBlockAttribute(d, 'class', 'pix ' + BigBlock.CSSid_color + color + ' ' + BigBlock.CSSid_position + index);
}
} else {
return false;
}
},
renderStaticBlock: function (obj, color, offset) {
var x, y, index, child;
x = BigBlock.Utils.getPixLoc('x', obj.x, offset); // get global x, y coords based on parent Block's coords
y = BigBlock.Utils.getPixLoc('y', obj.y, offset);
if (BigBlock.Utils.ptInsideRect(x, y, 0, BigBlock.Grid.width, 0, BigBlock.Grid.height)) { // check that block is on screen
index = BigBlock.Utils.getPixIndex(x, y);
child = BigBlock.GridStatic.div.cloneNode(false); // dom method; clone a div element
this.setBlockAttribute(child, 'id', '_static'); // all static blocks have the same id
this.setBlockAttribute(child, 'name', obj.alias); // set the block name to alias of the object; used to remove static blocks
this.setBlockAttribute(child, 'class', 'pix ' + BigBlock.CSSid_color + color + ' ' + BigBlock.CSSid_position + index);
this.grid_static_fragment.appendChild(child); // append the static block to the Static Grid doc fragment
} else {
return false;
}
},
renderChar: function (id, obj, color, offset) {
var x, y, index, child, char_pos, k, k_max, char_div, gl_limit;
x = BigBlock.Utils.getPixLoc('x', obj.x, offset); // get global x, y coords based on parent Block's coords
y = BigBlock.Utils.getPixLoc('y', obj.y, offset);
if (BigBlock.Utils.ptInsideRect(x, y, 0, BigBlock.Grid.width, 0, BigBlock.Grid.height) && y < BigBlock.GridStatic.height) { // check that block is on screen
index = BigBlock.Utils.getPixIndex(x, y);
child = BigBlock.GridText.div.cloneNode(false); // dom method; clone a div element
//this.setBlockAttribute(child, 'id', BigBlock.Utils.getUniqueId()); // uncomment to give each text div a unique id
this.setBlockAttribute(child, 'name', obj.word_id);
this.setBlockAttribute(child, 'class', 'pix ' + BigBlock.CSSid_text_bg + ' ' + BigBlock.CSSid_position + index);
char_pos = obj.char_pos; // get positions of all divs in the character
for (k = 0, k_max = char_pos.length; k < k_max; k += 1) {
char_div = BigBlock.GridText.div.cloneNode(false); // dom method; create a div for each block in the letter
gl_limit = BigBlock.Grid.blk_dim * 4; // check for glass
if (char_pos[k].p < gl_limit && obj.glass === true) {
this.setBlockAttribute(char_div, 'class', BigBlock.CSSid_char + ' ' + BigBlock.CSSid_char_pos + char_pos[k].p + ' ' + BigBlock.CSSid_color + color + '_glass0');
} else {
this.setBlockAttribute(char_div, 'class', BigBlock.CSSid_char + ' ' + BigBlock.CSSid_char_pos + char_pos[k].p + ' ' + BigBlock.CSSid_color + color);
}
child.appendChild(char_div); // add the character div to the Block's div
}
this.grid_text_fragment.appendChild(child); // add character to text doc fragment
}
},
setBlockAttribute: function (obj, key, val) {
if (typeof obj !== "object" || obj === null) {
return false;
} else {
obj.setAttribute(key, val);
if (typeof document.addEventListener !== "function" && key === "class") { // test for IE
obj.setAttribute("className", val); // IE
obj.innerHTML = "."; // IE6
}
}
},
/**
* clearScene() will clear all divs from all viewports, empty the Blocks array, and empty the Button.map property
*
* @param {Function} beforeClear
* @param {Function} afterClear
*/
clearScene: function(before, after) {
BigBlock.inputBlock = true; // block user input when clearing scene
try {
if (typeof before !== "undefined" && before !== null) {
if (typeof before !== "function") {
throw new Error("BigBlock.RenderMgr.clearScene(beforeClear, afterClear): beforeClear must be a function");
} else {
before();
}
}
} catch(e) {
BigBlock.Log.display(e.name + ": " + e.message);
}
if (typeof BigBlock.GridStatic !== "undefined") {
document.getElementById(BigBlock.GridStatic.viewport.id).innerHTML = "";
BigBlock.GridStatic.setStyle("backgroundColor", "transparent");
}
if (typeof BigBlock.GridText !== "undefined") {
document.getElementById(BigBlock.GridText.viewport.id).innerHTML = "";
BigBlock.GridText.setStyle("backgroundColor", "transparent");
}
// never remove divs from GridActive
if (typeof BigBlock.Blocks !== "undefined") { // clear Block array
BigBlock.Blocks = {};
}
if (typeof BigBlock.BlocksKeys !== "undefined") { // clear Block Keys array
BigBlock.BlocksKeys = [];
}
if (typeof BigBlock.Button.map !== "undefined") { // clear Button.map array
BigBlock.Button.map = [];
}
try {
if (typeof after !== "undefined" && after !== null) {
if (typeof after !== "function") {
throw new Error("BigBlock.RenderMgr.clearScene(beforeClear, afterClear): afterClear must be a function.");
} else {
after();
}
}
} catch(er) {
BigBlock.Log.display(er.name + ": " + er.message);
}
//
BigBlock.inputBlock = false; // release user input block
}
};
}()); |
/*
Header
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Components, registerComponent, withCurrentUser, getSetting } from 'meteor/vulcan:core';
import { Link } from 'react-router';
import Button from 'react-bootstrap/lib/Button';
import { FormattedMessage } from 'meteor/vulcan:i18n';
// import UsersMenu from '../users/UsersMenu';
// import UsersAccountMenu from '../users/UsersAccountMenu';
const Header = ({ currentUser }, context) =>
<header className="header">
<div className="brand">
<div className="logo"><Link to="/"><h1>{getSetting('title')}</h1></Link></div>
<div className="tagline">{getSetting('tagline')}</div>
</div>
<div className="nav">
<Link className="nav-item" to="/how-to"><FormattedMessage id="nav.how_to"/></Link>
<Link className="nav-item" to="/about"><FormattedMessage id="nav.about"/></Link>
<div className="nav-item nav-user">
{currentUser ? <Components.UsersMenu/> : <Components.UsersAccountMenu/>}
</div>
</div>
</header>
Header.displayName = 'Header';
Header.propTypes = {
currentUser: PropTypes.object,
};
registerComponent('Header', Header, withCurrentUser);
// export default withCurrentUser(Header);
|
/*****************************************************************************/
/* Stats: Event Handlers */
/*****************************************************************************/
Template.Stats.events({
});
/*****************************************************************************/
/* Stats: Helpers */
/*****************************************************************************/
Template.Stats.helpers({
roles: function () {
return Roles.getAllRoles();
},
countRole: function () {
return Tasks.find({skill: this.name}).count();
}
});
/*****************************************************************************/
/* Stats: Lifecycle Hooks */
/*****************************************************************************/
Template.Stats.created = function () {
};
Template.Stats.rendered = function () {
};
Template.Stats.destroyed = function () {
};
|
module.exports = function ( grunt ) {
'use strict';
grunt.registerTask( 'test', [
'nodeunit',
'qunit:all'
]);
};
|
'use strict';
var test = require('../');
test.beforeEach(function (t) {
t.context.test = 'test';
});
test(function (t) {
t.is(true, true);
});
test('is compatible with ava', function (t) {
t.is(true, true);
});
test('is compatible with ava context', function (t) {
t.true(t.context.test === 'test');
});
test.describe('describe', function (test) {
test('can be used to nest tests', function (t) {
t.is(true, true);
});
});
test.skip.describe('describe', function (test) {
test('can skip multiple tests', function (t) {
t.is(true, false);
});
test('can skip multiple tests', function () {
throw new Error('hello world');
});
});
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Owner: felix@famo.us
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
define('famous/views/SequentialLayout', ["famous/core/OptionsManager","famous/core/Transform","famous/core/ViewSequence","famous/utilities/Utility"], function(require, exports, module) {
var OptionsManager = require('famous/core/OptionsManager');
var Transform = require('famous/core/Transform');
var ViewSequence = require('famous/core/ViewSequence');
var Utility = require('famous/utilities/Utility');
/**
* SequentialLayout will lay out a collection of renderables sequentially in the specified direction.
* @class SequentialLayout
* @constructor
* @param {Options} [options] An object of configurable options.
* @param {Number} [options.direction=Utility.Direction.Y] Using the direction helper found in the famous Utility
* module, this option will lay out the SequentialLayout instance's renderables either horizontally
* (x) or vertically (y). Utility's direction is essentially either zero (X) or one (Y), so feel free
* to just use integers as well.
* @param {Array.Number} [options.defaultItemSize=[50, 50]] In the case where a renderable layed out
* under SequentialLayout's control doesen't have a getSize method, SequentialLayout will assign it
* this default size. (Commonly a case with Views).
*/
function SequentialLayout(options) {
this._items = null;
this._size = null;
this._outputFunction = SequentialLayout.DEFAULT_OUTPUT_FUNCTION;
this.options = Object.create(this.constructor.DEFAULT_OPTIONS);
this.optionsManager = new OptionsManager(this.options);
this._itemsCache = [];
this._outputCache = {
size: null,
target: this._itemsCache
};
if (options) this.setOptions(options);
}
SequentialLayout.DEFAULT_OPTIONS = {
direction: Utility.Direction.Y,
itemSpacing: 0,
defaultItemSize: [50, 50]
};
SequentialLayout.DEFAULT_OUTPUT_FUNCTION = function DEFAULT_OUTPUT_FUNCTION(input, offset, index) {
var transform = (this.options.direction === Utility.Direction.X) ? Transform.translate(offset, 0) : Transform.translate(0, offset);
return {
transform: transform,
target: input.render()
};
};
/**
* Returns the width and the height of the SequentialLayout instance.
*
* @method getSize
* @return {Array} A two value array of the SequentialLayout instance's current width and height (in that order).
*/
SequentialLayout.prototype.getSize = function getSize() {
if (!this._size) this.render(); // hack size in
return this._size;
};
/**
* Sets the collection of renderables under the SequentialLayout instance's control.
*
* @method sequenceFrom
* @param {Array|ViewSequence} items Either an array of renderables or a Famous viewSequence.
* @chainable
*/
SequentialLayout.prototype.sequenceFrom = function sequenceFrom(items) {
if (items instanceof Array) items = new ViewSequence(items);
this._items = items;
return this;
};
/**
* Patches the SequentialLayout instance's options with the passed-in ones.
*
* @method setOptions
* @param {Options} options An object of configurable options for the SequentialLayout instance.
* @chainable
*/
SequentialLayout.prototype.setOptions = function setOptions(options) {
this.optionsManager.setOptions.apply(this.optionsManager, arguments);
return this;
};
/**
* setOutputFunction is used to apply a user-defined output transform on each processed renderable.
* For a good example, check out SequentialLayout's own DEFAULT_OUTPUT_FUNCTION in the code.
*
* @method setOutputFunction
* @param {Function} outputFunction An output processer for each renderable in the SequentialLayout
* instance.
* @chainable
*/
SequentialLayout.prototype.setOutputFunction = function setOutputFunction(outputFunction) {
this._outputFunction = outputFunction;
return this;
};
/**
* Generate a render spec from the contents of this component.
*
* @private
* @method render
* @return {number} Render spec for this component
*/
SequentialLayout.prototype.render = function render() {
var length = 0;
var girth = 0;
var lengthDim = (this.options.direction === Utility.Direction.X) ? 0 : 1;
var girthDim = (this.options.direction === Utility.Direction.X) ? 1 : 0;
var currentNode = this._items;
var result = this._itemsCache;
var i = 0;
while (currentNode) {
var item = currentNode.get();
if (!item) break;
var itemSize;
if (item && item.getSize) itemSize = item.getSize();
if (!itemSize) itemSize = this.options.defaultItemSize;
if (itemSize[girthDim] !== true) girth = Math.max(girth, itemSize[girthDim]);
var output = this._outputFunction.call(this, item, length, i);
result[i] = output;
if (itemSize[lengthDim] && (itemSize[lengthDim] !== true)) length += itemSize[lengthDim] + this.options.itemSpacing;
currentNode = currentNode.getNext();
i++;
}
this._itemsCache.splice(i);
if (!girth) girth = undefined;
if (!this._size) this._size = [0, 0];
this._size[lengthDim] = length - this.options.itemSpacing; // account for last itemSpacing
this._size[girthDim] = girth;
this._outputCache.size = this.getSize();
return this._outputCache;
};
module.exports = SequentialLayout;
});
|
var request = require('request');
request.get({url: 'http://tms.aidaojia.com'},function (err, res, body) {
console.log(res);
})
|
module.exports = function (config) {
'use strict';
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'src/es5-polyfill.js',
'src/tennis.js',
'src/tennis.specs.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['spec'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.