code stringlengths 2 1.05M |
|---|
const offset = {};
// mouse position inside btn
let dragging = false;
const btn = '';
// font btn
btn.addEventListener('mousedown', (e) => {
dragging = true;
({ clientX: offset.x, clientY: offset.y } = e);
}, true);
self.addEventListener('mousemove', (e) => {
e.preventDefault();
if (dragging) {
btn.style.left = `${e.clientX + offset.x}px`;
btn.style.top = `${e.clientY + offset.y}px`;
}
});
self.addEventListener('mouseup', () => {
dragging = false;
const node = Array.from(document.querySelectorAll(":hover")).pop();
const selector = [
node.tagName,
node.id ? `#${node.id}` : ``,
node.className ? `.${node.className}` : ``,
].join('');
// TODO: options to select this element or it's parent(s)
Array.from(document.querySelectorAll(selector)).forEach((e) => {
const prevOutline = e.style.outline;
e.style.outline = `1px solid blue`;
e.style.outline = prevOutline;
});
// Array.from(document.querySelectorAll(":hover")).slice(-1); /* or deeper -2,-3,etc */
});
// Classes
class Baka {
constructor(x) {
this.x = x;
}
yandere() { return self.console.log(`${this.x} is dead.`); }
static scream(name = 'John') { return self.console.log(`${name}, you are B-BAKA!!!`); }
}
Baka.scream('Rito');
Baka.scream();
const foo = new Baka('Kirito');
foo.yandere();
// or
{
class baka {
constructor(x) {
this.x = x;
this.yan = () => { self.console.log(`${this.x}!!! `.repeat(10)); };
}
yandere() {
return (() => {
this.yan();
baka.scream(this.x);
self.console.log(`...${this.x} is dead. He got himself a yandere in the harem.`);
})();
}
static scream(name = 'Kirito') {
return self.console.log(`${name}, you are B-BAKA!!!`);
}
}
const foo = new baka(`Rito`);
foo.yandere();
baka.scream();
baka.scream('Onii-sama');
}
|
export default {
// 90deg
1: '[originX + originY - y, -originX + originY + x]',
// 180deg
2: '[(2 * originX) - x, (2 * originY) - y]',
// 270deg
3: '[originX - originY + y, originX + originY - x]'
};
|
let Promise = require('bluebird');
let { log, error } = require('../logger');
let request;
function addons(app, desiredAddons) {
let existingAddons;
// fetch existing app addons
return request.get(`/apps/${app.name}/addons`)
// filter existing addons for those which aren't in the new schema
.then((response) => {
existingAddons = response;
let toRemove = existingAddons
.filter((addon) => !desiredAddons[addon.name])
.map((addon) => addon.name);
return Promise.resolve(toRemove);
})
// remove addons not present in the new app schema
.then((toRemove) => {
if (!toRemove.length) {
return Promise.resolve();
}
return Promise.all(toRemove.map((addon) => {
return request.delete(`/apps/${app.name}/addons/${addon}`)
}));
})
// check if existing addons need a plan change
.then(() => {
let toUpdate = existingAddons
.filter((addon) => {
if (!desiredAddons[addon.name]) {
return false;
}
return addon.plan.name !== desiredAddons[addon.name];
})
.map((addon) => addon.name);
return Promise.resolve(toUpdate);
})
// Update addon plans
.then((toUpdate) => {
if (!toUpdate.length) {
return Promise.resolve();
}
return Promise.all(toUpdate.map((addon) => {
return request.patch(`/apps/${app.name}/addons/${addon}`, {
plan: desiredAddons[name].plan
});
}));
})
// filter out the new addons to create
.then(() => {
let toCreate = Object.keys(desiredAddons)
.filter((name) => !existingAddons[name])
.map((name) => `${name}:${desiredAddons[name]}`);
return Promise.resolve(toCreate);
})
// Create new addons
.then((toCreate) => {
if (!toCreate.length) {
return Promise.resolve();
}
return Promise.all(toCreate.map((addon) => {
return request.post(`/apps/${app.name}/addons`, {
body: {
plan: addon
}
});
}));
})
.then(() => {
log(`Updated addons and plans`);
return Promise.resolve(app);
})
.catch((err) => {
error(`Error: ${err}`);
process.exit(1);
});
}
module.exports = function(req) {
request = req;
return addons;
};
|
'use strict';
/**
* Custom `@colors` annotation. Accepts optional
* map-variable name (used to access data from Sass JSON).
*/
module.exports = () => ({
name: 'colors',
multiple: false,
parse: (raw) => ({ key: raw.trim() }),
});
|
'use strict';
import 'prismjs';
import Vue from 'vue';
import VueSimpleValidator from '../src';
import App from './vue/App.vue';
import LeftNavBar from './vue/LeftNavBar.vue';
import MainContent from './vue/MainContent.vue';
import DemoWithCode from './vue/DemoWithCode.vue';
import GettingStarted from './vue/chapters/GettingStarted.vue';
import UsagesAndExamples from './vue/chapters/UsagesAndExamples.vue';
import Miscellaneous from './vue/chapters/Miscellaneous.vue';
import APIAndReference from './vue/chapters/APIAndReference.vue';
import BasicExample from './vue/examples/BasicExample.vue';
import BuiltinRulesExample from './vue/examples/BuiltinRulesExample.vue';
import CustomRuleExample from './vue/examples/CustomRuleExample.vue';
import CrossFieldValidationExample1 from './vue/examples/CrossFieldValidationExample1.vue';
import CrossFieldValidationExample2 from './vue/examples/CrossFieldValidationExample2.vue';
import AsyncValidationExample1 from './vue/examples/AsyncValidationExample1.vue';
import AsyncValidationExample2 from './vue/examples/AsyncValidationExample2.vue';
import CheckboxGroup from './vue/examples/CheckboxGroup.vue';
import CustomComponentExample from './vue/examples/CustomComponentExample.vue';
import DynamicForm from './vue/examples/DynamicForm.vue';
import DynamicFormExample from './vue/examples/DynamicFormExample.vue';
import LocalizationExample from './vue/examples/LocalizationExample.vue';
import ComponentBasedMessageExample from './vue/examples/ComponentBasedMessageExample.vue';
import FieldBasedMessageExample from './vue/examples/FieldBasedMessageExample.vue';
Vue.use(VueSimpleValidator);
Vue.component('LeftNavBar', LeftNavBar);
Vue.component('MainContent', MainContent);
Vue.component('DemoWithCode', DemoWithCode);
// chapters
Vue.component('GettingStarted', GettingStarted);
Vue.component('UsagesAndExamples', UsagesAndExamples);
Vue.component('Miscellaneous', Miscellaneous);
Vue.component('APIAndReference', APIAndReference);
// examples
Vue.component('BasicExample', BasicExample);
Vue.component('BuiltinRulesExample', BuiltinRulesExample);
Vue.component('CustomRuleExample', CustomRuleExample);
Vue.component('CrossFieldValidationExample1', CrossFieldValidationExample1);
Vue.component('CrossFieldValidationExample2', CrossFieldValidationExample2);
Vue.component('AsyncValidationExample1', AsyncValidationExample1);
Vue.component('AsyncValidationExample2', AsyncValidationExample2);
Vue.component('CheckboxGroup', CheckboxGroup);
Vue.component('CustomComponentExample', CustomComponentExample);
Vue.component('DynamicForm', DynamicForm);
Vue.component('DynamicFormExample', DynamicFormExample);
Vue.component('LocalizationExample', LocalizationExample);
Vue.component('ComponentBasedMessageExample', ComponentBasedMessageExample);
Vue.component('FieldBasedMessageExample', FieldBasedMessageExample);
new Vue({
el: '#app',
render: function (h) {
return h(App);
}
});
|
import {sendGetRequest} from "../../../helpers/RequestHelper";
import {FETCH_COMPANY_REQUESTS_ACTION_PREFIX, FETCH_COMPANY_REQUESTS_URL,} from "../constants";
const PAGING = `&sort=id,DESC&size=999`
const FILTER = "?filter=status:PENDING"
export const fetchCompanyRequests = dispatch => {
dispatch({type: `${FETCH_COMPANY_REQUESTS_ACTION_PREFIX}_request`})
sendGetRequest(`${FETCH_COMPANY_REQUESTS_URL}${FILTER}${PAGING}`)
.then(data => dispatch({
type: `${FETCH_COMPANY_REQUESTS_ACTION_PREFIX}_success`,
response: data
})
)
.catch(errorMsg => dispatch({
type: `${FETCH_COMPANY_REQUESTS_ACTION_PREFIX}_failure`,
error: errorMsg
}))
}
export const fetchCompanyRequestsReducer = (state, action) => {
switch (action.type) {
case `${FETCH_COMPANY_REQUESTS_ACTION_PREFIX}_request`: {
return {
...state,
fetching: true,
error: null,
}
}
case `${FETCH_COMPANY_REQUESTS_ACTION_PREFIX}_success`: {
return {
...state,
fetching: false,
requests: action.response.content,
}
}
case `${FETCH_COMPANY_REQUESTS_ACTION_PREFIX}_failure`: {
return {
...state,
fetching: false,
error: action.error,
}
}
default: {
throw new Error(`Unhandled exception type ${action.type}`)
}
}
} |
const Marionette = require('backbone.marionette');
module.exports = class LocationPickerListView extends Marionette.View {
template = Templates['picker/location-picker-list'];
ui() {
return {room: '.room'};
}
events() {
return {'click @ui.room': 'onRoomClick'};
}
serializeData() {
const currentRoom = this.getOption('current');
return {
rooms: this.getOption('rooms').map(function(room) {
return {
name: room.name,
active: room.active,
selected: room.name === currentRoom
};
})
};
}
onRoomClick(event) {
const room = $(event.target).closest('.room').data('room');
this.trigger('select', room);
}
}
|
"use strict";
exports.__esModule = true;
exports.navigateTo = undefined;
var _extends2 = require("babel-runtime/helpers/extends");
var _extends3 = _interopRequireDefault(_extends2);
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _objectWithoutProperties2 = require("babel-runtime/helpers/objectWithoutProperties");
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
exports.withPrefix = withPrefix;
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _reactRouterDom = require("react-router-dom");
var _propTypes = require("prop-types");
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pathPrefix = "/"; /*global __PREFIX_PATHS__, __PATH_PREFIX__ */
if (typeof __PREFIX_PATHS__ !== "undefined" && __PREFIX_PATHS__) {
pathPrefix = __PATH_PREFIX__;
}
function withPrefix(path) {
return normalizePath(pathPrefix + path);
}
function normalizePath(path) {
return path.replace(/^\/\//g, "/");
}
var NavLinkPropTypes = {
activeClassName: _propTypes2.default.string,
activeStyle: _propTypes2.default.object,
exact: _propTypes2.default.bool,
strict: _propTypes2.default.bool,
isActive: _propTypes2.default.func,
location: _propTypes2.default.object
// Set up IntersectionObserver
};var handleIntersection = function handleIntersection(el, cb) {
var io = new window.IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (el === entry.target) {
// Check if element is within viewport, remove listener, destroy observer, and run link callback.
// MSEdge doesn't currently support isIntersecting, so also test for an intersectionRatio > 0
if (entry.isIntersecting || entry.intersectionRatio > 0) {
io.unobserve(el);
io.disconnect();
cb();
}
}
});
});
// Add element to the observer
io.observe(el);
};
var GatsbyLink = function (_React$Component) {
(0, _inherits3.default)(GatsbyLink, _React$Component);
function GatsbyLink(props) {
(0, _classCallCheck3.default)(this, GatsbyLink);
// Default to no support for IntersectionObserver
var _this = (0, _possibleConstructorReturn3.default)(this, _React$Component.call(this));
var IOSupported = false;
if (typeof window !== "undefined" && window.IntersectionObserver) {
IOSupported = true;
}
_this.state = {
to: withPrefix(props.to),
IOSupported: IOSupported
};
_this.handleRef = _this.handleRef.bind(_this);
return _this;
}
GatsbyLink.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.to !== nextProps.to) {
this.setState({
to: withPrefix(nextProps.to)
});
// Preserve non IO functionality if no support
if (!this.state.IOSupported) {
___loader.enqueue(this.state.to);
}
}
};
GatsbyLink.prototype.componentDidMount = function componentDidMount() {
// Preserve non IO functionality if no support
if (!this.state.IOSupported) {
___loader.enqueue(this.state.to);
}
};
GatsbyLink.prototype.handleRef = function handleRef(ref) {
var _this2 = this;
this.props.innerRef && this.props.innerRef(ref);
if (this.state.IOSupported && ref) {
// If IO supported and element reference found, setup Observer functionality
handleIntersection(ref, function () {
___loader.enqueue(_this2.state.to);
});
}
};
GatsbyLink.prototype.render = function render() {
var _this3 = this;
var _props = this.props,
_onClick = _props.onClick,
rest = (0, _objectWithoutProperties3.default)(_props, ["onClick"]);
var El = void 0;
if ((0, _keys2.default)(NavLinkPropTypes).some(function (propName) {
return _this3.props[propName];
})) {
El = _reactRouterDom.NavLink;
} else {
El = _reactRouterDom.Link;
}
return _react2.default.createElement(El, (0, _extends3.default)({
onClick: function onClick(e) {
// eslint-disable-line
_onClick && _onClick(e);
if (e.button === 0 && // ignore right clicks
!_this3.props.target && // let browser handle "target=_blank"
!e.defaultPrevented && // onClick prevented default
!e.metaKey && // ignore clicks with modifier keys...
!e.altKey && !e.ctrlKey && !e.shiftKey) {
// Is this link pointing to a hash on the same page? If so,
// just scroll there.
var pathname = _this3.state.to;
if (pathname.split("#").length > 1) {
pathname = pathname.split("#").slice(0, -1).join("");
}
if (pathname === window.location.pathname) {
var hashFragment = _this3.state.to.split("#").slice(1).join("#");
var element = document.getElementById(hashFragment);
if (element !== null) {
element.scrollIntoView();
return true;
}
}
// In production, make sure the necessary scripts are
// loaded before continuing.
if (process.env.NODE_ENV === "production") {
e.preventDefault();
window.___navigateTo(_this3.state.to);
}
}
return true;
}
}, rest, {
to: this.state.to,
innerRef: this.handleRef
}));
};
return GatsbyLink;
}(_react2.default.Component);
GatsbyLink.propTypes = (0, _extends3.default)({}, NavLinkPropTypes, {
innerRef: _propTypes2.default.func,
onClick: _propTypes2.default.func,
to: _propTypes2.default.string.isRequired
});
GatsbyLink.contextTypes = {
router: _propTypes2.default.object
};
exports.default = GatsbyLink;
var navigateTo = exports.navigateTo = function navigateTo(pathname) {
window.___navigateTo(withPrefix(pathname));
}; |
'use strict';
describe('RepoFetcherRatings', function(){
beforeEach( function(){
//initialize module under test
module('RepoFetcherRatings');
});
it('sanity check', function(){
expect(true).toBe(true);
});
xdescribe('Repo', function(){
var repo;
var _httpBackend;
beforeEach(inject(function( $injector, $httpBackend, Repo){
repo = Repo;
_httpBackend = $httpBackend;
}));
it('sanity check', function(){
expect(repo).toBeDefined();
});
describe('.initBaseModel', function(){
describe('nominal cases', function(){
var fetchedRepos;
var repos = [
{ ratings:{"stable":5, "useful":4} },
{ ratings:{"stable":5, "useful":4} },
{ ratings:{"stable":5, "useful":4} }
];
beforeEach(function(){
_httpBackend
.when('GET', /api.github.com/)
.respond(repos);
repo.initBaseModel('foo', [])
.then(function(repos){
fetchedRepos = repos;
})
.catch(function(err){
throw(err);
});
});
it('returns collection', function(){
fetchedRepos = null;
_httpBackend.flush();
expect(fetchedRepos.length).toEqual(3);
});
it('each item has rating object', function(){
fetchedRepos = null;
_httpBackend.flush();
fetchedRepos.forEach(function(repo){
expect(repo.__rating.stable).toEqual(5);
expect(repo.__rating.useful).toEqual(4) ;
});
});
});
describe('abnormal cases', function(){
describe('malformed JSON', function(){
var fetchedRepos;
var repos = [
{ description: 'Awesome _rating_:{"stable":5 "useful":4}' },
{ description: 'Meh _rating_:{""stable":5, "useful":4}' },
{ description: 'Unfinished _rating_:{"stable":{{}, "useful":4}' }
];
beforeEach(function(){
_httpBackend
.when('GET', /api.github.com/)
.respond(repos);
repo.initBaseModel('foo', [])
.then(function(repos){
fetchedRepos = repos;
});
});
it('returns error object (for now at least)', function(){
fetchedRepos = null;
_httpBackend.flush();
fetchedRepos.forEach(function(repo){
expect(repo.__rating instanceof SyntaxError).toBeTruthy();
});
});
});
describe('various valid JSON', function(){
var fetchedRepos;
var repos = [
{ description: 'Awesome _rating_:["stable":5, "useful":4]' },
{ description: 'Meh _rating_:"plain string"' },
{ description: 'Unfinished _rating_:{"a":{"stable":3}, "b":{"useful":4}}' }
];
beforeEach(function(){
_httpBackend
.when('GET', /api.github.com/)
.respond(repos);
repo.initBaseModel('foo', [])
.then(function(repos){
fetchedRepos = repos;
});
});
it('parses, but up to user land to handle', function(){
fetchedRepos = null;
_httpBackend.flush();
fetchedRepos.forEach(function(repo){
expect(repo.__rating).toBeDefined();
});
});
});
describe('missing _rating_: in description', function(){
var fetchedRepos;
var repos = [
{ description: 'Awesome' },
{ description: 'Meh {"a":"B"}' },
{ description: 'Unfinished:{"a":"B"}' }
];
beforeEach(function(){
_httpBackend
.when('GET', /api.github.com/)
.respond(repos);
repo.initBaseModel('foo', [])
.then(function(repos){
fetchedRepos = repos;
});
});
it('returns rating of null', function(){
fetchedRepos = null;
_httpBackend.flush();
fetchedRepos.forEach(function(repo){
expect(repo.__rating).toBe(null);
});
});
});
describe('missing description (ie Github API change', function(){
var fetchedRepos;
var repos = [
{ desc: 'Awesome' },
{ desc: 'Meh {"a":"B"}' },
{ desc: 'Unfinished:{"a":"B"}' }
];
beforeEach(function(){
_httpBackend
.when('GET', /api.github.com/)
.respond(repos);
repo.initBaseModel('foo', [])
.then(function(repos){
fetchedRepos = repos;
});
});
it('returns rating with ApiMismatchError', function(){
fetchedRepos = null;
_httpBackend.flush();
fetchedRepos.forEach(function(repo){
expect(repo.__rating.name).toEqual('ApiMismatchError');
});
});
});
});
});
describe('.getBaseModel', function(){
describe('nominal cases', function(){
describe('initialize model', function(){
var fetchedRepos;
var count;
var repos = [
{ description: 'Awesome _rating_:{"stable":9, "useful":8}' },
{ description: 'Meh _rating_:{"stable":5, "useful":4}' },
{ description: 'Unfinished _rating_:{"stable":1, "useful":6}' }
];
beforeEach(function(){
count=0;
function fetchResponse(method, url, data, headers){
count+=1;
return [ 200, repos, {} ];
}
88
_httpBackend
.when('GET', /api.github.com/)
.respond(repos);
repo.getBaseModel('forforforf', [], {init: true})
.then(function(repos){
fetchedRepos = repos;
});
});
it('returns collection', function(){
expect(fetchedRepos).not.toBeDefined();
_httpBackend.flush();
expect(fetchedRepos.length).toEqual(3);
});
});
describe('initialize model', function(){
var fetchedRepos;
var count;
var repos = [
{ description: 'Awesome _rating_:{"stable":9, "useful":8}' },
{ description: 'Meh _rating_:{"stable":5, "useful":4}' },
{ description: 'Unfinished _rating_:{"stable":1, "useful":6}' }
];
beforeEach(function(){
count=0;
function fetchResponse(method, url, data, headers){
count+=1;
return [ 200, repos, {} ];
}
_httpBackend
.when('GET', /api.github.com/)
.respond(repos);
//initialize cache
repo.getBaseModel('forforforf', [], {init: true})
.then(function(repos){
fetchedRepos = repos;
});
});
it('returns collection', function(){
expect(fetchedRepos).not.toBeDefined();
_httpBackend.flush();
// getting mode from cache
repo.getBaseModel('forforforf', [])
.then(function(repos){
expect(fetchedRepos).toEqual(repos);
});
//If No http request was made, flush will error
expect(function(){ _httpBackend.flush(); }).toThrow('No pending request to flush !');
});
});
});
});
});
describe('list', function(){
beforeEach(inject(function( $injector, $httpBackend, Repo){
var repos = [
{ description: 'Awesome _rating_:{"stable":9, "useful":8}' },
{ description: 'Meh _rating_:{"stable":5, "useful":4}' },
{ description: 'Unfinished _rating_:{"stable":1, "useful":6}' }
];
$httpBackend
.when('GET', /api.github.com/)
.respond(repos);
}));
});
}) |
/**
* Module exports.
*/
exports = module.exports = setup;
/**
* Module dependencies.
*/
var http = require('http');
var send = require('send');
var root = __dirname;
var swf = '/ClipAndFile.swf';
function setup () {
return http.createServer(onReq);
}
function onReq (req, res) {
send(req, swf)
.root(root)
.on('error', onError)
.pipe(res);
}
function onError (err) {
res.statusCode = err.status || 500;
res.end(err.message);
}
|
'use strict';
var Anyfetch = require('anyfetch');
var rarity = require('rarity');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} document to hydrate
* @param {function} cb Callback, first parameter, is the error if any, then the processed data
*/
module.exports = function(path, document, changes, cb) {
var anyfetch = new Anyfetch(document.access_token);
anyfetch.setApiUrl(cb.apiUrl);
anyfetch.deleteDocumentByIdentifier(document.identifier, rarity.carryAndSlice([{}], 2, function(err) {
cb(err, null);
}));
};
|
export { default as Tooltip } from './directives/tooltip'
|
var gulp = require("gulp");
var jshint = require("gulp-jshint");
var uglify = require("gulp-uglify");
var minifyCSS = require("gulp-minify-css");
var concat = require("gulp-concat");
var rename = require("gulp-rename");
var del = require("del");
var assets = require("gulp-assets");
gulp.task("css", function() {
gulp.src("./templates/layouts/default.html")
.pipe(assets({
js: false,
css: "site.css",
cwd: "../../public/"
}))
.pipe(concat("site.css"))
.pipe(minifyCSS({ comments:true, spare:true }))
.pipe(rename({ suffix: ".min" }))
.pipe(gulp.dest("./public/assets/dist"));
});
gulp.task("js", function() {
gulp.src("./templates/layouts/default.html")
.pipe(assets({
js: "site.js",
css: false,
cwd: "../../public/"
}))
.pipe(concat("site.js"))
.pipe(uglify())
.pipe(rename({ suffix: ".min" }))
.pipe(gulp.dest("./public/assets/dist"));
});
gulp.task("lint", function() {
gulp.src([
"./public/assets/js/**/*.js",
])
.pipe(jshint())
.pipe(jshint.reporter("default"))
.pipe(jshint.reporter("fail"));
});
gulp.task("clean", function(cb) {
del([
"public/assets/dist/*.css",
"public/assets/dist/*.min.css",
"public/assets/dist/*.js",
"public/assets/dist/*.min.js"
], cb);
});
gulp.task("default", ["clean", "lint", "css", "js"]);
|
'use strict';
angular
.module('webRemoteViewerApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
|
(function($$) {
/**
* WindowTitle class
*/
class WindowTitle extends Component
{
/**
* @constructor
* @param {String} cfg.title - title text
* @param {Boolean} cfg.closable - is set a close box is added
* @param {Function} cfg.onclose - function to call on close
*/
constructor( cfg ) {
super( cfg );
this._clsName = 'x-header';
}
render( ) {
return {
items: [
{
cls: 'x-text',
content: this.title
},
{
xtype: 'Icon',
icon: 'fa@times',
listeners: {
'click': this.onclose
}
}
]
}
}
}
/**
* WindowBase class
* base class for all popup windows
*/
class WindowBase extends Component
{
/**
* @constructor
* @param {Boolean} cfg.clickDismiss - if true a click outside of the window close it
* @param {Boolean} cfg.modal - if true the window is modal
* @param {String} cfg.cls - class to add to the window
*/
constructor( cfg ) {
super( cfg, {cls:''} );
this._checkClick = this._checkClick.bind(this);
this._showInfo = undefined;
this._init = false;
this._root = null;
}
/**
* show the window as modal
* @param {Object} showInfo - depending of the subclasses
*/
show( showInfo ) {
if( !this._init ) {
this._show_info = showInfo;
this._createRootNode( );
this._init = true;
}
else {
this._refresh( );
}
}
/**
* close the window
*/
close( ) {
if( this._root && this._init ) {
if( this.clickDismiss ) {
window.removeEventListener( 'click', this._checkClick );
}
React.unmountComponentAtNode(this._root);
document.body.removeChild(this._root);
this._init = false;
}
}
// small hack:
// for modless windows, as react must render elements inside a root element (and remove other elements)
// we have to create a temp element by hand
// for modals: the created element serves as modal mask, we keep it.
_createRootNode( ) {
// insert a div into which we will render
this._root = document.createElement( 'div' );
if( this.clickDismiss ) {
let me = this;
asap( function() { // because we get the last click
window.addEventListener( 'click', me._checkClick );
});
}
if( this.modal ) {
// put it inside body
this._root.className = 'x-modal-mask x-center';
}
document.body.appendChild( this._root );
React.renderSubtreeIntoContainer( this._, React.createElement(this._), this._root );
}
/**
* check is the click was done on our descendant
*/
_checkClick( e ) {
let dom = this._getDOM( );
if( !isDescendantElement(e.target,dom) ) {
this.onClickAway( );
}
}
/**
* a click appear outside of this or our descendants
*/
onClickAway( ) {
this.close( );
}
}
/**
* Stabdard Window class
* basic Window with a title
*/
class Window extends WindowBase {
/**
* @constructor
* @param {String} cfg.title - title of the window, if title is specified, the window show a caption
* @param {Object|Component} cfg.content - content of the window
*/
constructor( cfg ) {
super( cfg );
if( this.title ) {
this._header = new WindowTitle( {title:this.title,closable:this.closable,onclose:this.onTitleClose.bind(this)} );
}
}
render( ) {
let bbar;
if( this.bbar ) {
bbar = {
cls: 'x-bar bottom',
layout: {
type: 'horizontal',
direction: 'end'
},
items: this.bbar
}
}
return {
cls: 'x-box x-nosel ' + this.cls,
style: {
position: 'fixed',
width: this.width,
height: this.height,
minWidth: 100,
minHeight: 100,
borderWidth: this.frame ? this.frame : 0
},
items: [
this._header,
this.content,
bbar
]
}
}
onTitleClose( ) {
this.close( );
}
}
/**
* MenuSeparator
* Basic menu separator
*/
class MenuSeparator extends Component
{
render( ) {
return {
}
}
}
/**
* MenuItem
* item of a menu
*/
class MenuItem extends Component
{
/**
* @constructor
* @param {String} cfg.title - title of the element
* @param {String} cfg.icon - icon of the element
* @param {Menu} cfg.menu - sub menu if this item is a popup menu
*/
constructor( cfg ) {
super( cfg );
this.bindAll( );
this.addEvents('click');
this._icon = new Icon({width:16});
this._popup = new Icon({icon:'fa@angle-right',width:16});
}
render( ) {
let isPopup = this.menu ? true : false;
this._icon.icon = this.icon;
return {
layout: 'horizontal',
onclick: this.onClick,
style: {
alignItems: 'center'
},
items: [
this._icon,
{
cls: 'x-text',
content: this.title,
flex: 1,
},
isPopup ? this._popup : {width:16},
]
}
}
onClick( ) {
if( this.menu ) {
this._showSubMenu( );
}
else {
if( this.handler ) {
this.handler( this );
}
this.fireEvent( 'click' );
// simulate a clic to close the main menu
let me = new MouseEvent( 'click' );
window.dispatchEvent( me );
}
}
_showSubMenu( ) {
this.menu.show( {ref:this,align:'trtl'} );
}
}
/**
* compute the menu position (avoid getting out of the screen)
* align: tlbt
*/
function positionElementInScreen( tar_dom, ref_dom, align, lvl=0 ) {
let rc_ref = ref_dom.getBoundingClientRect( ),
rc_tar = tar_dom.getBoundingClientRect( );
let href, vref, x, y;
if( align[0]=='t' ) {vref = rc_ref.top;}
else {vref = rc_ref.top+rc_ref.height;}
if( align[1]=='r' ) {href = rc_ref.left+rc_ref.width;}
else {href = rc_ref.left;}
if( align[2]=='t' ) {y = vref;}
else {y = vref-rc_tar.height;}
if( align[3]=='r' ) {x = href-rc_tar.width;}
else {x = href;}
let sw = document.body.clientWidth,
sh = document.body.clientHeight,
tmp;
if( (x+rc_tar.width)>sw ) {
if( align[1]=='r' && align[3]=='l' && lvl==0 ) {
align = align[0]+'l'+align[2]+'r';
tmp = positionElementInScreen( tar_dom, ref_dom, align, 1 );
x = tmp.x + 4;
}
else {
x = sw-rc_tar.width;
}
}
if( x<0 ) {
if( align[1]=='l' && align[3]=='r' && lvl==0 ) {
align = align[0]+'r'+align[2]+'l';
tmp = positionElementInScreen( tar_dom, ref_dom, align, 1 );
x = tmp.x - 4;
}
else {
x = 0;
}
}
if( (y+rc_tar.height)>sh ) { y = sh-rc_tar.height; }
if( y<0 ) { y = 0; }
return {x,y};
}
/**
* Menu class
* Popup menu
*/
class Menu extends WindowBase {
/**
* @constructor
* @param {[MenuItem|MenuSeparator]} cfg.items - items
*/
constructor( cfg ) {
super( cfg );
this.clickDismiss = true;
}
afterMount( ) {
if( this._show_info ) {
this._positionMenu( this._show_info );
}
else {
let dom = this._getDOM();
dom.style.opacity = 1.0;
}
}
_positionMenu( info ) {
let tar_dom = this._getDOM(),
ref_dom = info.ref._getDOM();
let {x,y} = positionElementInScreen( tar_dom, ref_dom, info.align );
tar_dom.style.left = x;
tar_dom.style.top = y;
tar_dom.style.opacity = 1.0;
}
render( ) {
return {
layout: 'vertical',
style: {
position: 'absolute',
minWidth: 'min-content',
opacity: 0,
zIndex: 100,
},
items: this.items
}
}
}
/**
* MessageBox Dialog
* @param {String} cfg.cls - base class of the messagebox
* @param {String} cfg.icon - icon to show
* @param {String} cfg.title - title of the message
* @param {String} cfg.text - text of the message (the text is not interpreted a html, cf. html parameter)
* @param {String} cfg.html - text of the message the text is pure html and you have to take care of the content (html/javascript attacks)
* @param {Boolean} cfg.clickDismiss - if true a click outside of the window close it
*/
function MessageBox( cfg ) {
const {title,text,icon,autoClose,clickDismiss,cls,html} = cfg;
let ic = new Icon({icon:icon,size:48});
let btn = new Button( {title: 'OK', width: 80, deffocus: true} );
let msg;
if( html ) {
msg = {
tag: 'p',
__direct: {
__html: html
}
}
}
else {
msg = text;
}
let content = {
layout: 'vertical',
style: {
paddingLeft: 32,
paddingRight: 32,
paddingTop: 16,
paddingBottom: 16,
maxWidth: 540,
color: '#424242',
},
items: [
{
layout: 'horizontal',
items: [
{
layout: {
type: 'vertical',
direction: 'center'
},
style: {
paddingRight: 32,
},
items: ic,
},
{
style: {
flexGrow: 1,
},
items: [
{
tag: 'h1',
content: title
},
{
tag: 'p',
style: {
textAlign: 'justify',
userSelect: 'initial',
overflowY: 'auto',
maxHeight: 200,
},
items: msg
}
]
},
]
},
{
layout: {
type: 'horizontal',
direction: 'end'
},
items: btn
}
]
};
btn.on( 'click', () => {wnd.close();} )
if( autoClose ) {
let tme = autoClose;
let xx = setInterval( ()=> {
tme--;
btn.setTitle( 'OK ('+tme+'s)' );
if( tme<=0 ) {
clearInterval( xx );
wnd.close( );
}
}, 1000 );
}
var wnd = new Window({content:content,clickDismiss:clickDismiss,modal:true,cls:cls});
wnd.show( );
}
/**
*
*/
class SnackBarItem extends Component
{
constructor( cfg ) {
super( cfg );
this._clsName = 'x-item';
this.addEvents( 'discard' );
this._tm1 = setTimeout( this._discard.bind(this), 5000 );
this._tm12 = setTimeout( this._fadeOut.bind(this), 4500 );
}
beforeUnmount( ) {
if( this._tm1 ) {clearTimeout( this._tm1 );}
if( this._tm2 ) {clearTimeout( this._tm2 );}
}
render( ) {
if( this.icon ) {
return {
cls: this.cls,
layout: 'horizontal',
items: [
{
xtype: 'Icon',
icon: this.icon
},
this.text
]
}
}
else {
return {
cls: this.cls,
content: this.text
}
}
}
_fadeOut( ) {
delete this._tm2;
this._addDOMClass( 'fade' );
}
_discard( ) {
delete this._tm1;
this.fireEvent( 'discard', this.uid );
}
}
/**
*
*/
class SnackBar extends WindowBase {
constructor( cfg ) {
super( cfg );
this._items = [];
this._uid = 1;
}
addSnack( cfg ) {
cfg = apply( cfg, {
uid:this._uid++,
listeners: {
discard: this._discardElement.bind(this)
}
});
this._items.push( new SnackBarItem(cfg) );
this.show( );
}
_discardElement( uid ) {
let items = this._items;
for( let e in items ) {
if( uid==items[e].uid ) {
items = items.splice( e, 1 );
if( items.length==0 ) {
this.close( );
}
else {
this._refresh( );
}
break;
}
}
}
render( ) {
return {
style: {
position: 'fixed',
left: 0,
bottom: 0,
},
items: this._items
}
}
}
$$.Menu = Menu;
$$.MenuItem = MenuItem;
$$.MenuSeparator = MenuSeparator;
$$.Window = Window;
$$.WindowBase = WindowBase;
$$.Exact.MessageBox = MessageBox;
$$.SnackBar = SnackBar;
$$.positionElementInScreen = positionElementInScreen;
})( window || this ); |
new Vue({
el: '.container',
data: {
todos: [
{ text: 'Test your mind' },
{ text: 'Wash dishes' },
{ text: 'Move to USA' },
],
newTask: ''
},
methods: {
add: function () {
var newTask = this.newTask.trim();
if (newTask === ''){
return;
}
this.todos.push({ text: newTask });
this.newTask = '';
},
remove: function (todoNumber) {
this.todos.splice(todoNumber, 1);
}
}
});
|
var bigInt = (function() {
var bi_base = 0x4000000; // 2^26 so there is not overflow in multiplication in the JS 2^53 ints
function _testBase() {
bi_base = 1000;
}
function BigInt (value) {
this.value = value;
}
BigInt.prototype.toString = function() {
return this.value.toString();
};
// string representation used in tests
BigInt.prototype.testString = function() {
return this.value.toString();
};
// simple predicates
BigInt.prototype.isNeg = function() {
return this.sign() < 0;
};
BigInt.prototype.isPos = function() {
return this.sign() > 0;
};
BigInt.prototype.isZero = function() {
return this.sign() == 0;
};
BigInt.prototype.isEven = function() {
return this.sign()==0 || ((this.value[1] % 2) == 0);
};
BigInt.prototype.isOdd = function() {
return !this.isEven();
};
// comparison methods
BigInt.prototype.sign = function() {
if (this.value[0]<0)
return -1;
else if (this.value[0]>0)
return 1;
else
return 0;
};
BigInt.prototype.compareTo = function(other) {
if (!(other instanceof BigInt)) {
other = parseInput(other);
}
var result = compareInts(this.value[0], other.value[0]);
if (result == 0) {
for (var i=Math.abs(this.value[0]); i>=1 && result==0; i--) {
result = compareInts(this.value[i], other.value[i]);
}
}
return result;
};
function compareInts(thisv, otherv) {
if (thisv == otherv)
return 0;
else if (thisv < otherv)
return -1;
else if (thisv > otherv)
return 1;
}
BigInt.prototype.eq = function(other) {
return this.compareTo(other) == 0;
};
BigInt.prototype.ne = function(other) {
return this.compareTo(other) != 0;
};
BigInt.prototype.lt = function(other) {
return this.compareTo(other) < 0;
};
BigInt.prototype.le = function(other) {
return this.compareTo(other) <= 0;
};
BigInt.prototype.gt = function(other) {
return this.compareTo(other) > 0;
};
BigInt.prototype.ge = function(other) {
return this.compareTo(other) >= 0;
};
// simple math methods
BigInt.prototype.abs = function() {
var value = this.value.slice(0);
value[0] = Math.abs(value[0]);
return new BigInt(value);
};
BigInt.prototype.neg = function() {
var value = this.value.slice(0);
value[0] = -1 * value[0];
return new BigInt(value);
};
// arithmetic methods
BigInt.prototype.add = function(other) {
if (!(other instanceof BigInt)) {
other = parseInput(other);
}
var thisv = this.value.slice(0);
var otherv = other.value.slice(0);
if (thisv[0] >= 0 && otherv[0] >= 0) {
// Sum of two positive addends
if (thisv[0] >= otherv[0])
return new BigInt(sum(thisv, otherv));
else
return new BigInt(sum(otherv, thisv));
} else if (thisv[0] <= 0 && otherv[0] <= 0) {
// Sum of two negative addends
thisv[0] = -1 * thisv[0];
otherv[0] = -1 * otherv[0];
if (thisv[0] >= otherv[0])
var sumv = sum(thisv, otherv);
else
var sumv = sum(otherv, thisv);
sumv[0] = -1 * sumv[0];
return new BigInt(sumv);
} else {
// Sum of two addends with different signs
var absthis = this.abs();
var absother = other.abs();
if (absother.eq(absthis))
return new BigInt(parseInput(0));
var thisNeg = this.isNeg();
var thisGT = absthis.gt(absother);
if (thisGT)
var diffv = diff(absthis.value, absother.value);
else
var diffv = diff(absother.value, absthis.value);
if ((thisNeg && thisGT) || (!thisNeg && !thisGT))
diffv[0] = -1 * diffv[0];
return new BigInt(diffv);
}
};
BigInt.prototype.subtract = function(other) {
if (!(other instanceof BigInt)) {
other = parseInput(other);
}
return this.add(other.neg());
};
BigInt.prototype.multiply = function(other) {
if (!(other instanceof BigInt)) {
other = parseInput(other);
}
var productv = [];
if (this.eq(0) || other.eq(0))
productv = [0];
else {
var thisabs = this.abs();
var otherabs = other.abs();
if (thisabs.eq(1))
productv = otherabs.value.slice(0);
else if (otherabs.eq(1))
productv = thisabs.value.slice(0);
else {
if (thisabs.value[0] > otherabs.value[0]) {
var multiplier = otherabs.value.slice(0);
var multiplicand = thisabs.value.slice(0);
} else {
var multiplier = thisabs.value.slice(0);
var multiplicand = otherabs.value.slice(0);
}
productv.push(0);
for (var i=1; i<=multiplier[0]; i++) {
var tmp = [multiplicand[0] + (i-1)];
for (var p=1; p<i; p++)
tmp.push(0);
for (var j=1; j<=multiplicand[0]; j++) {
tmp.push(multiplier[i] * multiplicand[j]);
}
productv = sum(tmp, productv);
}
}
if (this.sign() != other.sign())
productv[0] = -1 * productv[0];
}
return new BigInt(productv);
}
/*
* assumes that the addends are positive
* and that addend1 has the same or more digits
*/
function sum(addend1, addend2) {
var sum = [];
sum.push(addend1[0]);
var carry = 0;
for(var i=1; i<addend1[0]+1; i++) {
var a1 = addend1[i];
var a2 = addend2.length>i ? addend2[i] : 0;
var s = a1 + a2 + carry;
sum.push(s % bi_base);
carry = Math.floor(s / bi_base);
}
if (carry>0) {
sum[0]++;
sum.push(carry);
}
return sum;
}
/*
* assumes that the minuend is larger that the subtrahend
*/
function diff(minuend, subtrahend) {
var diff = [];
diff.push(minuend[0]);
var carry = 0;
for(var i=1; i<minuend[0]+1; i++) {
var m = minuend[i];
var s = subtrahend.length>i ? subtrahend[i] : 0;
var d = (m-carry) - s;
if (d < 0) {
diff.push(d + bi_base);
carry = 1;
} else {
diff.push(d);
carry = 0;
}
}
for(var i=diff.length-1; i>=1 && diff[i]==0; i--)
diff[0]--;
return diff.slice(0, diff[0]+1);
}
BigInt.prototype.toNumber = function() {
if (this.value[0] == 0)
return 0;
else {
var out = 0;
for (var i=Math.abs(this.value[0]); i>=1; i--) {
out = (out*bi_base) + this.value[i];
}
if (this.value[0] < 0)
out = -1 * out;
return out;
}
};
function parseInput(invalue) {
var outvalue = [];
if (invalue instanceof BigInt)
outvalue = invalue.value.slice(0);
else if (invalue == 0)
outvalue.push(0);
else {
var negate = (invalue < 0);
if (negate)
invalue = -1 * invalue;
while (invalue > 0) {
if (invalue < bi_base) {
outvalue.push(invalue);
invalue = 0;
} else {
outvalue.push(invalue % bi_base);
invalue = Math.floor(invalue/bi_base);
}
}
var count = outvalue.length;
if (negate)
count = -1 * count;
outvalue.unshift(count);
}
return new BigInt(outvalue);
}
// some synonms
BigInt.prototype.sub = BigInt.prototype.subtract;
BigInt.prototype.mul = BigInt.prototype.multiply;
BigInt.prototype.times = BigInt.prototype.multiply;
var fnReturn = function (a) {
if (typeof a === 'undefined') return parseInput(0);
return parseInput(a);
};
fnReturn._testBase = _testBase;
return fnReturn;
})();
if (typeof module !== "undefined") {
module.exports = bigInt;
}
|
(function () {
'use strict';
angular.module('scaApp.widgets', ['scaApp.core', 'ui.bootstrap']);
})();
|
/**
* A simple test case that determines if elements, specified by a selector,
* exist or not.
*
* The test fails for elements that are found and a case is created for each
* one. The test passes is the selector finds no matching elements.
*/
'use strict';
quail.formHasSubmitButton = function (quail, test, Case, options) {
var selector = 'input[type=submit], button[type=submit]';
this.get('$scope').each(function () {
var candidates = $(this).find('form');
if (candidates.length === 0) {
test.add(quail.lib.Case({
element: this,
status: 'inapplicable'
}));
} else {
candidates.each(function () {
var submitButton = $(this).find(selector);
var status = submitButton.length === 1 ? 'passed' : 'failed';
test.add(quail.lib.Case({
element: this,
status: status
}));
});
}
});
}; |
var User = require('mongoose').model('user');
var Joi = require('joi');
var server = require(__dirname + '/../lib/http');
var crypt = require(__dirname + '/../lib/crypt');
var log = require(__dirname + '/../lib/log');
var proto = require(__dirname + '/../lib/proto');
var crypto = require(__dirname + '/../lib/crypto');
var moment = require('moment');
var Boom = require('boom');
server.route({
method: 'POST',
path: '/api/v1/login',
handler: function(request, reply){
User.findOne({username: request.payload.username}, function(err, doc){
if(err){
log.error('Check user error: '+err);
return reply(Boom.unauthorized('Invalid user or password'));
}
if(!doc){
log.error('Error user not Found');
return reply(Boom.unauthorized('Invalid user or password'));
}
crypt.compare(request.payload.password, doc.password, function(err, check){
if(err){
log.error('Error on compare password: '+err);
return reply(Boom.unauthorized('Invalid user or password'));
}
if(!check){
return reply(Boom.unauthorized('Invalid user or password'));
}
var expires = moment().add('year', 1).unix();
var token = new proto.Token({
_id : doc._id.toString(),
username: doc.username,
expires: expires,
created: moment().unix()
});
var encrypted = crypto.encrypt(token.toBuffer());
return reply({
token: encrypted.toString('base64')
});
});
});
},
config: {
validate: {
payload: {
username: Joi.string().required().min(2).max(25),
password: Joi.string().required().min(8).max(50)
}
}
}
});
//Registrar usuário
server.route({
method: 'POST',
path: '/api/v1/user/register',
handler: function(request, reply){
crypt.encrypt(request.payload.password, function(err, hash){
if(err){
log.error('Encrypt error: '+err);
return reply(Boom.badRequest('Try again later...'));
}
request.payload.password = hash;
var user = new User(request.payload);
user.save(function(err, doc){
if(err){
log.error('Save user error: '+err);
if(err.name === 'ValidationError'){
if(!!err.errors.email){
return reply(Boom.badRequest('Email already in use'));
}
if(!!err.errors.username){
return reply(Boom.badRequest('Username already in use'));
}
}
return reply(Boom.badRequest('Try again later...'));
}
var expires = moment().add(1, 'year').unix();
var token = new proto.Token({
_id : doc._id.toString(),
username: doc.username,
expires: expires,
created: moment().unix()
});
var encrypted = crypto.encrypt(token.toBuffer());
return reply({
token: encrypted.toString('base64')
});
});
});
},
config: {
validate: {
payload: {
name: Joi.string().min(2).max(100).default(''),
username: Joi.string().required().min(2).max(25),
email: Joi.string().required().email(),
password: Joi.string().required().min(8).max(50)
}
}
}
});
server.route({
method: ['POST', 'PUT'],
path: '/api/v1/user',
handler: function(request, reply){
//validando token
var token = request.headers['x-token'] || '';
if(token === ''){
return reply(Boom.unauthorized('Sorry you can\'t access here'));
}
try{
var buff = crypto.decrypt(new Buffer(token, 'base64'));
var obj = proto.Token.decode(buff, false);
if(obj.expires.low < (new Date().getTime() / 1000))
return reply(Boom.forbidden('Expired authentication token.'));
if(request.payload.username != obj.username){
log.error('Token is not valid for this user');
return reply(Boom.unauthorized('Token is not valid for this user'));
}
delete request.payload.username;
User.findById(obj._id, function(err, doc){
if(err){
log.error('Validate user error: '+err);
return reply(Boom.badRequest('Invalid user'));
}
User.findByIdAndUpdate(obj._id, {$set: request.payload}, function(err, doc){
if(err){
log.error('Updating user error: '+err);
return reply(Boom.badRequest('Update is failed'));
}
delete doc.password;
return reply(doc);
});
});
}catch(err){
log.error('Validate token error: '+err);
return reply(Boom.forbidden('Invalid token'));
}
},
config: {
validate: {
payload: {
name: Joi.string().min(2).max(100).optional(),
username: Joi.string().min(2).max(25).required(),
email: Joi.string().email().optional(),
password: Joi.string().min(8).max(50).optional()
}
}
}
});
server.route({
method: 'GET',
path: '/api/v1/user',
handler: function(request, reply){
//validando token
var token = request.headers['x-token'] || '';
if(token === ''){
return reply(Boom.unauthorized('Sorry you can\'t access here'));
}
try{
var buff = crypto.decrypt(new Buffer(token, 'base64'));
var obj = proto.Token.decode(buff, false);
if(obj.expires.low < (new Date().getTime() / 1000))
return reply(Boom.forbidden('Expired authentication token.'));
User.findById(obj._id, function(err, doc){
if(err){
log.error('Validate user error: '+err);
return reply(Boom.badRequest('Invalid user'));
}
if(doc.username != obj.username){
log.error('Token is not valid for this user');
return reply(Boom.unauthorized('Token is not valid for this user'));
}
delete doc.password;
return reply(doc);
});
}catch(err){
log.error('Validate token error: '+err);
return reply(Boom.forbidden('Invalid token'));
}
}
});
server.route({
method: 'GET',
path: '/api/v1/user/{username}',
handler: function(request, reply){
//validando token
var token = request.headers['x-token'] || '';
if(token === ''){
return reply(Boom.unauthorized('Sorry you can\'t access here'));
}
try{
var buff = crypto.decrypt(new Buffer(token, 'base64'));
var obj = proto.Token.decode(buff, false);
if(obj.expires.low < (new Date().getTime() / 1000))
return reply(Boom.forbidden('Expired authentication token.'));
User.findOne({username: request.params.username}, function(err, doc){
if(err){
log.error('Check user error: '+err);
return reply(Boom.notFound('Invalid user'));
}
delete doc.password;
return reply(doc);
});
}catch(err){
log.error('Validate token error: '+err);
return reply(Boom.forbidden('Invalid token'));
}
},
config: {
validate: {
params: {
username: Joi.string().required().min(2).max(25)
}
}
}
});
|
var tape = require("tape"),
vec2 = require("vec2"),
aabb2ToAabb2 = require("..");
tape("aabb2ToAabb2(minx1, miny1, maxx1, maxy1, minx2, miny2, maxx2, maxy2)", function(assert) {
assert.deepEqual(aabb2ToAabb2(
0, 0, 1, 1,
0.5, 0.5, 1.5, 1.5
), {
point: vec2.create(0.5, 0.5),
normal: vec2.create(0.7071067690849304, 0.7071067690849304),
depth: 0.7071067811865476,
data: null
});
assert.equal(aabb2ToAabb2(
0, 0, 1, 1,
1, 1, 2, 2
), false);
assert.end();
});
|
var Attacklab=Attacklab||{};
Attacklab.wmdBase=function(){
var _1=top;
var _2=_1["Attacklab"];
var _3=_1["document"];
var _4=_1["RegExp"];
var _5=_1["navigator"];
_2.Util={};
_2.Position={};
_2.Command={};
var _6=_2.Util;
var _7=_2.Position;
var _8=_2.Command;
_2.Util.IE=(_5.userAgent.indexOf("MSIE")!=-1);
_2.Util.oldIE=(_5.userAgent.indexOf("MSIE 6.")!=-1||_5.userAgent.indexOf("MSIE 5.")!=-1);
_2.Util.newIE=!_2.Util.oldIE&&(_5.userAgent.indexOf("MSIE")!=-1);
_6.makeElement=function(_9,_a){
var _b=_3.createElement(_9);
if(!_a){
var _c=_b.style;
_c.margin="0";
_c.padding="0";
_c.clear="none";
_c.cssFloat="none";
_c.textAlign="left";
_c.position="relative";
_c.lineHeight="1em";
_c.border="none";
_c.color="black";
_c.backgroundRepeat="no-repeat";
_c.backgroundImage="none";
_c.minWidth=_c.minHeight="0";
_c.maxWidth=_c.maxHeight="90000px";
}
return _b;
};
_6.getStyle=function(_d,_e){
var _f=function(_10){
return _10.replace(/-(\S)/g,function(_11,_12){
return _12.toUpperCase();
});
};
if(_d.currentStyle){
_e=_f(_e);
return _d.currentStyle[_e];
}else{
if(_1.getComputedStyle){
return _3.defaultView.getComputedStyle(_d,null).getPropertyValue(_e);
}
}
return "";
};
_6.getElementsByClass=function(_13,_14,_15){
var _16=[];
if(_14==null){
_14=_3;
}
if(_15==null){
_15="*";
}
var _17=_14.getElementsByTagName(_15);
var _18=_17.length;
var _19=new _4("(^|\\s)"+_13+"(\\s|$)");
for(var i=0,j=0;i<_18;i++){
if(_19.test(_17[i].className.toLowerCase())){
_16[j]=_17[i];
j++;
}
}
return _16;
};
_6.addEvent=function(_1c,_1d,_1e){
if(_1c.attachEvent){
_1c.attachEvent("on"+_1d,_1e);
}else{
_1c.addEventListener(_1d,_1e,false);
}
};
_6.removeEvent=function(_1f,_20,_21){
if(_1f.detachEvent){
_1f.detachEvent("on"+_20,_21);
}else{
_1f.removeEventListener(_20,_21,false);
}
};
_6.regexToString=function(_22){
var _23={};
var _24=_22.toString();
_23.expression=_24.replace(/\/([gim]*)$/,"");
_23.flags=_4.$1;
_23.expression=_23.expression.replace(/(^\/|\/$)/g,"");
return _23;
};
_6.stringToRegex=function(_25){
return new _4(_25.expression,_25.flags);
};
_6.elementOk=function(_26){
if(!_26||!_26.parentNode){
return false;
}
if(_6.getStyle(_26,"display")=="none"){
return false;
}
return true;
};
_6.skin=function(_27,_28,_29,_2a){
var _2b;
var _2c=(_5.userAgent.indexOf("MSIE")!=-1);
if(_2c){
_6.fillers=[];
}
var _2d=_29/2;
for(var _2e=0;_2e<4;_2e++){
var _2f=_6.makeElement("div");
_2b=_2f.style;
_2b.overflow="hidden";
_2b.padding="0";
_2b.margin="0";
_2b.lineHeight="0px";
_2b.height=_2d+"px";
_2b.width="50%";
_2b.maxHeight=_2d+"px";
_2b.position="absolute";
if(_2e&1){
_2b.top="0";
}else{
_2b.bottom=-_29+"px";
}
_2b.zIndex="-1000";
if(_2e&2){
_2b.left="0";
}else{
_2b.marginLeft="50%";
}
if(_2c){
var _30=_6.makeElement("span");
_2b=_30.style;
_2b.height="100%";
_2b.width=_2a;
_2b.filter="progid:DXImageTransform.Microsoft."+"AlphaImageLoader(src='"+_2.basePath+"images/bg.png')";
_2b.position="absolute";
if(_2e&1){
_2b.top="0";
}else{
_2b.bottom="0";
}
if(_2e&2){
_2b.left="0";
}else{
_2b.right="0";
}
_2f.appendChild(_30);
}else{
_2b.backgroundImage="url("+_28+")";
_2b.backgroundPosition=(_2e&2?"left":"right")+" "+(_2e&1?"top":"bottom");
}
_27.appendChild(_2f);
}
var _31=function(_32){
var _33=_6.makeElement("div");
if(_6.fillers){
_6.fillers.push(_33);
}
_2b=_33.style;
_2b.overflow="hidden";
_2b.padding="0";
_2b.margin="0";
_2b.marginTop=_2d+"px";
_2b.lineHeight="0px";
_2b.height="100%";
_2b.width="50%";
_2b.position="absolute";
_2b.zIndex="-1000";
if(_2c){
var _34=_6.makeElement("span");
_2b=_34.style;
_2b.height="100%";
_2b.width=_2a;
_2b.filter="progid:DXImageTransform.Microsoft."+"AlphaImageLoader(src='"+_2.basePath+"images/bg-fill.png',sizingMethod='scale')";
_2b.position="absolute";
_33.appendChild(_34);
if(_32){
_2b.left="0";
}
if(!_32){
_2b.right="0";
}
}
if(!_2c){
_2b.backgroundImage="url("+_2.basePath+"images/bg-fill.png)";
_2b.backgroundRepeat="repeat-y";
if(_32){
_2b.backgroundPosition="left top";
}
if(!_32){
_2b.backgroundPosition="right top";
}
}
if(!_32){
_33.style.marginLeft="50%";
}
return _33;
};
_27.appendChild(_31(true));
_27.appendChild(_31(false));
};
_6.setImage=function(_35,_36,_37,_38){
_36=_2.basePath+_36;
if(_5.userAgent.indexOf("MSIE")!=-1){
var _39=_35.firstChild;
var _3a=_39.style;
_3a.filter="progid:DXImageTransform.Microsoft."+"AlphaImageLoader(src='"+_36+"')";
}else{
_35.src=_36;
}
return _35;
};
_6.createImage=function(_3b,_3c,_3d){
_3b=_2.basePath+_3b;
if(_5.userAgent.indexOf("MSIE")!=-1){
var _3e=_6.makeElement("span");
var _3f=_3e.style;
_3f.display="inline-block";
_3f.height="1px";
_3f.width="1px";
_3e.unselectable="on";
var _40=_6.makeElement("span");
_3f=_40.style;
_3f.display="inline-block";
_3f.height="1px";
_3f.width="1px";
_3f.filter="progid:DXImageTransform.Microsoft."+"AlphaImageLoader(src='"+_3b+"')";
_40.unselectable="on";
_3e.appendChild(_40);
}else{
var _3e=_6.makeElement("img");
_3e.style.display="inline";
_3e.src=_3b;
}
_3e.style.border="none";
_3e.border="0";
if(_3c&&_3d){
_3e.style.width=_3c+"px";
_3e.style.height=_3d+"px";
}
return _3e;
};
_6.prompt=function(_41,_42,_43){
var _44;
var _45,_46,_47;
var _48=function(_49){
var _4a=(_49.charCode||_49.keyCode);
if(_4a==27){
_4b(true);
}
};
var _4b=function(_4c){
_6.removeEvent(_3.body,"keydown",_48);
var _4d=_47.value;
if(_4c){
_4d=null;
}
_45.parentNode.removeChild(_45);
_46.parentNode.removeChild(_46);
_43(_4d);
return false;
};
if(_42==undefined){
_42="";
}
var _4e=function(){
_46=_6.makeElement("div");
_44=_46.style;
_3.body.appendChild(_46);
_44.position="absolute";
_44.top="0";
_44.left="0";
_44.backgroundColor="#000";
_44.zIndex="1000";
var _4f=/konqueror/.test(_5.userAgent.toLowerCase());
if(_4f){
_44.backgroundColor="transparent";
}else{
_44.opacity="0.5";
_44.filter="alpha(opacity=50)";
}
var _50=_7.getPageSize();
_44.width="100%";
_44.height=_50[1]+"px";
};
var _51=function(){
_45=_3.createElement("div");
_45.style.border="3px solid #333";
_45.style.backgroundColor="#ccc";
_45.style.padding="10px;";
_45.style.borderTop="3px solid white";
_45.style.borderLeft="3px solid white";
_45.style.position="fixed";
_45.style.width="400px";
_45.style.zIndex="1001";
var _52=_6.makeElement("div");
_44=_52.style;
_44.fontSize="14px";
_44.fontFamily="Helvetica, Arial, Verdana, sans-serif";
_44.padding="5px";
_52.innerHTML=_41;
_45.appendChild(_52);
var _53=_6.makeElement("form");
_53.onsubmit=function(){
return _4b();
};
_44=_53.style;
_44.padding="0";
_44.margin="0";
_44.cssFloat="left";
_44.width="100%";
_44.textAlign="center";
_44.position="relative";
_45.appendChild(_53);
_47=_3.createElement("input");
_47.value=_42;
_44=_47.style;
_44.display="block";
_44.width="80%";
_44.marginLeft=_44.marginRight="auto";
_44.backgroundColor="white";
_44.color="black";
_53.appendChild(_47);
var _54=_3.createElement("input");
_54.type="button";
_54.onclick=function(){
return _4b();
};
_54.value="OK";
_44=_54.style;
_44.margin="10px";
_44.display="inline";
_44.width="7em";
var _55=_3.createElement("input");
_55.type="button";
_55.onclick=function(){
return _4b(true);
};
_55.value="Cancel";
_44=_55.style;
_44.margin="10px";
_44.display="inline";
_44.width="7em";
if(/mac/.test(_5.platform.toLowerCase())){
_53.appendChild(_55);
_53.appendChild(_54);
}else{
_53.appendChild(_54);
_53.appendChild(_55);
}
_6.addEvent(_3.body,"keydown",_48);
_45.style.top="50%";
_45.style.left="50%";
_45.style.display="block";
if(_2.Util.oldIE){
var _56=_7.getPageSize();
_45.style.position="absolute";
_45.style.top=_3.documentElement.scrollTop+200+"px";
_45.style.left="50%";
}
_3.body.appendChild(_45);
_45.style.marginTop=-(_7.getHeight(_45)/2)+"px";
_45.style.marginLeft=-(_7.getWidth(_45)/2)+"px";
};
_4e();
_1.setTimeout(function(){
_51();
var _57=_42.length;
if(_47.selectionStart!=undefined){
_47.selectionStart=0;
_47.selectionEnd=_57;
}else{
if(_47.createTextRange){
var _58=_47.createTextRange();
_58.collapse(false);
_58.moveStart("character",-_57);
_58.moveEnd("character",_57);
_58.select();
}
}
_47.focus();
},0);
};
_6.objectsEqual=function(_59,_5a){
for(var _5b in _59){
if(_59[_5b]!=_5a[_5b]){
return false;
}
}
for(_5b in _5a){
if(_59[_5b]!=_5a[_5b]){
return false;
}
}
return true;
};
_6.cloneObject=function(_5c){
var _5d={};
for(var _5e in _5c){
_5d[_5e]=_5c[_5e];
}
return _5d;
};
_6.escapeUnderscores=function(_5f){
_5f=_5f.replace(/(\S)(_+)(\S)/g,function(_60,_61,_62,_63){
_62=_62.replace(/_/g,"_");
return _61+_62+_63;
});
return _5f;
};
_7.getPageSize=function(){
var _64,_65;
var _66,_67;
if(_1.innerHeight&&_1.scrollMaxY){
_64=_3.body.scrollWidth;
_65=_1.innerHeight+_1.scrollMaxY;
}else{
if(_3.body.scrollHeight>_3.body.offsetHeight){
_64=_3.body.scrollWidth;
_65=_3.body.scrollHeight;
}else{
_64=_3.body.offsetWidth;
_65=_3.body.offsetHeight;
}
}
var _68,_69;
if(self.innerHeight){
_68=self.innerWidth;
_69=self.innerHeight;
}else{
if(_3.documentElement&&_3.documentElement.clientHeight){
_68=_3.documentElement.clientWidth;
_69=_3.documentElement.clientHeight;
}else{
if(_3.body){
_68=_3.body.clientWidth;
_69=_3.body.clientHeight;
}
}
}
if(_65<_69){
_67=_69;
}else{
_67=_65;
}
if(_64<_68){
_66=_68;
}else{
_66=_64;
}
var _6a=[_66,_67,_68,_69];
return _6a;
};
_7.getPixelVal=function(_6b){
if(_6b&&/^(-?\d+(\.\d*)?)px$/.test(_6b)){
return _4.$1;
}
return undefined;
};
_7.getTop=function(_6c,_6d){
var _6e=_6c.offsetTop;
if(!_6d){
while(_6c=_6c.offsetParent){
_6e+=_6c.offsetTop;
}
}
return _6e;
};
_7.setTop=function(_6f,_70,_71){
var _72=_7.getPixelVal(_6f.style.top);
if(_72==undefined){
_6f.style.top=_70+"px";
_72=_70;
}
var _73=_7.getTop(_6f,_71)-_72;
_6f.style.top=(_70-_73)+"px";
};
_7.getLeft=function(_74,_75){
var _76=_74.offsetLeft;
if(!_75){
while(_74=_74.offsetParent){
_76+=_74.offsetLeft;
}
}
return _76;
};
_7.setLeft=function(_77,_78,_79){
var _7a=_7.getPixelVal(_77.style.left);
if(_7a==undefined){
_77.style.left=_78+"px";
_7a=_78;
}
var _7b=_7.getLeft(_77,_79)-_7a;
_77.style.left=(_78-_7b)+"px";
};
_7.getHeight=function(_7c){
var _7d=_7c.offsetHeight;
if(!_7d){
_7d=_7c.scrollHeight;
}
return _7d;
};
_7.setHeight=function(_7e,_7f){
var _80=_7.getPixelVal(_7e.style.height);
if(_80==undefined){
_7e.style.height=_7f+"px";
_80=_7f;
}
var _81=_7.getHeight(_7e)-_80;
if(_81>_7f){
_81=_7f;
}
_7e.style.height=(_7f-_81)+"px";
};
_7.getWidth=function(_82){
var _83=_82.offsetWidth;
if(!_83){
_83=_82.scrollWidth;
}
return _83;
};
_7.setWidth=function(_84,_85){
var _86=_7.getPixelVal(_84.style.width);
if(_86==undefined){
_84.style.width=_85+"px";
_86=_85;
}
var _87=_7.getWidth(_84)-_86;
if(_87>_85){
_87=_85;
}
_84.style.width=(_85-_87)+"px";
};
_7.getWindowHeight=function(){
if(_1.innerHeight){
return _1.innerHeight;
}else{
if(_3.documentElement&&_3.documentElement.clientHeight){
return _3.documentElement.clientHeight;
}else{
if(_3.body){
return _3.body.clientHeight;
}
}
}
};
_2.inputPoller=function(_88,_89,_8a){
var _8b=this;
var _8c;
var _8d;
var _8e,_8f;
this.tick=function(){
if(!_6.elementOk(_88)){
return;
}
if(_88.selectionStart||_88.selectionStart==0){
var _90=_88.selectionStart;
var _91=_88.selectionEnd;
if(_90!=_8c||_91!=_8d){
_8c=_90;
_8d=_91;
if(_8e!=_88.value){
_8e=_88.value;
return true;
}
}
}
return false;
};
var _92=function(){
if(_6.getStyle(_88,"display")=="none"){
return;
}
if(_8b.tick()){
_89();
}
};
var _93=function(){
if(_8a==undefined){
_8a=500;
}
_8f=_1.setInterval(_92,_8a);
};
this.destroy=function(){
_1.clearInterval(_8f);
};
_93();
};
_2.undoManager=function(_94,_95){
var _96=this;
var _97=[];
var _98=0;
var _99="none";
var _9a;
var _9b;
var _9c;
var _9d;
var _9e=function(_9f,_a0){
if(_99!=_9f){
_99=_9f;
if(!_a0){
_a1();
}
}
if(!_2.Util.IE||_99!="moving"){
_9c=_1.setTimeout(_a2,1);
}else{
_9d=null;
}
};
var _a2=function(){
_9d=new _2.textareaState(_94);
_9b.tick();
_9c=undefined;
};
this.setCommandMode=function(){
_99="command";
_a1();
_9c=_1.setTimeout(_a2,0);
};
this.canUndo=function(){
return _98>1;
};
this.canRedo=function(){
if(_97[_98+1]){
return true;
}
return false;
};
this.undo=function(){
if(_96.canUndo()){
if(_9a){
_9a.restore();
_9a=null;
}else{
_97[_98]=new _2.textareaState(_94);
_97[--_98].restore();
if(_95){
_95();
}
}
}
_99="none";
_94.focus();
_a2();
};
this.redo=function(){
if(_96.canRedo()){
_97[++_98].restore();
if(_95){
_95();
}
}
_99="none";
_94.focus();
_a2();
};
var _a1=function(){
var _a3=_9d||new _2.textareaState(_94);
if(!_a3){
return false;
}
if(_99=="moving"){
if(!_9a){
_9a=_a3;
}
return;
}
if(_9a){
if(_97[_98-1].text!=_9a.text){
_97[_98++]=_9a;
}
_9a=null;
}
_97[_98++]=_a3;
_97[_98+1]=null;
if(_95){
_95();
}
};
var _a4=function(_a5){
var _a6=false;
if(_a5.ctrlKey||_a5.metaKey){
var _a7=(_a5.charCode||_a5.keyCode)|96;
var _a8=String.fromCharCode(_a7);
switch(_a8){
case "y":
_96.redo();
_a6=true;
break;
case "z":
if(!_a5.shiftKey){
_96.undo();
}else{
_96.redo();
}
_a6=true;
break;
}
}
if(_a6){
if(_a5.preventDefault){
_a5.preventDefault();
}
if(_1.event){
_1.event.returnValue=false;
}
return;
}
};
var _a9=function(_aa){
if(!_aa.ctrlKey&&!_aa.metaKey){
var _ab=_aa.keyCode;
if((_ab>=33&&_ab<=40)||(_ab>=63232&&_ab<=63235)){
_9e("moving");
}else{
if(_ab==8||_ab==46||_ab==127){
_9e("deleting");
}else{
if(_ab==13){
_9e("newlines");
}else{
if(_ab==27){
_9e("escape");
}else{
if((_ab<16||_ab>20)&&_ab!=91){
_9e("typing");
}
}
}
}
}
}
};
var _ac=function(){
_6.addEvent(_94,"keypress",function(_ad){
if((_ad.ctrlKey||_ad.metaKey)&&(_ad.keyCode==89||_ad.keyCode==90)){
_ad.preventDefault();
}
});
var _ae=function(){
if(_2.Util.IE||(_9d&&_9d.text!=_94.value)){
if(_9c==undefined){
_99="paste";
_a1();
_a2();
}
}
};
_9b=new _2.inputPoller(_94,_ae,100);
_6.addEvent(_94,"keydown",_a4);
_6.addEvent(_94,"keydown",_a9);
_6.addEvent(_94,"mousedown",function(){
_9e("moving");
});
_94.onpaste=_ae;
_94.ondrop=_ae;
};
var _af=function(){
_ac();
_a2();
_a1();
};
this.destroy=function(){
if(_9b){
_9b.destroy();
}
};
_af();
};
_2.editor=function(_b0,_b1){
if(!_b1){
_b1=function(){
};
}
var _b2=28;
var _b3=4076;
var _b4=0;
var _b5,_b6;
var _b7=this;
var _b8,_b9;
var _ba,_bb,_bc;
var _bd,_be,_bf;
var _c0=[];
var _c1=function(_c2){
if(_bd){
_bd.setCommandMode();
}
var _c3=new _2.textareaState(_b0);
if(!_c3){
return;
}
var _c4=_c3.getChunks();
var _c5=function(){
_b0.focus();
if(_c4){
_c3.setChunks(_c4);
}
_c3.restore();
_b1();
};
var _c6=_c2(_c4,_c5);
if(!_c6){
_c5();
}
};
var _c7=function(_c8){
_b0.focus();
if(_c8.textOp){
_c1(_c8.textOp);
}
if(_c8.execute){
_c8.execute(_b7);
}
};
var _c9=function(_ca,_cb){
var _cc=_ca.style;
if(_cb){
_cc.opacity="1.0";
_cc.KHTMLOpacity="1.0";
if(_2.Util.newIE){
_cc.filter="";
}
if(_2.Util.oldIE){
_cc.filter="chroma(color=fuchsia)";
}
_cc.cursor="pointer";
_ca.onmouseover=function(){
_cc.backgroundColor="lightblue";
_cc.border="1px solid blue";
};
_ca.onmouseout=function(){
_cc.backgroundColor="";
_cc.border="1px solid transparent";
if(_2.Util.oldIE){
_cc.borderColor="fuchsia";
_cc.filter="chroma(color=fuchsia)"+_cc.filter;
}
};
}else{
_cc.opacity="0.4";
_cc.KHTMLOpacity="0.4";
if(_2.Util.oldIE){
_cc.filter="chroma(color=fuchsia) alpha(opacity=40)";
}
if(_2.Util.newIE){
_cc.filter="alpha(opacity=40)";
}
_cc.cursor="";
_cc.backgroundColor="";
if(_ca.onmouseout){
_ca.onmouseout();
}
_ca.onmouseover=_ca.onmouseout=null;
}
};
var _cd=function(_ce){
_ce&&_c0.push(_ce);
};
var _cf=function(){
_c0.push("|");
};
var _d0=function(){
var _d1=_6.createImage("images/separator.png",20,20);
_d1.style.padding="4px";
_d1.style.paddingTop="0px";
_b9.appendChild(_d1);
};
var _d2=function(_d3){
if(_d3.image){
var _d4=_6.createImage(_d3.image,16,16);
_d4.border=0;
if(_d3.description){
var _d5=_d3.description;
if(_d3.key){
var _d6=" Ctrl+";
_d5+=_d6+_d3.key.toUpperCase();
}
_d4.title=_d5;
}
_c9(_d4,true);
var _d7=_d4.style;
_d7.margin="0px";
_d7.padding="1px";
_d7.marginTop="7px";
_d7.marginBottom="5px";
_d4.onmouseout();
var _d8=_d4;
_d8.onclick=function(){
if(_d8.onmouseout){
_d8.onmouseout();
}
_c7(_d3);
return false;
};
_b9.appendChild(_d8);
return _d8;
}
return;
};
var _d9=function(){
for(var _da in _c0){
if(_c0[_da]=="|"){
_d0();
}else{
_d2(_c0[_da]);
}
}
};
var _db=function(){
if(_bd){
_c9(_be,_bd.canUndo());
_c9(_bf,_bd.canRedo());
}
};
var _dc=function(){
if(_b0.offsetParent){
_ba=_6.makeElement("div");
var _dd=_ba.style;
_dd.visibility="hidden";
_dd.top=_dd.left=_dd.width="0px";
_dd.display="inline";
_dd.cssFloat="left";
_dd.overflow="visible";
_dd.opacity="0.999";
_b8.style.position="absolute";
_ba.appendChild(_b8);
_b0.style.marginTop="";
var _de=_7.getTop(_b0);
_b0.style.marginTop="0";
var _df=_7.getTop(_b0);
_b4=_de-_df;
_e0();
_b0.parentNode.insertBefore(_ba,_b0);
_e1();
_6.skin(_b8,_2.basePath+"images/bg.png",_b2,_b3);
_dd.visibility="visible";
return true;
}
return false;
};
var _e2=function(){
var _e3=_2.wmd_env.buttons.split(/\s+/);
for(var _e4 in _e3){
switch(_e3[_e4]){
case "|":
_cf();
break;
case "bold":
_cd(_8.bold);
break;
case "italic":
_cd(_8.italic);
break;
case "link":
_cd(_8.link);
break;
}
if(_2.full){
switch(_e3[_e4]){
case "blockquote":
_cd(_8.blockquote);
break;
case "code":
_cd(_8.code);
break;
case "image":
_cd(_8.img);
break;
case "ol":
_cd(_8.ol);
break;
case "ul":
_cd(_8.ul);
break;
case "heading":
_cd(_8.h1);
break;
case "hr":
_cd(_8.hr);
break;
}
}
}
return;
};
var _e5=function(){
if(/\?noundo/.test(_3.location.href)){
_2.nativeUndo=true;
}
if(!_2.nativeUndo){
_bd=new _2.undoManager(_b0,function(){
_b1();
_db();
});
}
var _e6=_b0.parentNode;
_b8=_6.makeElement("div");
_b8.style.display="block";
_b8.style.zIndex=100;
if(!_2.full){
_b8.title+="\n(Free Version)";
}
_b8.unselectable="on";
_b8.onclick=function(){
_b0.focus();
};
_b9=_6.makeElement("span");
var _e7=_b9.style;
_e7.height="auto";
_e7.paddingBottom="2px";
_e7.lineHeight="0";
_e7.paddingLeft="15px";
_e7.paddingRight="65px";
_e7.display="block";
_e7.position="absolute";
_b9.unselectable="on";
_b8.appendChild(_b9);
_cd(_8.autoindent);
var _e8=_6.createImage("images/bg.png");
var _e9=_6.createImage("images/bg-fill.png");
_e2();
_d9();
if(_bd){
_d0();
_be=_d2(_8.undo);
_bf=_d2(_8.redo);
var _ea=_5.platform.toLowerCase();
if(/win/.test(_ea)){
_be.title+=" - Ctrl+Z";
_bf.title+=" - Ctrl+Y";
}else{
if(/mac/.test(_ea)){
_be.title+=" - Ctrl+Z";
_bf.title+=" - Ctrl+Shift+Z";
}else{
_be.title+=" - Ctrl+Z";
_bf.title+=" - Ctrl+Shift+Z";
}
}
}
var _eb="keydown";
if(_5.userAgent.indexOf("Opera")!=-1){
_eb="keypress";
}
_6.addEvent(_b0,_eb,function(_ec){
var _ed=false;
if(_ec.ctrlKey||_ec.metaKey){
var _ee=(_ec.charCode||_ec.keyCode);
var _ef=String.fromCharCode(_ee).toLowerCase();
for(var _f0 in _c0){
var _f1=_c0[_f0];
if(_f1.key&&_ef==_f1.key||_f1.keyCode&&_ec.keyCode==_f1.keyCode){
_c7(_f1);
_ed=true;
}
}
}
if(_ed){
if(_ec.preventDefault){
_ec.preventDefault();
}
if(_1.event){
_1.event.returnValue=false;
}
}
});
_6.addEvent(_b0,"keyup",function(_f2){
if(_f2.shiftKey&&!_f2.ctrlKey&&!_f2.metaKey){
var _f3=(_f2.charCode||_f2.keyCode);
switch(_f3){
case 13:
_c7(_8.autoindent);
break;
}
}
});
if(!_dc()){
_bc=_1.setInterval(function(){
if(_dc()){
_1.clearInterval(_bc);
}
},100);
}
_6.addEvent(_1,"resize",_e1);
_bb=_1.setInterval(_e1,100);
if(_b0.form){
var _f4=_b0.form.onsubmit;
_b0.form.onsubmit=function(){
_f5();
if(_f4){
return _f4.apply(this,arguments);
}
};
}
_db();
};
var _f5=function(){
if(_2.showdown){
var _f6=new _2.showdown.converter();
}
var _f7=_b0.value;
var _f8=function(){
_b0.value=_f7;
};
_f7=_6.escapeUnderscores(_f7);
if(!/markdown/.test(_2.wmd_env.output.toLowerCase())){
if(_f6){
_b0.value=_f6.makeHtml(_f7);
_1.setTimeout(_f8,0);
}
}
return true;
};
var _e0=function(){
var _f9=_6.makeElement("div");
var _fa=_f9.style;
_fa.paddingRight="15px";
_fa.height="100%";
_fa.display="block";
_fa.position="absolute";
_fa.right="0";
_f9.unselectable="on";
var _fb=_6.makeElement("a");
_fa=_fb.style;
_fa.position="absolute";
_fa.right="10px";
_fa.top="5px";
_fa.display="inline";
_fa.width="50px";
_fa.height="25px";
_fb.href="http://www.wmd-editor.com/";
_fb.target="_blank";
_fb.title="WMD: The Wysiwym Markdown Editor";
var _fc=_6.createImage("images/wmd.png");
var _fd=_6.createImage("images/wmd-on.png");
_fb.appendChild(_fc);
_fb.onmouseover=function(){
_6.setImage(_fc,"images/wmd-on.png");
_fb.style.cursor="pointer";
};
_fb.onmouseout=function(){
_6.setImage(_fc,"images/wmd.png");
};
_b8.appendChild(_fb);
};
var _e1=function(){
if(!_6.elementOk(_b0)){
_b8.style.display="none";
return;
}
if(_b8.style.display=="none"){
_b8.style.display="block";
}
var _fe=_7.getWidth(_b0);
var _ff=_7.getHeight(_b0);
var _100=_7.getLeft(_b0);
if(_b8.style.width==_fe+"px"&&_b5==_ff&&_b6==_100){
if(_7.getTop(_b8)<_7.getTop(_b0)){
return;
}
}
_b5=_ff;
_b6=_100;
var _101=100;
_b8.style.width=Math.max(_fe,_101)+"px";
var root=_b8.offsetParent;
var _103=_7.getHeight(_b9);
var _104=_103-_b2+"px";
_b8.style.height=_104;
if(_6.fillers){
_6.fillers[0].style.height=_6.fillers[1].style.height=_104;
}
var _105=3;
_b0.style.marginTop=_103+_105+_b4+"px";
var _106=_7.getTop(_b0);
var _100=_7.getLeft(_b0);
_7.setTop(root,_106-_103-_105);
_7.setLeft(root,_100);
_b8.style.opacity=_b8.style.opacity||0.999;
return;
};
this.undo=function(){
if(_bd){
_bd.undo();
}
};
this.redo=function(){
if(_bd){
_bd.redo();
}
};
var init=function(){
_e5();
};
this.destroy=function(){
if(_bd){
_bd.destroy();
}
if(_ba.parentNode){
_ba.parentNode.removeChild(_ba);
}
if(_b0){
_b0.style.marginTop="";
}
_1.clearInterval(_bb);
_1.clearInterval(_bc);
};
init();
};
_2.textareaState=function(_108){
var _109=this;
var _10a=function(_10b){
if(_6.getStyle(_108,"display")=="none"){
return;
}
var _10c=_5.userAgent.indexOf("Opera")!=-1;
if(_10b.selectionStart!=undefined&&!_10c){
_10b.focus();
_10b.selectionStart=_109.start;
_10b.selectionEnd=_109.end;
_10b.scrollTop=_109.scrollTop;
}else{
if(_3.selection){
if(_3.activeElement&&_3.activeElement!=_108){
return;
}
_10b.focus();
var _10d=_10b.createTextRange();
_10d.moveStart("character",-_10b.value.length);
_10d.moveEnd("character",-_10b.value.length);
_10d.moveEnd("character",_109.end);
_10d.moveStart("character",_109.start);
_10d.select();
}
}
};
this.init=function(_10e){
if(_10e){
_108=_10e;
}
if(_6.getStyle(_108,"display")=="none"){
return;
}
_10f(_108);
_109.scrollTop=_108.scrollTop;
if(!_109.text&&_108.selectionStart||_108.selectionStart=="0"){
_109.text=_108.value;
}
};
var _110=function(_111){
_111=_111.replace(/\r\n/g,"\n");
_111=_111.replace(/\r/g,"\n");
return _111;
};
var _10f=function(){
if(_108.selectionStart||_108.selectionStart=="0"){
_109.start=_108.selectionStart;
_109.end=_108.selectionEnd;
}else{
if(_3.selection){
_109.text=_110(_108.value);
var _112=_3.selection.createRange();
var _113=_110(_112.text);
var _114="\x07";
var _115=_114+_113+_114;
_112.text=_115;
var _116=_110(_108.value);
_112.moveStart("character",-_115.length);
_112.text=_113;
_109.start=_116.indexOf(_114);
_109.end=_116.lastIndexOf(_114)-_114.length;
var _117=_109.text.length-_110(_108.value).length;
if(_117){
_112.moveStart("character",-_113.length);
while(_117--){
_113+="\n";
_109.end+=1;
}
_112.text=_113;
}
_10a(_108);
}
}
return _109;
};
this.restore=function(_118){
if(!_118){
_118=_108;
}
if(_109.text!=undefined&&_109.text!=_118.value){
_118.value=_109.text;
}
_10a(_118,_109);
_118.scrollTop=_109.scrollTop;
};
this.getChunks=function(){
var _119=new _2.Chunks();
_119.before=_110(_109.text.substring(0,_109.start));
_119.startTag="";
_119.selection=_110(_109.text.substring(_109.start,_109.end));
_119.endTag="";
_119.after=_110(_109.text.substring(_109.end));
_119.scrollTop=_109.scrollTop;
return _119;
};
this.setChunks=function(_11a){
_11a.before=_11a.before+_11a.startTag;
_11a.after=_11a.endTag+_11a.after;
var _11b=_5.userAgent.indexOf("Opera")!=-1;
if(_11b){
_11a.before=_11a.before.replace(/\n/g,"\r\n");
_11a.selection=_11a.selection.replace(/\n/g,"\r\n");
_11a.after=_11a.after.replace(/\n/g,"\r\n");
}
_109.start=_11a.before.length;
_109.end=_11a.before.length+_11a.selection.length;
_109.text=_11a.before+_11a.selection+_11a.after;
_109.scrollTop=_11a.scrollTop;
};
this.init();
};
_2.Chunks=function(){
};
_2.Chunks.prototype.findTags=function(_11c,_11d){
var _11e,_11f;
var _120=this;
if(_11c){
_11f=_6.regexToString(_11c);
_11e=new _4(_11f.expression+"$",_11f.flags);
this.before=this.before.replace(_11e,function(_121){
_120.startTag=_120.startTag+_121;
return "";
});
_11e=new _4("^"+_11f.expression,_11f.flags);
this.selection=this.selection.replace(_11e,function(_122){
_120.startTag=_120.startTag+_122;
return "";
});
}
if(_11d){
_11f=_6.regexToString(_11d);
_11e=new _4(_11f.expression+"$",_11f.flags);
this.selection=this.selection.replace(_11e,function(_123){
_120.endTag=_123+_120.endTag;
return "";
});
_11e=new _4("^"+_11f.expression,_11f.flags);
this.after=this.after.replace(_11e,function(_124){
_120.endTag=_124+_120.endTag;
return "";
});
}
};
_2.Chunks.prototype.trimWhitespace=function(_125){
this.selection=this.selection.replace(/^(\s*)/,"");
if(!_125){
this.before+=_4.$1;
}
this.selection=this.selection.replace(/(\s*)$/,"");
if(!_125){
this.after=_4.$1+this.after;
}
};
_2.Chunks.prototype.skipLines=function(_126,_127,_128){
if(_126==undefined){
_126=1;
}
if(_127==undefined){
_127=1;
}
_126++;
_127++;
var _129,_12a;
this.selection=this.selection.replace(/(^\n*)/,"");
this.startTag=this.startTag+_4.$1;
this.selection=this.selection.replace(/(\n*$)/,"");
this.endTag=this.endTag+_4.$1;
this.startTag=this.startTag.replace(/(^\n*)/,"");
this.before=this.before+_4.$1;
this.endTag=this.endTag.replace(/(\n*$)/,"");
this.after=this.after+_4.$1;
if(this.before){
_129=_12a="";
while(_126--){
_129+="\\n?";
_12a+="\n";
}
if(_128){
_129="\\n*";
}
this.before=this.before.replace(new _4(_129+"$",""),_12a);
}
if(this.after){
_129=_12a="";
while(_127--){
_129+="\\n?";
_12a+="\n";
}
if(_128){
_129="\\n*";
}
this.after=this.after.replace(new _4(_129,""),_12a);
}
};
_8.prefixes="(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
_8.unwrap=function(_12b){
var _12c=new _4("([^\\n])\\n(?!(\\n|"+_8.prefixes+"))","g");
_12b.selection=_12b.selection.replace(_12c,"$1 $2");
};
_8.wrap=function(_12d,len){
_8.unwrap(_12d);
var _12f=new _4("(.{1,"+len+"})( +|$\\n?)","gm");
_12d.selection=_12d.selection.replace(_12f,function(_130,line){
if(new _4("^"+_8.prefixes,"").test(_130)){
return _130;
}
return line+"\n";
});
_12d.selection=_12d.selection.replace(/\s+$/,"");
};
_8.doBold=function(_132){
return _8.doBorI(_132,2,"strong text");
};
_8.doItalic=function(_133){
return _8.doBorI(_133,1,"emphasized text");
};
_8.doBorI=function(_134,_135,_136){
_134.trimWhitespace();
_134.selection=_134.selection.replace(/\n{2,}/g,"\n");
_134.before.search(/(\**$)/);
var _137=_4.$1;
_134.after.search(/(^\**)/);
var _138=_4.$1;
var _139=Math.min(_137.length,_138.length);
if((_139>=_135)&&(_139!=2||_135!=1)){
_134.before=_134.before.replace(_4("[*]{"+_135+"}$",""),"");
_134.after=_134.after.replace(_4("^[*]{"+_135+"}",""),"");
return;
}
if(!_134.selection&&_138){
_134.after=_134.after.replace(/^([*_]*)/,"");
_134.before=_134.before.replace(/(\s?)$/,"");
var _13a=_4.$1;
_134.before=_134.before+_138+_13a;
return;
}
if(!_134.selection&&!_138){
_134.selection=_136;
}
var _13b=_135<=1?"*":"**";
_134.before=_134.before+_13b;
_134.after=_13b+_134.after;
};
_8.stripLinkDefs=function(_13c,_13d){
_13c=_13c.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,function(_13e,id,_140,_141,_142){
_13d[id]=_13e.replace(/\s*$/,"");
if(_141){
_13d[id]=_13e.replace(/["(](.+?)[")]$/,"");
return _141+_142;
}
return "";
});
return _13c;
};
_8.addLinkDef=function(_143,_144){
var _145=0;
var _146={};
_143.before=_8.stripLinkDefs(_143.before,_146);
_143.selection=_8.stripLinkDefs(_143.selection,_146);
_143.after=_8.stripLinkDefs(_143.after,_146);
var _147="";
var _148=/(\[(?:\[[^\]]*\]|[^\[\]])*\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
var _149=function(def){
_145++;
def=def.replace(/^[ ]{0,3}\[(\d+)\]:/," ["+_145+"]:");
_147+="\n"+def;
};
var _14b=function(_14c,_14d,id,end){
if(_146[id]){
_149(_146[id]);
return _14d+_145+end;
}
return _14c;
};
_143.before=_143.before.replace(_148,_14b);
if(_144){
_149(_144);
}else{
_143.selection=_143.selection.replace(_148,_14b);
}
var _150=_145;
_143.after=_143.after.replace(_148,_14b);
if(_143.after){
_143.after=_143.after.replace(/\n*$/,"");
}
if(!_143.after){
_143.selection=_143.selection.replace(/\n*$/,"");
}
_143.after+="\n\n"+_147;
return _150;
};
_8.doLinkOrImage=function(_151,_152,_153){
_151.trimWhitespace();
_151.findTags(/\s*!?\[/,/\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
if(_151.endTag.length>1){
_151.startTag=_151.startTag.replace(/!?\[/,"");
_151.endTag="";
_8.addLinkDef(_151,null);
}else{
if(/\n\n/.test(_151.selection)){
_8.addLinkDef(_151,null);
return;
}
var _154;
var _155=function(_156){
if(_156!=null){
_151.startTag=_151.endTag="";
var _157=" [999]: "+_156;
var num=_8.addLinkDef(_151,_157);
_151.startTag=_152?"![":"[";
_151.endTag="]["+num+"]";
if(!_151.selection){
if(_152){
_151.selection="alt text";
}else{
_151.selection="link text";
}
}
}
_153();
};
if(_152){
_154=_6.prompt("<p style='margin-top: 0px'><b>Enter the image URL.</b></p><p>You can also add a title, which will be displayed as a tool tip.</p><p>Example:<br />http://wmd-editor.com/images/cloud1.jpg \"Optional title\"</p>","http://",_155);
}else{
_154=_6.prompt("<p style='margin-top: 0px'><b>Enter the web address.</b></p><p>You can also add a title, which will be displayed as a tool tip.</p><p>Example:<br />http://wmd-editor.com/ \"Optional title\"</p>","http://",_155);
}
return true;
}
};
_8.bold={};
_8.bold.description="Strong <strong>";
_8.bold.image="images/bold.png";
_8.bold.key="b";
_8.bold.textOp=_8.doBold;
_8.italic={};
_8.italic.description="Emphasis <em>";
_8.italic.image="images/italic.png";
_8.italic.key="i";
_8.italic.textOp=_8.doItalic;
_8.link={};
_8.link.description="Hyperlink <a>";
_8.link.image="images/link.png";
_8.link.key="l";
_8.link.textOp=function(_159,_15a){
return _8.doLinkOrImage(_159,false,_15a);
};
_8.undo={};
_8.undo.description="Undo";
_8.undo.image="images/undo.png";
_8.undo.execute=function(_15b){
_15b.undo();
};
_8.redo={};
_8.redo.description="Redo";
_8.redo.image="images/redo.png";
_8.redo.execute=function(_15c){
_15c.redo();
};
_6.findPanes=function(_15d){
_15d.preview=_15d.preview||_6.getElementsByClass("wmd-preview",null,"div")[0];
_15d.output=_15d.output||_6.getElementsByClass("wmd-output",null,"textarea")[0];
_15d.output=_15d.output||_6.getElementsByClass("wmd-output",null,"div")[0];
if(!_15d.input){
var _15e=-1;
var _15f=_3.getElementsByTagName("textarea");
//var _15f=_3.getElementById("markdown");
for(var _160=0;_160<_15f.length;_160++){
var _161=_15f[_160];
if(_161!=_15d.output&&!/wmd-ignore/.test(_161.className.toLowerCase())){
_15d.input=_161;
break;
}
}
}
return _15d;
};
_6.makeAPI=function(){
_2.wmd={};
_2.wmd.editor=_2.editor;
_2.wmd.previewManager=_2.previewManager;
};
_6.startEditor=function(){
if(_2.wmd_env.autostart==false){
_2.editorInit();
_6.makeAPI();
return;
}
var _162={};
var _163,_164;
var _165=function(){
try{
var _166=_6.cloneObject(_162);
_6.findPanes(_162);
if(!_6.objectsEqual(_166,_162)&&_162.input){
if(!_163){
_2.editorInit();
var _167;
if(_2.previewManager!=undefined){
_164=new _2.previewManager(_162);
_167=_164.refresh;
}
_163=new _2.editor(_162.input,_167);
}else{
if(_164){
_164.refresh(true);
}
}
}
}
catch(e){
}
};
_6.addEvent(_1,"load",_165);
var _168=_1.setInterval(_165,100);
};
_2.previewManager=function(_169){
var _16a=this;
var _16b,_16c;
var _16d,_16e;
var _16f,_170;
var _171=3000;
var _172="delayed";
var _173=function(_174,_175){
_6.addEvent(_174,"input",_175);
_174.onpaste=_175;
_174.ondrop=_175;
_6.addEvent(_1,"keypress",_175);
_6.addEvent(_174,"keypress",_175);
_6.addEvent(_174,"keydown",_175);
_16c=new _2.inputPoller(_174,_175);
};
var _176=function(){
var _177=0;
if(_1.innerHeight){
_177=_1.pageYOffset;
}else{
if(_3.documentElement&&_3.documentElement.scrollTop){
_177=_3.documentElement.scrollTop;
}else{
if(_3.body){
_177=_3.body.scrollTop;
}
}
}
return _177;
};
var _178=function(){
if(!_169.preview&&!_169.output){
return;
}
var text=_169.input.value;
if(text&&text==_16f){
return;
}else{
_16f=text;
}
var _17a=new Date().getTime();
if(!_16b&&_2.showdown){
_16b=new _2.showdown.converter();
}
text=_6.escapeUnderscores(text);
if(_16b){
text=_16b.makeHtml(text);
}
var _17b=new Date().getTime();
_16e=_17b-_17a;
_17c(text);
_170=text;
};
var _17d=function(){
if(_16d){
_1.clearTimeout(_16d);
_16d=undefined;
}
if(_172!="manual"){
var _17e=0;
if(_172=="delayed"){
_17e=_16e;
}
if(_17e>_171){
_17e=_171;
}
_16d=_1.setTimeout(_178,_17e);
}
};
var _17f;
var _180;
var _181=function(_182){
if(_182.scrollHeight<=_182.clientHeight){
return 1;
}
return _182.scrollTop/(_182.scrollHeight-_182.clientHeight);
};
var _183=function(_184,_185){
_184.scrollTop=(_184.scrollHeight-_184.clientHeight)*_185;
};
var _186=function(){
if(_169.preview){
_17f=_181(_169.preview);
}
if(_169.output){
_180=_181(_169.output);
}
};
var _187=function(){
if(_169.preview){
_169.preview.scrollTop=_169.preview.scrollTop;
_183(_169.preview,_17f);
}
if(_169.output){
_183(_169.output,_180);
}
};
this.refresh=function(_188){
if(_188){
_16f="";
_178();
}else{
_17d();
}
};
this.processingTime=function(){
return _16e;
};
this.output=function(){
return _170;
};
this.setUpdateMode=function(_189){
_172=_189;
_16a.refresh();
};
var _18a=true;
var _17c=function(text){
_186();
var _18c=_7.getTop(_169.input)-_176();
if(_169.output){
if(_169.output.value!=undefined){
_169.output.value=text;
_169.output.readOnly=true;
}else{
var _18d=text.replace(/&/g,"&");
_18d=_18d.replace(/</g,"<");
_169.output.innerHTML="<pre><code>"+_18d+"</code></pre>";
}
}
if(_169.preview){
_169.preview.innerHTML=text;
}
_187();
if(_18a){
_18a=false;
return;
}
var _18e=_7.getTop(_169.input)-_176();
if(_5.userAgent.indexOf("MSIE")!=-1){
_1.setTimeout(function(){
_1.scrollBy(0,_18e-_18c);
},0);
}else{
_1.scrollBy(0,_18e-_18c);
}
};
var init=function(){
_173(_169.input,_17d);
_178();
if(_169.preview){
_169.preview.scrollTop=0;
}
if(_169.output){
_169.output.scrollTop=0;
}
};
this.destroy=function(){
if(_16c){
_16c.destroy();
}
};
init();
};
};
if(Attacklab.fileLoaded){
Attacklab.fileLoaded("wmd-base.js");
}
|
// Unit test for a.mem
QUnit.module('core/mem.js', {
_beforeStore: [],
setup: function() {
this._beforeStore = a.keys(a.mem.list());
},
teardown: function() {
var current = a.keys(a.mem.list());
var difference = a.difference(current, this._beforeStore);
a.each(difference, function(element) {
a.mem.remove(element);
});
this._beforeStore = null;
}
});
// Test mem system
QUnit.test('a.mem.default', function (assert) {
assert.expect(3);
a.mem.set('some-test', 'hello');
assert.strictEqual(a.mem.get('some-test'), 'hello');
a.mem.set('some-test', 'second');
assert.strictEqual(a.mem.get('some-test'), 'second');
a.mem.remove('some-test');
assert.strictEqual(a.mem.get('some-test'), null);
});
// Test mem duplicate system
QUnit.test('a.mem.instance', function (assert) {
assert.expect(6);
var instance = a.mem.getInstance('some.test');
instance.set('inside', 'ok');
assert.strictEqual(a.mem.get('some.test.inside'), 'ok');
assert.strictEqual(instance.get('inside'), 'ok');
instance.set('inside', 'second');
assert.strictEqual(a.mem.get('some.test.inside'), 'second');
assert.strictEqual(instance.get('inside'), 'second');
instance.remove('inside');
assert.strictEqual(a.mem.get('some.test.inside'), null);
assert.strictEqual(instance.get('inside'), null);
});
// Testing list function
QUnit.test('a.mem.list', function (assert) {
assert.expect(4);
a.mem.set('tempList', 'ok');
var instance = a.mem.getInstance('list.test');
instance.set('t', 'ok');
var list1 = a.mem.list(),
list2 = instance.list();
assert.strictEqual(list2.t, 'ok');
assert.strictEqual(list1.tempList, 'ok', 'Test global list');
assert.strictEqual(list1['list.test.t'], 'ok', 'Test instance list');
assert.strictEqual(list2.tempList, undefined,
'Test instance does not have full list');
// Cleaning elements
instance.remove('t');
a.mem.remove('tempList');
});
// Dual instance does not create any bug
QUnit.test('a.mem.dual-instance', function (assert) {
assert.expect(2);
var instance1 = a.mem.getInstance('qunit.t1'),
instance2 = a.mem.getInstance('qunit.t2');
instance1.set('val1', 'val1');
instance2.set('val2', 'val2');
var list1 = instance1.list(),
list2 = instance2.list();
assert.strictEqual(list1.val1, 'val1', 'Test value 1');
assert.strictEqual(list2.val2, 'val2', 'Test value 2');
}); |
/* @flow */
jest.mock('../../utils', () => ({ requireModule: v => require(v) }));
jest.mock(
'cwd/src/gluestick.config.js',
() => config => ({ ...config, buildStaticPath: 'test' }),
{ virtual: true },
);
const compileGluestickConfig = require('../compileGlueStickConfig');
const defaultConfig = require('../defaults/glueStickConfig');
const logger = require('../../__tests__/mocks/context').commandApi.getLogger();
describe('config/compileGluestickConfig', () => {
it('should return default config', () => {
expect(compileGluestickConfig(logger, [])).toEqual(defaultConfig);
});
it('should throw error', () => {
const errorMessage = 'Invalid plugins argument';
expect(() => {
// $FlowIgnore
compileGluestickConfig();
}).toThrowError(errorMessage);
expect(() => {
// $FlowIgnore
compileGluestickConfig(null);
}).toThrowError(errorMessage);
expect(() => {
// $FlowIgnore
compileGluestickConfig('string');
}).toThrowError(errorMessage);
expect(() => {
// $FlowIgnore
compileGluestickConfig(1);
}).toThrowError(errorMessage);
expect(() => {
// $FlowIgnore
compileGluestickConfig({});
}).toThrowError(errorMessage);
});
it('should return overwriten config', () => {
const originalProcessCwd = process.cwd.bind(process);
// $FlowIgnore
process.cwd = () => 'cwd';
expect(
compileGluestickConfig(logger, [
// $FlowIgnore
{
name: 'testPlugin',
postOverwrites: {
gluestickConfig: config => {
return { ...config, protocol: 'https' };
},
},
},
// $FlowIgnore
{
name: 'testPlugin',
postOverwrites: {
gluestickConfig: config => {
return { ...config, host: 'test' };
},
},
},
]),
).toEqual({
...defaultConfig,
protocol: 'https',
host: 'test',
buildStaticPath: 'test',
});
// $FlowIgnore
process.cwd = originalProcessCwd;
});
});
|
/* eslint-disable no-unused-expressions */
const { expect } = require('chai');
const { base, example, orm } = require('feathers-service-tests');
const errors = require('feathers-errors');
const feathers = require('feathers');
const service = require('../lib');
const { hooks, Service } = require('../lib');
const server = require('./test-app');
const { User, Pet, Peeps, CustomPeeps, Post, TextPost } = require('./models');
const _ids = {};
const _petIds = {};
const app = feathers()
.use('/peeps', service({ Model: Peeps, events: [ 'testing' ] }))
.use('/peeps-customid', service({
id: 'customid',
Model: CustomPeeps,
events: [ 'testing' ]
}))
.use('/people', service({ Model: User, lean: false }))
.use('/pets', service({ Model: Pet, lean: false }))
.use('/people2', service({ Model: User }))
.use('/pets2', service({ Model: Pet }))
.use('/posts', service({ Model: Post, discriminators: [TextPost] }));
const people = app.service('people');
const pets = app.service('pets');
const leanPeople = app.service('people2');
const leanPets = app.service('pets2');
const posts = app.service('posts');
const sortAge = (data) => {
if (Array.isArray(data)) {
// Order is not guaranteed so lets just order by age
data = data.sort((a, b) => {
return a.age < b.age;
});
}
return data;
};
let testApp;
describe('Feathers Mongoose Service', () => {
describe('Requiring', () => {
const lib = require('../lib');
it('exposes the service as a default module', () => {
expect(typeof lib).to.equal('function');
});
it('exposes the Service Constructor', () => {
expect(typeof lib.Service).to.equal('function');
});
it('exposes hooks', () => {
expect(typeof lib.hooks).to.equal('object');
});
});
describe('Importing', () => {
it('exposes the service as a default module', () => {
expect(typeof service).to.equal('function');
});
it('exposes the Service constructor', () => {
// Check by calling the Service constructor without
// any params. It should return an error.
let newService;
try {
newService = new Service();
} catch (e) {
expect(e).to.not.be.undefined;
expect(newService).to.be.undefined;
}
});
it('exposes hooks', () => {
expect(typeof hooks).to.equal('object');
});
});
describe('Initialization', () => {
describe('when missing options', () => {
it('throws an error', () => {
expect(service.bind(null)).to.throw('Mongoose options have to be provided');
});
});
describe('when missing a Model', () => {
it('throws an error', () => {
expect(service.bind(null, { name: 'Test' })).to.throw(/You must provide a Mongoose Model/);
});
});
describe('when missing the id option', () => {
it('sets the default to be _id', () => {
expect(people.id).to.equal('_id');
});
});
describe('when missing the paginate option', () => {
it('sets the default to be {}', () => {
expect(people.paginate).to.deep.equal({});
});
});
describe('when missing the overwrite option', () => {
it('sets the default to be true', () => {
expect(people.overwrite).to.be.true;
});
});
describe('when missing the lean option', () => {
it('sets the default to be false', () => {
expect(people.lean).to.be.false;
});
});
});
describe('insertMany', () => {
afterEach(() => {
return people.remove(null, { query: {} });
});
it('can handles empty arrays', function () {
return people.create([])
.then(data => {
throw new Error('Create should not be successful');
})
.catch(error => {
expect(error.name).to.equal('BadRequest');
expect(error.message).to.equal('Cannot pass empty array to create.');
});
});
it('can return all validation errors', function () {
return people.create([
{
name: 'David',
age: 10
},
{
name: 'Peter',
age: -6
},
{
age: 7
},
{
name: 'Christopher',
age: 5
}
])
.then(sortAge)
.then(data => {
expect(data).to.be.an('array');
expect(data.length).to.equal(2);
expect(data[0].name).to.equal('David');
expect(data[1].name).to.equal('Christopher');
});
});
it('can return duplicate key errors', function (done) {
people.create([
{
name: 'David',
age: 10
}
])
.then(data => {
_ids.David = data[0]._id;
people.create([
{
_id: _ids.David,
name: 'Matt',
age: 20
}
])
.then(data => {
expect(data).to.be.an('array');
expect(data.length).to.equal(0);
done();
})
.catch(done);
})
.catch(done);
});
it('can return combination of duplicate key and validation errors', function (done) {
people.create([
{
name: 'David',
age: 10
}
])
.then(data => {
_ids.David = data[0]._id;
people.create([
{
_id: _ids.David,
name: 'David',
age: 20
},
{
age: 20
},
{
name: 'Peter',
age: 27
}
])
.then(sortAge)
.then(data => {
expect(data.length).to.equal(1);
expect(data[0].name).to.equal('Peter');
done();
})
.catch(done);
})
.catch(done);
});
it('can create with array', function (done) {
people.create([
{
name: 'David',
age: 10
},
{
name: 'Peter',
age: 27
}
])
.then(sortAge)
.then(data => {
expect(data.length).to.equal(2);
expect(data[0].name).to.equal('Peter');
expect(data[1].name).to.equal('David');
done();
})
.catch(done);
});
});
describe('Common functionality', () => {
beforeEach(() => {
// FIXME (EK): This is shit. We should be loading fixtures
// using the raw driver not our system under test
return pets.create({type: 'dog', name: 'Rufus', gender: 'Unknown'}).then(pet => {
_petIds.Rufus = pet._id;
return people.create({
name: 'Doug',
age: 32,
pets: [pet._id]
}).then(user => {
_ids.Doug = user._id;
});
});
});
afterEach(() => {
return pets.remove(null, { query: {} }).then(() =>
people.remove(null, { query: {} })
);
});
it('can $select with a String', function (done) {
var params = {
query: {
name: 'Rufus',
$select: '+gender'
}
};
pets.find(params).then(data => {
expect(data[0].gender).to.equal('Unknown');
done();
});
});
it('can $select with an Array', function (done) {
var params = {
query: {
name: 'Rufus',
$select: ['gender']
}
};
pets.find(params).then(data => {
expect(data[0].gender).to.equal('Unknown');
done();
});
});
it('can $select with an Object', function (done) {
var params = {
query: {
name: 'Rufus',
$select: {'gender': true}
}
};
pets.find(params).then(data => {
expect(data[0].gender).to.equal('Unknown');
done();
});
});
it('can $populate with find', function (done) {
var params = {
query: {
name: 'Doug',
$populate: ['pets']
}
};
people.find(params).then(data => {
expect(data[0].pets[0].name).to.equal('Rufus');
done();
});
});
it('can $populate with get', function (done) {
var params = {
query: {
$populate: ['pets']
}
};
people.get(_ids.Doug, params).then(data => {
expect(data.pets[0].name).to.equal('Rufus');
done();
}).catch(done);
});
it('can patch a mongoose model', function (done) {
people.get(_ids.Doug).then(dougModel => {
people.patch(_ids.Doug, dougModel).then(data => {
expect(data.name).to.equal('Doug');
done();
}).catch(done);
}).catch(done);
});
it('can patch a mongoose model', function (done) {
people.get(_ids.Doug).then(dougModel => {
people.update(_ids.Doug, dougModel).then(data => {
expect(data.name).to.equal('Doug');
done();
}).catch(done);
}).catch(done);
});
it('can upsert with patch', function (done) {
var data = { name: 'Henry', age: 300 };
var params = {
mongoose: { upsert: true },
query: { name: 'Henry' }
};
people.patch(null, data, params).then(data => {
expect(Array.isArray(data)).to.equal(true);
var henry = data[0];
expect(henry.name).to.equal('Henry');
done();
}).catch(done);
});
it('can $populate with update', function (done) {
var params = {
query: {
$populate: ['pets']
}
};
people.get(_ids.Doug).then(doug => {
var newDoug = doug.toObject();
newDoug.name = 'Bob';
people.update(_ids.Doug, newDoug, params).then(data => {
expect(data.name).to.equal('Bob');
expect(data.pets[0].name).to.equal('Rufus');
done();
}).catch(done);
}).catch(done);
});
it('can $populate with patch', function (done) {
var params = {
query: {
$populate: ['pets']
}
};
people.patch(_ids.Doug, { name: 'Bob' }, params).then(data => {
expect(data.name).to.equal('Bob');
expect(data.pets[0].name).to.equal('Rufus');
done();
}).catch(done);
});
it('can $push an item onto an array with update', function (done) {
pets.create({ type: 'cat', name: 'Margeaux' }).then(margeaux => {
people.update(_ids.Doug, { $push: { pets: margeaux } })
.then(() => {
var params = {
query: {
$populate: ['pets']
}
};
people.get(_ids.Doug, params).then(data => {
expect(data.pets[1].name).to.equal('Margeaux');
done();
}).catch(done);
}).catch(done);
}).catch(done);
});
it('can $push an item onto an array with patch', function (done) {
pets.create({ type: 'cat', name: 'Margeaux' }).then(margeaux => {
people.patch(_ids.Doug, { $push: { pets: margeaux } })
.then(() => {
var params = {
query: {
$populate: ['pets']
}
};
people.get(_ids.Doug, params).then(data => {
expect(data.pets[1].name).to.equal('Margeaux');
done();
}).catch(done);
}).catch(done);
}).catch(done);
});
it('runs validators on update', function () {
return people.create({ name: 'David', age: 33 })
.then(person => people.update(person._id, { name: 'Dada', age: 'wrong' }))
.then(() => {
throw new Error('Update should not be successful');
})
.catch(error => {
expect(error.name).to.equal('BadRequest');
expect(error.message).to.equal('User validation failed: age: Cast to Number failed for value "wrong" at path "age"');
});
});
it('runs validators on patch', function (done) {
people.create({ name: 'David', age: 33 })
.then(person => people.patch(person._id, { name: 'Dada', age: 'wrong' }))
.then(() => done(new Error('Update should not be successful')))
.catch(error => {
expect(error.name).to.equal('BadRequest');
expect(error.message).to.equal('Cast to number failed for value "wrong" at path "age"');
done();
});
});
it('returns a Conflict when unique index is violated', function (done) {
pets.create({ type: 'cat', name: 'Bob' })
.then(() => pets.create({ type: 'cat', name: 'Bob' }))
.then(() => done(new Error('Should not be successful')))
.catch(error => {
expect(error.name).to.equal('Conflict');
done();
});
});
orm(leanPeople, errors, '_id');
});
describe('Lean Services', () => {
beforeEach((done) => {
// FIXME (EK): This is shit. We should be loading fixtures
// using the raw driver not our system under test
leanPets.create({type: 'dog', name: 'Rufus'}).then(pet => {
_petIds.Rufus = pet._id;
return leanPeople.create({ name: 'Doug', age: 32, pets: [pet._id] }).then(user => {
_ids.Doug = user._id;
done();
});
});
});
afterEach(done => {
leanPets.remove(null, { query: {} }).then(() => {
return leanPeople.remove(null, { query: {} }).then(() => {
return done();
});
});
});
it('can $populate with find', function (done) {
var params = {
query: {
name: 'Doug',
$populate: ['pets']
}
};
leanPeople.find(params).then(data => {
expect(data[0].pets[0].name).to.equal('Rufus');
done();
});
});
it('can $populate with get', function (done) {
var params = {
query: {
$populate: ['pets']
}
};
leanPeople.get(_ids.Doug, params).then(data => {
expect(data.pets[0].name).to.equal('Rufus');
done();
}).catch(done);
});
it('can upsert with patch', function (done) {
var data = { name: 'Henry', age: 300 };
var params = {
mongoose: { upsert: true },
query: { name: 'Henry' }
};
leanPeople.patch(null, data, params).then(data => {
expect(Array.isArray(data)).to.equal(true);
var henry = data[0];
expect(henry.name).to.equal('Henry');
done();
}).catch(done);
});
});
describe('Discriminators', () => {
const data = {
_type: 'text',
text: 'Feathers!!!'
};
afterEach(done => {
posts.remove(null, { query: {} })
.then(data => {
done();
});
});
it('can get a discriminated model', function (done) {
posts.create(data)
.then(data => posts.get(data._id))
.then(data => {
expect(data._type).to.equal('text');
expect(data.text).to.equal('Feathers!!!');
done();
});
});
it('can find discriminated models by the type', function (done) {
posts.create(data)
.then(data => posts.find({ query: { _type: 'text' } }))
.then(data => {
data.forEach(element => {
expect(element._type).to.equal('text');
});
done();
});
});
it('can create a discriminated model', function (done) {
posts.create(data)
.then(data => {
expect(data._type).to.equal('text');
expect(data.text).to.equal('Feathers!!!');
done();
});
});
it('can update a discriminated model', function (done) {
const update = {
_type: 'text',
text: 'Hello, world!',
createdAt: Date.now(),
updatedAt: Date.now()
};
const params = {
query: {
_type: 'text'
}
};
posts.create(data)
.then(data => posts.update(data._id, update, params))
.then(data => {
expect(data._type).to.equal('text');
expect(data.text).to.equal('Hello, world!');
done();
});
});
it('can patch a discriminated model', function (done) {
const update = {
text: 'Howdy folks!'
};
const params = {
query: {
_type: 'text'
}
};
posts.create(data)
.then(data => posts.patch(data._id, update, params))
.then(data => {
expect(data.text).to.equal('Howdy folks!');
done();
});
});
it('can remove a discriminated model', function (done) {
posts.create(data)
.then(data => posts.remove(data._id, { query: { _type: 'text' } }))
.then(data => {
expect(data._type).to.equal('text');
done();
});
});
});
describe('Common tests', () => {
before(() => Promise.all([
app.service('peeps').remove(null),
app.service('peeps-customid').remove(null)
]));
base(app, errors, 'peeps', '_id');
base(app, errors, 'peeps-customid', 'customid');
});
describe('Mongoose service example test', () => {
before(done => {
server.service('todos').remove(null, {}).then(() => {
testApp = server.listen(3030);
return done();
});
});
after(done => testApp.close(() => done()));
example('_id');
});
});
|
var searchData=
[
['scadenza',['scadenza',['../structflashcards__t.html#aca5df2b9c7f242f0fe6bca656d38e991',1,'flashcards_t']]]
];
|
/*!
handlebars v4.0.5
Copyright (C) 2011-2015 by Yehuda Katz
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.
@license
*/
(function (e, t) {
if (typeof exports === 'object' && typeof module === 'object') module.exports = t();
else if (typeof define === 'function' && define.amd) define([], t);
else if (typeof exports === 'object') exports['Handlebars'] = t();
else e['Handlebars'] = t()
})(this, function () {
return (function (e) {
var r = {};
function t(n) {
if (r[n]) return r[n].exports;
var a = r[n] = {
exports: {},
id: n,
loaded: !1
};
e[n].call(a.exports, a, a.exports, t);
a.loaded = !0;
return a.exports
};
t.m = e;
t.c = r;
t.p = '';
return t(0)
})([function (e, t, r) {
'use strict';
var i = r(1)['default'],
o = r(2)['default'];
t.__esModule = !0;
var f = r(3),
s = i(f),
c = r(17),
d = o(c),
p = r(5),
h = o(p),
m = r(4),
a = i(m),
v = r(18),
u = i(v),
g = r(19),
x = o(g);
function l() {
var e = new s.HandlebarsEnvironment();
a.extend(e, s);
e.SafeString = d['default'];
e.Exception = h['default'];
e.Utils = a;
e.escapeExpression = a.escapeExpression;
e.VM = u;
e.template = function (t) {
return u.template(t, e)
};
return e
};
var n = l();
n.create = l;
x['default'](n);
n['default'] = n;
t['default'] = n;
e.exports = t['default']
}, function (e, t) {
'use strict';
t['default'] = function (e) {
if (e && e.__esModule) {
return e
} else {
var r = {};
if (e != null) {
for (var t in e) {
if (Object.prototype.hasOwnProperty.call(e, t)) r[t] = e[t]
}
}
;
r['default'] = e;
return r
}
};
t.__esModule = !0
}, function (e, t) {
'use strict';
t['default'] = function (e) {
return e && e.__esModule ? e : {
'default': e
}
};
t.__esModule = !0
}, function (e, t, r) {
'use strict';
var u = r(2)['default'];
t.__esModule = !0;
t.HandlebarsEnvironment = s;
var n = r(4),
d = r(5),
o = u(d),
p = r(6),
h = r(14),
m = r(16),
a = u(m),
v = '4.0.5';
t.VERSION = v;
var c = 7;
t.COMPILER_REVISION = c;
var f = {
1: '<= 1.0.rc.2',
2: '== 1.0.0-rc.3',
3: '== 1.0.0-rc.4',
4: '== 1.x.x',
5: '== 2.0.0-alpha.x',
6: '>= 2.0.0-beta.1',
7: '>= 4.0.0'
};
t.REVISION_CHANGES = f;
var i = '[object Object]';
function s(e, t, r) {
this.helpers = e || {};
this.partials = t || {};
this.decorators = r || {};
p.registerDefaultHelpers(this);
h.registerDefaultDecorators(this)
};
s.prototype = {
constructor: s,
logger: a['default'],
log: a['default'].log,
registerHelper: function (e, t) {
if (n.toString.call(e) === i) {
if (t) {
throw new o['default']('Arg not supported with multiple helpers')
}
;
n.extend(this.helpers, e)
} else {
this.helpers[e] = t
}
},
unregisterHelper: function (e) {
delete this.helpers[e]
},
registerPartial: function (e, t) {
if (n.toString.call(e) === i) {
n.extend(this.partials, e)
} else {
if (typeof t === 'undefined') {
throw new o['default']('Attempting to register a partial called "' + e + '" as undefined')
}
;
this.partials[e] = t
}
},
unregisterPartial: function (e) {
delete this.partials[e]
},
registerDecorator: function (e, t) {
if (n.toString.call(e) === i) {
if (t) {
throw new o['default']('Arg not supported with multiple decorators')
}
;
n.extend(this.decorators, e)
} else {
this.decorators[e] = t
}
},
unregisterDecorator: function (e) {
delete this.decorators[e]
}
};
var l = a['default'].log;
t.log = l;
t.createFrame = n.createFrame;
t.logger = a['default']
}, function (e, t) {
'use strict';
t.__esModule = !0;
t.extend = i;
t.indexOf = f;
t.escapeExpression = c;
t.isEmpty = d;
t.createFrame = p;
t.blockParams = h;
t.appendContextPath = m;
var u = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': ''',
'`': '`',
'=': '='
};
var o = /[&<>"'`=]/g,
s = /[&<>"'`=]/;
function l(e) {
return u[e]
};
function i(e) {
for (var t = 1; t < arguments.length; t++) {
for (var r in arguments[t]) {
if (Object.prototype.hasOwnProperty.call(arguments[t], r)) {
e[r] = arguments[t][r]
}
}
}
;
return e
};
var n = Object.prototype.toString;
t.toString = n;
var r = function (e) {
return typeof e === 'function'
};
if (r(/x/)) {
t.isFunction = r = function (e) {
return typeof e === 'function' && n.call(e) === '[object Function]'
}
}
;
t.isFunction = r;
var a = Array.isArray || function (e) {
return e && typeof e === 'object' ? n.call(e) === '[object Array]' : !1
};
t.isArray = a;
function f(e, t) {
for (var r = 0, n = e.length; r < n; r++) {
if (e[r] === t) {
return r
}
}
;
return -1
};
function c(e) {
if (typeof e !== 'string') {
if (e && e.toHTML) {
return e.toHTML()
} else if (e == null) {
return ''
} else if (!e) {
return e + ''
}
;
e = '' + e
}
;
if (!s.test(e)) {
return e
}
;
return e.replace(o, l)
};
function d(e) {
if (!e && e !== 0) {
return !0
} else if (a(e) && e.length === 0) {
return !0
} else {
return !1
}
};
function p(e) {
var t = i({}, e);
t._parent = e;
return t
};
function h(e, t) {
e.path = t;
return e
};
function m(e, t) {
return (e ? e + '.' : '') + t
}
}, function (e, t) {
'use strict';
t.__esModule = !0;
var r = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
function n(e, t) {
var i = t && t.loc,
o = undefined,
s = undefined;
if (i) {
o = i.start.line;
s = i.start.column;
e += ' - ' + o + ':' + s
}
;
var u = Error.prototype.constructor.call(this, e);
for (var a = 0; a < r.length; a++) {
this[r[a]] = u[r[a]]
}
;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, n)
}
;
if (i) {
this.lineNumber = o;
this.column = s
}
};
n.prototype = new Error();
t['default'] = n;
e.exports = t['default']
}, function (e, t, r) {
'use strict';
var n = r(2)['default'];
t.__esModule = !0;
t.registerDefaultHelpers = x;
var a = r(7),
i = n(a),
o = r(8),
s = n(o),
u = r(9),
l = n(u),
f = r(10),
c = n(f),
d = r(11),
p = n(d),
h = r(12),
m = n(h),
v = r(13),
g = n(v);
function x(e) {
i['default'](e);
s['default'](e);
l['default'](e);
c['default'](e);
p['default'](e);
m['default'](e);
g['default'](e)
}
}, function (e, t, r) {
'use strict';
t.__esModule = !0;
var n = r(4);
t['default'] = function (e) {
e.registerHelper('blockHelperMissing', function (t, r) {
var i = r.inverse,
o = r.fn;
if (t === !0) {
return o(this)
} else if (t === !1 || t == null) {
return i(this)
} else if (n.isArray(t)) {
if (t.length > 0) {
if (r.ids) {
r.ids = [r.name]
}
;
return e.helpers.each(t, r)
} else {
return i(this)
}
} else {
if (r.data && r.ids) {
var a = n.createFrame(r.data);
a.contextPath = n.appendContextPath(r.data.contextPath, r.name);
r = {
data: a
}
}
;
return o(t, r)
}
})
};
e.exports = t['default']
}, function (e, t, r) {
'use strict';
var o = r(2)['default'];
t.__esModule = !0;
var n = r(4),
a = r(5),
i = o(a);
t['default'] = function (e) {
e.registerHelper('each', function (e, t) {
if (!t) {
throw new i['default']('Must pass iterator to #each')
}
;
var d = t.fn,
p = t.inverse,
r = 0,
s = '',
a = undefined,
u = undefined;
if (t.data && t.ids) {
u = n.appendContextPath(t.data.contextPath, t.ids[0]) + '.'
}
;
if (n.isFunction(e)) {
e = e.call(this)
}
;
if (t.data) {
a = n.createFrame(t.data)
}
;
function l(t, r, i) {
if (a) {
a.key = t;
a.index = r;
a.first = r === 0;
a.last = !!i;
if (u) {
a.contextPath = u + t
}
}
;
s = s + d(e[t], {
data: a,
blockParams: n.blockParams([e[t], t], [u + t, null])
})
};
if (e && typeof e === 'object') {
if (n.isArray(e)) {
for (var c = e.length; r < c; r++) {
if (r in e) {
l(r, r, r === e.length - 1)
}
}
} else {
var o = undefined;
for (var f in e) {
if (e.hasOwnProperty(f)) {
if (o !== undefined) {
l(o, r - 1)
}
;
o = f;
r++
}
}
;
if (o !== undefined) {
l(o, r - 1, !0)
}
}
}
;
if (r === 0) {
s = p(this)
}
;
return s
})
};
e.exports = t['default']
}, function (e, t, r) {
'use strict';
var i = r(2)['default'];
t.__esModule = !0;
var n = r(5),
a = i(n);
t['default'] = function (e) {
e.registerHelper('helperMissing', function () {
if (arguments.length === 1) {
return undefined
} else {
throw new a['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"')
}
})
};
e.exports = t['default']
}, function (e, t, r) {
'use strict';
t.__esModule = !0;
var n = r(4);
t['default'] = function (e) {
e.registerHelper('if', function (e, t) {
if (n.isFunction(e)) {
e = e.call(this)
}
;
if (!t.hash.includeZero && !e || n.isEmpty(e)) {
return t.inverse(this)
} else {
return t.fn(this)
}
});
e.registerHelper('unless', function (t, r) {
return e.helpers['if'].call(this, t, {
fn: r.inverse,
inverse: r.fn,
hash: r.hash
})
})
};
e.exports = t['default']
}, function (e, t) {
'use strict';
t.__esModule = !0;
t['default'] = function (e) {
e.registerHelper('log', function () {
var a = [undefined],
t = arguments[arguments.length - 1];
for (var n = 0; n < arguments.length - 1; n++) {
a.push(arguments[n])
}
;
var r = 1;
if (t.hash.level != null) {
r = t.hash.level
} else if (t.data && t.data.level != null) {
r = t.data.level
}
;
a[0] = r;
e.log.apply(e, a)
})
};
e.exports = t['default']
}, function (e, t) {
'use strict';
t.__esModule = !0;
t['default'] = function (e) {
e.registerHelper('lookup', function (e, t) {
return e && e[t]
})
};
e.exports = t['default']
}, function (e, t, r) {
'use strict';
t.__esModule = !0;
var n = r(4);
t['default'] = function (e) {
e.registerHelper('with', function (e, t) {
if (n.isFunction(e)) {
e = e.call(this)
}
;
var a = t.fn;
if (!n.isEmpty(e)) {
var r = t.data;
if (t.data && t.ids) {
r = n.createFrame(t.data);
r.contextPath = n.appendContextPath(t.data.contextPath, t.ids[0])
}
;
return a(e, {
data: r,
blockParams: n.blockParams([e], [r && r.contextPath])
})
} else {
return t.inverse(this)
}
})
};
e.exports = t['default']
}, function (e, t, r) {
'use strict';
var i = r(2)['default'];
t.__esModule = !0;
t.registerDefaultDecorators = o;
var n = r(15),
a = i(n);
function o(e) {
a['default'](e)
}
}, function (e, t, r) {
'use strict';
t.__esModule = !0;
var n = r(4);
t['default'] = function (e) {
e.registerDecorator('inline', function (e, t, r, a) {
var i = e;
if (!t.partials) {
t.partials = {};
i = function (a, i) {
var o = r.partials;
r.partials = n.extend({}, o, t.partials);
var s = e(a, i);
r.partials = o;
return s
}
}
;
t.partials[a.args[0]] = a.fn;
return i
})
};
e.exports = t['default']
}, function (e, t, r) {
'use strict';
t.__esModule = !0;
var a = r(4),
n = {
methodMap: ['debug', 'info', 'warn', 'error'],
level: 'info',
lookupLevel: function (e) {
if (typeof e === 'string') {
var t = a.indexOf(n.methodMap, e.toLowerCase());
if (t >= 0) {
e = t
} else {
e = parseInt(e, 10)
}
}
;
return e
},
log: function (e) {
e = n.lookupLevel(e);
if (typeof console !== 'undefined' && n.lookupLevel(n.level) <= e) {
var a = n.methodMap[e];
if (!console[a]) {
a = 'log'
}
;
for (var r = arguments.length, i = Array(r > 1 ? r - 1 : 0), t = 1; t < r; t++) {
i[t - 1] = arguments[t]
}
;
console[a].apply(console, i)
}
}
};
t['default'] = n;
e.exports = t['default']
}, function (e, t) {
'use strict';
t.__esModule = !0;
function r(e) {
this.string = e
};
r.prototype.toString = r.prototype.toHTML = function () {
return '' + this.string
};
t['default'] = r;
e.exports = t['default']
}, function (e, t, r) {
'use strict';
var c = r(1)['default'],
d = r(2)['default'];
t.__esModule = !0;
t.checkRevision = p;
t.template = h;
t.wrapProgram = o;
t.resolvePartial = m;
t.invokePartial = v;
t.noop = s;
var l = r(4),
a = c(l),
f = r(5),
n = d(f),
i = r(3);
function p(e) {
var t = e && e[0] || 1,
r = i.COMPILER_REVISION;
if (t !== r) {
if (t < r) {
var a = i.REVISION_CHANGES[r],
o = i.REVISION_CHANGES[t];
throw new n['default']('Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (' + a + ') or downgrade your runtime to an older version (' + o + ').')
} else {
throw new n['default']('Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version (' + e[1] + ').')
}
}
};
function h(e, t) {
if (!t) {
throw new n['default']('No environment passed to template')
}
;
if (!e || !e.main) {
throw new n['default']('Unknown template object: ' + typeof e)
}
;
e.main.decorator = e.main_d;
t.VM.checkRevision(e.compiler);
function s(r, i, o) {
if (o.hash) {
i = a.extend({}, i, o.hash);
if (o.ids) {
o.ids[0] = !0
}
}
;
r = t.VM.resolvePartial.call(this, r, i, o);
var u = t.VM.invokePartial.call(this, r, i, o);
if (u == null && t.compile) {
o.partials[o.name] = t.compile(r, e.compilerOptions, t);
u = o.partials[o.name](i, o)
}
;
if (u != null) {
if (o.indent) {
var l = u.split('\n');
for (var s = 0, f = l.length; s < f; s++) {
if (!l[s] && s + 1 === f) {
break
}
;
l[s] = o.indent + l[s]
}
;
u = l.join('\n')
}
;
return u
} else {
throw new n['default']('The partial ' + o.name + ' could not be compiled when running in runtime-only mode')
}
};
var r = {
strict: function (e, t) {
if (!(t in e)) {
throw new n['default']('"' + t + '" not defined in ' + e)
}
;
return e[t]
},
lookup: function (e, t) {
var n = e.length;
for (var r = 0; r < n; r++) {
if (e[r] && e[r][t] != null) {
return e[r][t]
}
}
},
lambda: function (e, t) {
return typeof e === 'function' ? e.call(t) : e
},
escapeExpression: a.escapeExpression,
invokePartial: s,
fn: function (t) {
var r = e[t];
r.decorator = e[t + '_d'];
return r
},
programs: [],
program: function (e, t, r, n, a) {
var i = this.programs[e],
s = this.fn(e);
if (t || a || n || r) {
i = o(this, e, s, t, r, n, a)
} else if (!i) {
i = this.programs[e] = o(this, e, s)
}
;
return i
},
data: function (e, t) {
while (e && t--) {
e = e._parent
}
;
return e
},
merge: function (e, t) {
var r = e || t;
if (e && t && e !== t) {
r = a.extend({}, t, e)
}
;
return r
},
noop: t.VM.noop,
compilerInfo: e.compiler
};
function i(t) {
var n = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var a = n.data;
i._setup(n);
if (!n.partial && e.useData) {
a = g(t, a)
}
;
var o = undefined,
l = e.useBlockParams ? [] : undefined;
if (e.useDepths) {
if (n.depths) {
o = t !== n.depths[0] ? [t].concat(n.depths) : n.depths
} else {
o = [t]
}
}
;
function s(t) {
return '' + e.main(r, t, r.helpers, r.partials, a, l, o)
};
s = u(e.main, s, r, n.depths || [], a, l);
return s(t, n)
};
i.isTop = !0;
i._setup = function (n) {
if (!n.partial) {
r.helpers = r.merge(n.helpers, t.helpers);
if (e.usePartial) {
r.partials = r.merge(n.partials, t.partials)
}
;
if (e.usePartial || e.useDecorators) {
r.decorators = r.merge(n.decorators, t.decorators)
}
} else {
r.helpers = n.helpers;
r.partials = n.partials;
r.decorators = n.decorators
}
};
i._child = function (t, a, i, s) {
if (e.useBlockParams && !i) {
throw new n['default']('must pass block params')
}
;
if (e.useDepths && !s) {
throw new n['default']('must pass parent depths')
}
;
return o(r, t, e[t], a, 0, i, s)
};
return i
};
function o(e, t, r, a, s, o, n) {
function i(t) {
var s = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var i = n;
if (n && t !== n[0]) {
i = [t].concat(n)
}
;
return r(e, t, e.helpers, e.partials, s.data || a, o && [s.blockParams].concat(o), i)
};
i = u(r, i, e, n, a, o);
i.program = t;
i.depth = n ? n.length : 0;
i.blockParams = s || 0;
return i
};
function m(e, t, r) {
if (!e) {
if (r.name === '@partial-block') {
e = r.data['partial-block']
} else {
e = r.partials[r.name]
}
} else if (!e.call && !r.name) {
r.name = e;
e = r.partials[e]
}
;
return e
};
function v(e, t, r) {
r.partial = !0;
if (r.ids) {
r.data.contextPath = r.ids[0] || r.data.contextPath
}
;
var o = undefined;
if (r.fn && r.fn !== s) {
r.data = i.createFrame(r.data);
o = r.data['partial-block'] = r.fn;
if (o.partials) {
r.partials = a.extend({}, r.partials, o.partials)
}
}
;
if (e === undefined && o) {
e = o
}
;
if (e === undefined) {
throw new n['default']('The partial ' + r.name + ' could not be found')
} else if (e instanceof Function) {
return e(t, r)
}
};
function s() {
return ''
};
function g(e, t) {
if (!t || !('root' in t)) {
t = t ? i.createFrame(t) : {};
t.root = e
}
;
return t
};
function u(e, t, r, n, i, o) {
if (e.decorator) {
var s = {};
t = e.decorator(t, s, r, n && n[0], i, o, n);
a.extend(t, s)
}
;
return t
}
}, function (e, t) {
(function (r) {
'use strict';
t.__esModule = !0;
t['default'] = function (e) {
var t = typeof r !== 'undefined' ? r : window,
n = t.Handlebars;
e.noConflict = function () {
if (t.Handlebars === e) {
t.Handlebars = n
}
;
return e
}
};
e.exports = t['default']
}.call(t, (function () {
return this
}())))
}])
});
|
/*
Product Name: dhtmlxSuite
Version: 4.1.1
Edition: Professional
License: content of this file is covered by DHTMLX Commercial or Enterprise license. Usage without proper license is prohibited. To obtain it contact sales@dhtmlx.com
Copyright UAB Dinamenta http://www.dhtmlx.com
*/
dhtmlXCalendarObject.prototype.draw = function() {
this.show();
};
dhtmlXCalendarObject.prototype.close = function() {
this.hide();
};
dhtmlXCalendarObject.prototype.setYearsRange = function() {
};
|
/*!
* JavaScript Custom Forms : Checkbox Module
*
* Copyright 2014-2016 PSD2HTML - http://psd2html.com/jcf
* Released under the MIT license (LICENSE.txt)
*
* Version: 1.2.3
*/
(function(jcf) {
jcf.addModule(function($) {
'use strict';
return {
name: 'Checkbox',
selector: 'input[type="checkbox"]',
options: {
wrapNative: true,
checkedClass: 'jcf-checked',
uncheckedClass: 'jcf-unchecked',
labelActiveClass: 'jcf-label-active',
fakeStructure: '<span class="jcf-checkbox"><span></span></span>'
},
matchElement: function(element) {
return element.is(':checkbox');
},
init: function() {
this.initStructure();
this.attachEvents();
this.refresh();
},
initStructure: function() {
// prepare structure
this.doc = $(document);
this.realElement = $(this.options.element);
this.fakeElement = $(this.options.fakeStructure).insertAfter(this.realElement);
this.labelElement = this.getLabelFor();
if (this.options.wrapNative) {
// wrap native checkbox inside fake block
this.realElement.appendTo(this.fakeElement).css({
position: 'absolute',
height: '100%',
width: '100%',
opacity: 0,
margin: 0
});
} else {
// just hide native checkbox
this.realElement.addClass(this.options.hiddenClass);
}
},
attachEvents: function() {
// add event handlers
this.realElement.on({
focus: this.onFocus,
click: this.onRealClick
});
this.fakeElement.on('click', this.onFakeClick);
this.fakeElement.on('jcf-pointerdown', this.onPress);
},
onRealClick: function(e) {
// just redraw fake element (setTimeout handles click that might be prevented)
var self = this;
this.savedEventObject = e;
setTimeout(function() {
self.refresh();
}, 0);
},
onFakeClick: function(e) {
// skip event if clicked on real element inside wrapper
if (this.options.wrapNative && this.realElement.is(e.target)) {
return;
}
// toggle checked class
if (!this.realElement.is(':disabled')) {
delete this.savedEventObject;
this.stateChecked = this.realElement.prop('checked');
this.realElement.prop('checked', !this.stateChecked);
this.fireNativeEvent(this.realElement, 'click');
if (this.savedEventObject && this.savedEventObject.isDefaultPrevented()) {
this.realElement.prop('checked', this.stateChecked);
} else {
this.fireNativeEvent(this.realElement, 'change');
}
delete this.savedEventObject;
}
},
onFocus: function() {
if (!this.pressedFlag || !this.focusedFlag) {
this.focusedFlag = true;
this.fakeElement.addClass(this.options.focusClass);
this.realElement.on('blur', this.onBlur);
}
},
onBlur: function() {
if (!this.pressedFlag) {
this.focusedFlag = false;
this.fakeElement.removeClass(this.options.focusClass);
this.realElement.off('blur', this.onBlur);
}
},
onPress: function(e) {
if (!this.focusedFlag && e.pointerType === 'mouse') {
this.realElement.focus();
}
this.pressedFlag = true;
this.fakeElement.addClass(this.options.pressedClass);
this.doc.on('jcf-pointerup', this.onRelease);
},
onRelease: function(e) {
if (this.focusedFlag && e.pointerType === 'mouse') {
this.realElement.focus();
}
this.pressedFlag = false;
this.fakeElement.removeClass(this.options.pressedClass);
this.doc.off('jcf-pointerup', this.onRelease);
},
getLabelFor: function() {
var parentLabel = this.realElement.closest('label'),
elementId = this.realElement.prop('id');
if (!parentLabel.length && elementId) {
parentLabel = $('label[for="' + elementId + '"]');
}
return parentLabel.length ? parentLabel : null;
},
refresh: function() {
// redraw custom checkbox
var isChecked = this.realElement.is(':checked'),
isDisabled = this.realElement.is(':disabled');
this.fakeElement.toggleClass(this.options.checkedClass, isChecked)
.toggleClass(this.options.uncheckedClass, !isChecked)
.toggleClass(this.options.disabledClass, isDisabled);
if (this.labelElement) {
this.labelElement.toggleClass(this.options.labelActiveClass, isChecked);
}
},
destroy: function() {
// restore structure
if (this.options.wrapNative) {
this.realElement.insertBefore(this.fakeElement).css({
position: '',
width: '',
height: '',
opacity: '',
margin: ''
});
} else {
this.realElement.removeClass(this.options.hiddenClass);
}
// removing element will also remove its event handlers
this.fakeElement.off('jcf-pointerdown', this.onPress);
this.fakeElement.remove();
// remove other event handlers
this.doc.off('jcf-pointerup', this.onRelease);
this.realElement.off({
focus: this.onFocus,
click: this.onRealClick
});
}
};
});
}(jcf));
|
// Generated on 2017-10-01 using generator-jhipster 4.9.0
'use strict';
var gulp = require('gulp'),
rev = require('gulp-rev'),
templateCache = require('gulp-angular-templatecache'),
htmlmin = require('gulp-htmlmin'),
imagemin = require('gulp-imagemin'),
ngConstant = require('gulp-ng-constant'),
rename = require('gulp-rename'),
eslint = require('gulp-eslint'),
del = require('del'),
runSequence = require('run-sequence'),
browserSync = require('browser-sync'),
KarmaServer = require('karma').Server,
plumber = require('gulp-plumber'),
changed = require('gulp-changed'),
gulpIf = require('gulp-if');
var handleErrors = require('./gulp/handle-errors'),
serve = require('./gulp/serve'),
util = require('./gulp/utils'),
copy = require('./gulp/copy'),
inject = require('./gulp/inject'),
build = require('./gulp/build');
var config = require('./gulp/config');
gulp.task('clean', function () {
return del([config.dist], { dot: true });
});
gulp.task('copy', ['copy:i18n', 'copy:fonts', 'copy:common']);
gulp.task('copy:i18n', copy.i18n);
gulp.task('copy:languages', copy.languages);
gulp.task('copy:fonts', copy.fonts);
gulp.task('copy:common', copy.common);
gulp.task('copy:swagger', copy.swagger);
gulp.task('copy:images', copy.images);
gulp.task('images', function () {
return gulp.src(config.app + 'content/images/**')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(changed(config.dist + 'content/images'))
.pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
.pipe(rev())
.pipe(gulp.dest(config.dist + 'content/images'))
.pipe(rev.manifest(config.revManifest, {
base: config.dist,
merge: true
}))
.pipe(gulp.dest(config.dist))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('styles', [], function () {
return gulp.src(config.app + 'content/css')
.pipe(browserSync.reload({stream: true}));
});
gulp.task('inject', function() {
runSequence('inject:dep', 'inject:app');
});
gulp.task('inject:dep', ['inject:test', 'inject:vendor']);
gulp.task('inject:app', inject.app);
gulp.task('inject:vendor', inject.vendor);
gulp.task('inject:test', inject.test);
gulp.task('inject:troubleshoot', inject.troubleshoot);
gulp.task('assets:prod', ['images', 'styles', 'html', 'copy:swagger', 'copy:images'], build);
gulp.task('html', function () {
return gulp.src(config.app + 'app/**/*.html')
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(templateCache({
module: 'webHipsterApp',
root: 'app/',
moduleSystem: 'IIFE'
}))
.pipe(gulp.dest(config.tmp));
});
gulp.task('ngconstant:dev', function () {
return ngConstant({
name: 'webHipsterApp',
constants: {
VERSION: util.parseVersion(),
DEBUG_INFO_ENABLED: true,
BUILD_TIMESTAMP: ''
},
template: config.constantTemplate,
stream: true
})
.pipe(rename('app.constants.js'))
.pipe(gulp.dest(config.app + 'app/'));
});
gulp.task('ngconstant:prod', function () {
return ngConstant({
name: 'webHipsterApp',
constants: {
VERSION: util.parseVersion(),
DEBUG_INFO_ENABLED: false,
BUILD_TIMESTAMP: new Date().getTime()
},
template: config.constantTemplate,
stream: true
})
.pipe(rename('app.constants.js'))
.pipe(gulp.dest(config.app + 'app/'));
});
// check app for eslint errors
gulp.task('eslint', function () {
return gulp.src(['gulpfile.js', config.app + 'app/**/*.js'])
.pipe(plumber({errorHandler: handleErrors}))
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
// check app for eslint errors anf fix some of them
gulp.task('eslint:fix', function () {
return gulp.src(config.app + 'app/**/*.js')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(eslint({
fix: true
}))
.pipe(eslint.format())
.pipe(gulpIf(util.isLintFixed, gulp.dest(config.app + 'app')));
});
gulp.task('test', ['inject:test', 'ngconstant:dev'], function (done) {
new KarmaServer({
configFile: __dirname + '/' + config.test + 'karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('watch', function () {
gulp.watch('bower.json', ['install']);
gulp.watch(['gulpfile.js', 'pom.xml'], ['ngconstant:dev']);
gulp.watch(config.app + 'content/css/**/*.css', ['styles']);
gulp.watch(config.app + 'content/images/**', ['images']);
gulp.watch(config.app + 'app/**/*.js', ['inject:app']);
gulp.watch([config.app + '*.html', config.app + 'app/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});
gulp.task('install', function () {
runSequence(['inject:dep', 'ngconstant:dev'], 'copy:languages', 'inject:app', 'inject:troubleshoot');
});
gulp.task('serve', ['install'], serve);
gulp.task('build', ['clean'], function (cb) {
runSequence(['copy', 'inject:vendor', 'ngconstant:prod', 'copy:languages'], 'inject:app', 'inject:troubleshoot', 'assets:prod', cb);
});
gulp.task('default', ['serve']);
|
function acceso() {
window.location.href="http://localhost/montage/public/home";
} |
(function() {
var Command, Config, apm, optimist, path, _,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
path = require('path');
_ = require('underscore-plus');
optimist = require('optimist');
apm = require('./apm');
Command = require('./command');
module.exports = Config = (function(_super) {
__extends(Config, _super);
Config.commandNames = ['config'];
function Config() {
var atomDirectory;
atomDirectory = apm.getAtomDirectory();
this.atomNodeDirectory = path.join(atomDirectory, '.node-gyp');
this.atomNpmPath = require.resolve('npm/bin/npm-cli');
}
Config.prototype.parseOptions = function(argv) {
var options;
options = optimist(argv);
options.usage("\nUsage: apm config set <key> <value>\n apm config get <key>\n apm config delete <key>\n apm config list\n apm config edit\n");
return options.alias('h', 'help').describe('help', 'Print this usage message');
};
Config.prototype.run = function(options) {
var callback, configArgs, configOptions, cwd, env;
callback = options.callback, cwd = options.cwd;
options = this.parseOptions(options.commandArgs);
configArgs = ['--globalconfig', apm.getGlobalConfigPath(), '--userconfig', apm.getUserConfigPath(), 'config'];
configArgs = configArgs.concat(options.argv._);
env = _.extend({}, process.env, {
HOME: this.atomNodeDirectory
});
configOptions = {
env: env
};
return this.fork(this.atomNpmPath, configArgs, configOptions, function(code, stderr, stdout) {
if (stderr == null) {
stderr = '';
}
if (stdout == null) {
stdout = '';
}
if (code === 0) {
if (stdout) {
process.stdout.write(stdout);
}
return callback();
} else {
if (stderr) {
process.stdout.write(stderr);
}
return callback(new Error("npm config failed: " + code));
}
});
};
return Config;
})(Command);
}).call(this);
|
const vm = require('vm')
const util = require('util')
const path = require('path')
const coverageMap = require('../lib/coverage-map')
describe('preprocessor', () => {
const createPreprocessor = require('../lib/preprocessor')
const ORIGINAL_CODE = `
if (a) {
something();
} else {
other();
}
`
const ORIGINAL_COFFEE_CODE = `
if a
something()
else
other()
`
const mockLogger = {
create: () => {
return {
error: (...arg) => { throw new Error(util.format.apply(util, arg)) },
warn: () => {},
info: () => {},
debug: () => {}
}
}
}
// TODO(vojta): refactor this somehow ;-) it's copy pasted from lib/file-list.js
function File (path, mtime) {
this.path = path
this.originalPath = path
this.contentPath = path
this.mtime = mtime
this.isUrl = false
}
it('should not do anything if coverage reporter is not used', (done) => {
const process = createPreprocessor(mockLogger, null, ['dots', 'progress'], {})
const file = new File('/base/path/file.js')
process(ORIGINAL_CODE, file, (preprocessedCode) => {
expect(preprocessedCode).to.equal(ORIGINAL_CODE)
expect(file.path).to.equal('/base/path/file.js')
done()
})
})
it('should preprocess the code', (done) => {
const process = createPreprocessor(mockLogger, '/base/path', ['coverage', 'progress'], {})
const file = new File('/base/path/file.js')
process(ORIGINAL_CODE, file, (preprocessedCode) => {
const sandbox = {
a: true,
something: () => {}
}
vm.runInNewContext(preprocessedCode, sandbox)
expect(sandbox.__coverage__).to.have.ownProperty(path.resolve('/base/path/file.js'))
done()
})
})
it('should preprocess the fake code', (done) => {
class fakeInstanbulLikeInstrumenter {
instrument (_a, _b, callback) {
callback()
}
lastSourceMap () {}
}
const process = createPreprocessor(mockLogger, '/base/path', ['coverage', 'progress'], {
instrumenters: {
fakeInstanbulLike: {
Instrumenter: fakeInstanbulLikeInstrumenter
}
},
instrumenter: {
'**/*.fake': 'fakeInstanbulLike'
}
})
const file = new File('/base/path/file.fake')
process(ORIGINAL_COFFEE_CODE, file, (preprocessedCode) => {
const sandbox = {
a: true,
something: () => {}
}
vm.runInNewContext(preprocessedCode, sandbox)
expect(file.path).to.equal('/base/path/file.fake')
done()
})
})
it('should preprocess the fake code with the config options', (done) => {
class fakeInstanbulLikeInstrumenter {
constructor (options) {
expect(options.experimental).to.be.ok
}
instrument (_a, _b, callback) {
callback()
}
lastSourceMap () {}
}
const process = createPreprocessor(mockLogger, '/base/path', ['coverage', 'progress'], {
instrumenters: {
fakeInstanbulLike: {
Instrumenter: fakeInstanbulLikeInstrumenter
}
},
instrumenterOptions: {
fakeInstanbulLike: {
experimental: 'yes'
}
},
instrumenter: {
'**/*.fake': 'fakeInstanbulLike'
}
})
const file = new File('/base/path/file.fake')
process(ORIGINAL_COFFEE_CODE, file, done)
})
it('should not preprocess the coffee code', (done) => {
const process = createPreprocessor(mockLogger, '/base/path', ['coverage', 'progress'], { instrumenter: { '**/*.coffee': 'istanbul' } })
const file = new File('/base/path/file.coffee')
process(ORIGINAL_CODE, file, (preprocessedCode) => {
const sandbox = {
a: true,
something: () => {}
}
vm.runInNewContext(preprocessedCode, sandbox)
expect(file.path).to.equal('/base/path/file.coffee')
expect(sandbox.__coverage__).to.have.ownProperty(path.resolve('/base/path/file.coffee'))
done()
})
})
it('should fail if invalid instrumenter provided', () => {
const work = () => {
createPreprocessor(mockLogger, '/base/path', ['coverage', 'progress'], { instrumenter: { '**/*.coffee': 'madeup' } })
}
expect(work).to.throw()
})
it('should add coverageMap when including all sources', (done) => {
const process = createPreprocessor(mockLogger, '/base/path', ['coverage'], { includeAllSources: true })
const file = new File('/base/path/file.js')
coverageMap.reset()
process(ORIGINAL_CODE, file, (preprocessedCode) => {
expect(coverageMap.get()[path.resolve('/base/path/file.js')]).to.exist
done()
})
})
it('should not add coverageMap when not including all sources', (done) => {
const process = createPreprocessor(mockLogger, '/base/path', ['coverage'], { includeAllSources: false })
const file = new File('/base/path/file.js')
coverageMap.reset()
process(ORIGINAL_CODE, file, (preprocessedCode) => {
expect(coverageMap.get()['./file.js']).to.not.exist
done()
})
})
it('should not add coverageMap in the default state', (done) => {
const process = createPreprocessor(mockLogger, '/base/path', ['coverage'], {})
const file = new File('/base/path/file.js')
coverageMap.reset()
process(ORIGINAL_CODE, file, (preprocessedCode) => {
expect(coverageMap.get()['./file.js']).to.not.exist
done()
})
})
it('should change extension of CoffeeScript files when given `useJSExtensionForCoffeeScript`', (done) => {
class ibrikInstrumenter {
instrument (_a, _b, callback) {
callback()
}
lastSourceMap () {}
}
const process = createPreprocessor(mockLogger, '/base/path', ['coverage', 'progress'], {
instrumenters: {
ibrik: {
Instrumenter: ibrikInstrumenter
}
},
instrumenter: {
'**/*.coffee': 'ibrik'
},
useJSExtensionForCoffeeScript: true
})
const file = new File('/base/path/file.coffee')
process(ORIGINAL_COFFEE_CODE, file, (preprocessedCode) => {
const sandbox = {
a: true,
something: () => {}
}
vm.runInNewContext(preprocessedCode, sandbox)
expect(file.path).to.equal('/base/path/file.js')
done()
})
})
})
|
// import { Signup } from '../index';
import expect from 'expect';
// import { shallow } from 'enzyme';
// import React from 'react';
describe('<Signup />', () => {
it('Expect to have unit tests specified', () => {
expect(true).toEqual(false);
});
});
|
var _ = require( "lodash" );
var when = require( "when" );
function setModel( self, model, context ) {
self._model = model;
self._context = context;
return self;
}
var HyperResponse = function( envelope, engine, hyperResource, contentType ) {
this._code = 200;
this._envelope = envelope;
this._engine = engine;
this._hyperResource = hyperResource;
var req = this._req = envelope._original.req;
this._res = envelope._original.res;
this._contentType = contentType;
this._context = req.context;
this._headers = {};
this._cookies = {};
this._authCheck = req._checkPermission || function() {
return true;
};
var self = this;
req.extendHttp.hyped = req.hyped = setModel.bind( undefined, self );
req.extendHttp.reply = this.render.bind( this );
req.extendHttp.render = req.render = function( host, resource, action, result ) {
var model = result.data ? result.data : result;
var context = result.context ? result.context : self._context;
setModel( self, model, context );
self._code = result.status || result.statusCode || self._code;
self._headers = result.headers || {};
self._cookies = result.cookies || {};
self._resource = result.resource || self._resource;
self._action = result.action || self._action;
};
};
HyperResponse.prototype.context = function( context ) {
this._context = context;
return this;
};
HyperResponse.prototype.cookies = function( cookies ) {
this._cookies = cookies;
return this;
};
HyperResponse.prototype.createResponse = function() {
var resource = this._req._resource;
var action = this._req._action;
this._headers[ "Content-Type" ] = this._contentType;
if ( this._code >= 400 ) {
if ( this._engine.hal ) {
_.assign( this._model, {
_action: this._action || action,
_resource: this._resource || resource,
_version: this._envelope.version,
_origin: {
href: this._originUrl,
method: this._originMethod
}
} );
}
return when( {
status: this._code,
headers: this._headers,
cookies: this._cookies,
data: this._engine( this._model )
} );
}
if ( this._code === 204 || !this._model ) {
return when( {
status: this._code,
headers: this._headers,
cookies: this._cookies
} );
}
return this._hyperResource(
this._resource || resource,
this._action || action,
this._envelope,
this._model,
"",
this._originUrl,
this._originMethod,
this._engine.hal
).then( function( hypermedia ) {
return {
status: this._code,
headers: this._headers,
cookies: this._cookies,
data: this._engine( hypermedia )
};
}.bind( this ) );
};
HyperResponse.prototype.headers = function( headers ) {
this._headers = headers;
return this;
};
HyperResponse.prototype.origin = function( originUrl, method ) {
this._originUrl = originUrl;
this._originMethod = method;
return this;
};
HyperResponse.prototype.status = function( code ) {
this._code = code;
return this;
};
HyperResponse.prototype.getResponse = function() {
if ( this._engine ) {
return this.createResponse();
} else {
return when( {
status: 415,
headers: {
"Content-Type": "text/plain"
},
data: "The requested media type '" + this._contentType + "' is not supported. Please see the OPTIONS at the api root to get a list of supported types."
} );
}
};
HyperResponse.prototype.render = function() {
var res = this._res;
return this.getResponse()
.then( function( response ) {
if ( response.headers ) {
_.each( response.headers, function( v, k ) {
res.set( k, v );
} );
}
if ( response.cookies ) {
_.each( response.cookies, function( v, k ) {
res.cookie( k, v.value, v.options );
} );
}
res.status( response.status ).send( response.data );
return response;
} );
};
module.exports = HyperResponse;
|
var loggly = require('loggly');
/*var client = loggly.createClient({
token: "1cae3802-0bfb-4462-8b6f-4697c794867c",
subdomain: "edwinacevedo",
tags: ["NodeJS"],
json: true
});*/
// we can use loggly's api to send logs from multiple servers to loggly,
// which assembles these into a comprehensible whole
function logger(tag) {
return loggly.createClient({
token: "process.env.LOGGLY_TOKEN",
subdomain: "edwinacevedo",
tags: ['NodeJS', tag],
json: true
});
return client;
}
/*client.log("Hello World from Node.js!");*/ //logs this to loggly
module.exports = logger;
|
import $ from 'jquery';
var Videos = {
current: null,
get: function (subreddit) {
var base = 'https://www.reddit.com/r/';
var url = base + subreddit + '.json?jsonp=?';
$.getJSON(url).done(function (json) {
this.current = json;
$(window).trigger('set-videos', this.current);
}.bind(this)).fail(function (error) {
$(window).trigger('set-videos-error', error);
});
},
getUrl: function (index) {
var iframe = this.current ? this.current.data.children[index].data.media_embed.content : null;
if (!iframe) return null;
var src = iframe.match(/src="(\S+)"/)[1].concat('&autoplay=1');
return src;
},
getTitle: function (index) {
return this.current ? this.current.data.children[index].data.title : 'No title'
}
};
export default Videos;
|
var assert = require('assert')
, ref = require('ref')
, ffi = require('../')
, int = ref.types.int
, bindings = require('bindings')({ module_root: __dirname, bindings: 'ffi_tests' })
describe('Callback', function () {
afterEach(gc)
it('should create a C function pointer from a JS function', function () {
var callback = ffi.Callback('void', [ ], function (val) { })
assert(Buffer.isBuffer(callback))
})
it('should be invokable by an ffi\'d ForeignFunction', function () {
var funcPtr = ffi.Callback(int, [ int ], Math.abs)
var func = ffi.ForeignFunction(funcPtr, int, [ int ])
assert.equal(1234, func(-1234))
})
it('should work with a "void" return type', function () {
var funcPtr = ffi.Callback('void', [ ], function (val) { })
var func = ffi.ForeignFunction(funcPtr, 'void', [ ])
assert.strictEqual(null, func())
})
it('should not call "set()" of a pointer type', function () {
var voidType = Object.create(ref.types.void)
voidType.get = function () {
throw new Error('"get()" should not be called')
}
voidType.set = function () {
throw new Error('"set()" should not be called')
}
var voidPtr = ref.refType(voidType)
var called = false
var cb = ffi.Callback(voidPtr, [ voidPtr ], function (ptr) {
called = true
assert.equal(0, ptr.address())
return ptr
})
var fn = ffi.ForeignFunction(cb, voidPtr, [ voidPtr ])
assert(!called)
var nul = fn(ref.NULL)
assert(called)
assert(Buffer.isBuffer(nul))
assert.equal(0, nul.address())
})
it('should throw an Error when invoked through a ForeignFunction and throws', function () {
var cb = ffi.Callback('void', [ ], function () {
throw new Error('callback threw')
})
var fn = ffi.ForeignFunction(cb, 'void', [ ])
assert.throws(function () {
fn()
}, /callback threw/)
})
it('should throw an Error with a meaningful message when a type\'s "set()" throws', function () {
var cb = ffi.Callback('int', [ ], function () {
// Changed, because returning string is not failing because of this; https://github.com/iojs/io.js/issues/1161
return 1111111111111111111111
})
var fn = ffi.ForeignFunction(cb, 'int', [ ])
assert.throws(function () {
fn()
}, /error setting return value/)
})
it('should throw an Error when invoked after the callback gets garbage collected', function () {
var cb = ffi.Callback('void', [ ], function () { })
// register the callback function
bindings.set_cb(cb)
// should be ok
bindings.call_cb()
cb = null // KILL!!
gc()
// should throw an Error synchronously
try {
bindings.call_cb()
assert(false) // shouldn't get here
} catch (e) {
assert(/ffi/.test(e.message))
}
})
describe('async', function () {
it('should be invokable asynchronously by an ffi\'d ForeignFunction', function (done) {
var funcPtr = ffi.Callback(int, [ int ], Math.abs)
var func = ffi.ForeignFunction(funcPtr, int, [ int ])
func.async(-9999, function (err, res) {
assert.equal(null, err)
assert.equal(9999, res)
done()
})
})
/**
* See https://github.com/rbranson/node-ffi/issues/153.
*/
it('multiple callback invocations from uv thread pool should be properly synchronized', function (done) {
this.timeout(10000)
var iterations = 30000
var cb = ffi.Callback('string', [ 'string' ], function (val) {
if (val === "ping" && --iterations > 0) {
return "pong"
}
return "end"
})
var pingPongFn = ffi.ForeignFunction(bindings.play_ping_pong, 'void', [ 'pointer' ])
pingPongFn.async(cb, function (err, ret) {
assert.equal(iterations, 0)
done()
})
})
/**
* See https://github.com/rbranson/node-ffi/issues/72.
* This is a tough issue. If we pass the ffi_closure Buffer to some foreign
* C function, we really don't know *when* it's safe to dispose of the Buffer,
* so it's left up to the developer.
*
* In this case, we wrap the responsibility in a simple "kill()" function
* that, when called, destroys of its references to the ffi_closure Buffer.
*/
it('should work being invoked multiple times', function (done) {
var invokeCount = 0
var cb = ffi.Callback('void', [ ], function () {
invokeCount++
})
var kill = (function (cb) {
// register the callback function
bindings.set_cb(cb)
return function () {
var c = cb
cb = null // kill
c = null // kill!!!
}
})(cb)
// destroy the outer "cb". now "kill()" holds the "cb" reference
cb = null
// invoke the callback a couple times
assert.equal(0, invokeCount)
bindings.call_cb()
assert.equal(1, invokeCount)
bindings.call_cb()
assert.equal(2, invokeCount)
setTimeout(function () {
// invoke it once more for shits and giggles
bindings.call_cb()
assert.equal(3, invokeCount)
gc() // ensure the outer "cb" Buffer is collected
process.nextTick(finish)
}, 25)
function finish () {
bindings.call_cb()
assert.equal(4, invokeCount)
kill()
gc() // now ensure the inner "cb" Buffer is collected
// should throw an Error synchronously
try {
bindings.call_cb()
assert(false) // shouldn't get here
} catch (e) {
assert(/ffi/.test(e.message))
}
done()
}
})
it('should throw an Error when invoked after the callback gets garbage collected', function (done) {
var cb = ffi.Callback('void', [ ], function () { })
// register the callback function
bindings.set_cb(cb)
// should be ok
bindings.call_cb()
// hijack the "uncaughtException" event for this test
var listeners = process.listeners('uncaughtException').slice()
process.removeAllListeners('uncaughtException')
process.once('uncaughtException', function (e) {
var err
try {
assert(/ffi/.test(e.message))
} catch (ae) {
err = ae
}
done(err);
listeners.forEach(function (fn) {
process.on('uncaughtException', fn)
})
})
cb = null // KILL!!
gc()
// should generate an "uncaughtException" asynchronously
bindings.call_cb_async()
})
})
})
|
const scrollSyncMixin = {
getScrollRate(targetElement) {
const rect = targetElement.getBoundingClientRect();
this.scrollTop = targetElement.scrollTop;
this.scrollHeight = targetElement.scrollHeight;
this.maxScrollTop = this.scrollHeight - rect.height;
return this.scrollTop / this.maxScrollTop;
}
};
export default scrollSyncMixin; |
import path from 'path';
import base from '../../';
import { fileExists, readDir, writeFile } from '../FileSystem';
const exportTpl = '\n\nconst modelIndex = [@param];\n\nexport default { modelIndex };';
const importTpl = 'import * as @paramModel from \'containers/@param/models\';';
function RegenerateImportLine(container) {
return importTpl.replace(/@param/g, container);
}
function RegenerateExportLine(modelExports) {
return exportTpl.replace('@param', modelExports);
}
function RegenerateModelIndex(containersPath, modelFilePath) {
let modelImports = '';
let modelExports = '';
const containerModels = getContainerModels(containersPath);
containerModels.forEach(function(model, index) {
if (model.import) {
modelImports += (index === 1) ? model.import : '\n' + model.import;
modelExports += model.name + 'Model';
modelExports += (index < containerModels.length-1) ? ',' : '';
}
});
const content = modelImports + RegenerateExportLine(modelExports);
try {
writeFile(modelFilePath, content);
base.console.success(`Model index regenerated correctly!`);
return true;
} catch (e) {
base.console.error(`Model index error ${e.msg}`);
return false;
}
}
function getContainerModels(containersPath) {
const containers = readDir(containersPath);
return containers.map(function(container) {
let modelPath = path.resolve(containersPath, container, 'models','index.js');
if (fileExists(modelPath)) {
return { name:container, import: RegenerateImportLine(container)};
} else {
return { name: container, import: null };
}
});
}
module.exports.RegenerateModelIndex = RegenerateModelIndex;
module.exports.RegenerateImportLine = RegenerateImportLine;
module.exports.RegenerateExportLine = RegenerateExportLine;
module.exports.getContainerModels = getContainerModels;
|
/*global module:false*/
module.exports = function(grunt) {
var glob = require("glob"),
root = grunt.config('build').options.root;
grunt.log.writeln('Searching for buildscripts in ' + root + '/app/' + ' ...');
glob(root + '/app/' + '**/scripts/build.js', {
sync: true
}, function(er, apps) {
if (!apps.length) {
grunt.log.error('No build files found. Exiting.');
return;
}
apps = grunt.util._.map(apps, function(app) {
return app.split('app/')[1].split('/')[0];
});
var oddIndex = 0;
var evenIndex = 0;
var oddFiles = new Array();
var evenFiles = new Array();
for (var i = 0, file; i < apps.length; i++) {
if ((i % 2) == 1) {
/* oddFiles[oddIndex] = apps[i].split(root).slice(1).join(root); */
oddFiles[oddIndex] = apps[i];
oddIndex++;
} else {
/* evenFiles[evenIndex] = apps[i].split(root).slice(1).join(root); */
evenFiles[evenIndex] = apps[i];
evenIndex++;
}
}
grunt.config('concurrent', {
build: {
tasks: ['oddBuild', 'evenBuild'],
options: {
logConcurrentOutput: true
}
}
})
grunt.registerTask('oddBuild', 'FrogOS MultiBuild.', function() {
this.requiresConfig('build');
grunt.log.writeln('Found ' + oddFiles.length + ' build files. Beginning steal task ...');
grunt.config('steal-build', {
js: root + '/app',
build: oddFiles
});
grunt.task.run('steal-build');
});
grunt.registerTask('evenBuild', 'FrogOS MultiBuild.', function() {
this.requiresConfig('build');
grunt.log.writeln('Found ' + evenFiles.length + ' build files. Beginning steal task ...');
grunt.config('steal-build', {
js: root + '/app',
build: evenFiles
});
grunt.task.run('steal-build');
});
grunt.loadNpmTasks('grunt-concurrent');
});
}; |
define([
"../core",
"../var/support"
], function( jQuery, support ) {
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
// Support: IE9-11+
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.vendor_js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
div.removeChild( marginDiv );
return ret;
}
});
}
})();
return support;
});
|
'use strict';
function isTrackEnabled(type, t){
return t.kind === type && t.enabled &&
!t.muted && t.readyState !== 'ended';
}
function hasValidTrack(stream, type){
return stream.getTracks().some(isTrackEnabled.bind(null, type));
}
module.exports = hasValidTrack;
|
import { Phaser } from 'phaser';
export class Spell extends Phaser.Sprite{
constructor(game, x, y) {
super(game, x, y, 'icicle');
this.animations.add('casting', [0,1,2,3,4,5,6,7,8]);
this.soundEffect = this.game.add.audio('spell');
this.soundEffect.volume = 0.5;
}
casting() {
this.animations.play('casting', 5, true);
this.soundEffect.play();
}
} |
(function() {
var url = 'data.json';
var r = 10;
var graph, layout, zoom, nodes, links, data;
var linkedByIndex = {};
var graphWidth, graphHeight;
// Helpers
function formatClassName(prefix, object) {
return prefix + '-' + object.id.replace(/(\.|\/)/gi, '-');
}
function findElementByNode(prefix, node) {
var selector = '.'+formatClassName(prefix, node);
return graph.select(selector);
}
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index] || a.index == b.index;
}
function fadeRelatedNodes(d, opacity, nodes, links) {
// Clean
$('path.link').removeAttr('data-show');
nodes.style("stroke-opacity", function(o) {
var thisOpacity;
if (isConnected(d, o)) {
thisOpacity = 1;
} else {
thisOpacity = opacity;
}
this.setAttribute('fill-opacity', thisOpacity);
this.setAttribute('stroke-opacity', thisOpacity);
if(thisOpacity == 1) {
this.classList.remove('dimmed');
} else {
this.classList.add('dimmed');
}
return thisOpacity;
});
links.style("stroke-opacity", function(o) {
if (o.source === d) {
// Highlight target/sources of the link
var elmNodes = graph.selectAll('.'+formatClassName('node', o.target));
elmNodes.attr('fill-opacity', 1);
elmNodes.attr('stroke-opacity', 1);
elmNodes.classed('dimmed', false);
// Highlight arrows
var elmCurrentLink = $('path.link[data-source=' + o.source.index + ']');
elmCurrentLink.attr('data-show', true);
elmCurrentLink.attr('marker-end', 'url(#regular)');
return 1;
} else {
var elmAllLinks = $('path.link:not([data-show])');
if(opacity == 1) {
elmAllLinks.attr('marker-end', 'url(#regular)');
} else {
elmAllLinks.attr('marker-end', '');
}
return opacity;
}
});
}
function render() {
zoom = d3.behavior.zoom();
zoom.on("zoom", onZoomChanged);
// Setup layout
layout = d3.layout.force()
.gravity(.05)
.charge(-300)
.linkDistance(100);
// Setup graph
graph = d3.select(".graph")
.append("svg:svg")
.attr("pointer-events", "all")
.call(zoom)
.append('svg:g')
.attr('width', graphWidth)
.attr('height', graphHeight);
d3.select(window).on("resize", resize);
// Load graph data
var graphData = window.getGraphData();
// Load node placement
var storedNodes = getNodes();
graphData.nodes = graphData.nodes.map(function(n){
if(storedNodes[n.id]){
return storedNodes[n.id];
} else {
return n;
}
});
renderGraph(graphData);
data = graphData;
// Resize
resize();
centerGraph();
// Controlers
$('.control-zoom a').on('click', onControlZoomClicked);
}
function resize() {
graphWidth = window.innerWidth;
graphHeight = window.innerHeight;
graph.attr("width", graphWidth)
.attr("height", graphHeight);
layout.size([graphWidth, graphHeight])
.resume();
}
function centerGraph() {
var centerTranslate = [
(graphWidth / 2) - (graphWidth * 0.2 / 2),
(graphHeight / 2) - (graphHeight * 0.2 / 2)
];
zoom.translate(centerTranslate);
// Render transition
graph.transition()
.duration(500)
.attr("transform", "translate(" + zoom.translate() + ")" + " scale(" + zoom.scale() + ")");
}
function renderGraph(data) {
// Markers
graph.append("svg:defs").selectAll("marker")
.data(['regular'])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
// Lines
links = graph.append('svg:g').selectAll("line")
.data(data.links)
.enter().append("svg:path")
.attr('class', 'link')
.attr("data-target", function(o) { return o.target })
.attr("data-source", function(o) { return o.source })
.attr("marker-end", function(d) { return "url(#regular)"; });
// Nodes
nodes = graph.append('svg:g').selectAll("node")
.data(data.nodes)
.enter().append("svg:g")
.attr("class","node")
.call(layout.drag)
.on("mousedown", onNodeMouseDown);
// Circles
nodes.attr("class", function(d) { return formatClassName('node', d) })
nodes.append("svg:circle")
.attr("class", function(d) { return formatClassName('circle', d) })
.attr("r", 6)
.on("mouseover", onNodeMouseOver.bind(this, nodes, links) )
.on("mouseout", onNodeMouseOut.bind(this, nodes, links) );
// A copy of the text with a thick white stroke for legibility.
nodes.append("svg:text")
.attr("x", 15)
.attr("y", ".31em")
.attr("class", function(d) { return 'shadow ' + formatClassName('text', d) })
.text(function(d) { return d.id.replace(window.basePath, '') });
nodes.append("svg:text")
.attr("class", function(d) { return formatClassName('text', d) })
.attr("x", 15)
.attr("y", ".31em")
.text(function(d) { return d.id.replace(window.basePath, '') });
// Build linked index
data.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
// Draw the
layout.nodes(data.nodes);
layout.links(data.links);
layout.on("tick", onTick);
layout.start();
zoom.scale(0.4);
// Render transition
graph.transition()
.duration(500)
.attr("transform", "scale(" + zoom.scale() + ")");
}
function onNodeMouseOver(nodes, links, d) {
// Highlight circle
var elm = findElementByNode('circle', d);
elm.style("fill", '#b94431');
// Highlight related nodes
fadeRelatedNodes(d, .05, nodes, links);
}
function onNodeMouseOut(nodes, links, d) {
// Highlight circle
var elm = findElementByNode('circle', d);
elm.style("fill", '#ccc');
// Highlight related nodes
fadeRelatedNodes(d, 1, nodes, links);
debouncedPersist();
}
function onTick(e) {
links.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
nodes.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
function onControlZoomClicked(e) {
var elmTarget = $(this)
var scaleProcentile = 0.20;
// Scale
var currentScale = zoom.scale();
var newScale;
if(elmTarget.hasClass('control-zoom-in')) {
newScale = currentScale * (1 + scaleProcentile);
} else {
newScale = currentScale * (1 - scaleProcentile);
}
newScale = Math.max(newScale, 0);
// Translate
var centerTranslate = [
(graphWidth / 2) - (graphWidth * newScale / 2),
(graphHeight / 2) - (graphHeight * newScale / 2)
];
// Store values
zoom
.translate(centerTranslate)
.scale(newScale);
// Render transition
graph.transition()
.duration(500)
.attr("transform", "translate(" + zoom.translate() + ")" + " scale(" + zoom.scale() + ")");
}
function onZoomChanged() {
graph.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
function persistNodes(nodes) {
var store = nodes.filter(function(n){ return n.fixed }).reduce(function(mem,n){
mem[n.id]=n;
return mem;
},{});
store = JSON.stringify(store);
window.localStorage.setItem("dependo"+window.graphIdentification, store);
}
function getNodes() {
try {
if(window.nodePositions){
return JSON.parse(window.nodePositions);
}else{
return JSON.parse(window.localStorage.getItem("dependo"+window.graphIdentification)) || {};
}
} catch (e) {
return {};
}
}
function onNodeMouseDown(d) {
d.fixed = true;
d3.select(this).classed("sticky", true);
debouncedPersist();
}
var persistTimer;
function debouncedPersist() {
clearTimeout(persistTimer);
persistTimer = setTimeout(function(){
persistNodes(data.nodes)
},1000);
}
render();
})();
|
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', '$window', 'Authentication',
function($scope, $http, $location, $window, Authentication) {
$scope.authentication = Authentication;
$scope.signup = function() {
$http.post('/auth/signup', $scope.credentials).success(function(response) {
//If successful we assign the response to the global user model
$scope.authentication.user = response;
//And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.signin = function() {
$http.post('/auth/signin', $scope.credentials).success(function(response) {
//If successful we assign the response to the global user model
$scope.authentication.user = response;
//And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.forgot = function() {
console.log('forgot', $scope.email);
$http.post('/forgot', $scope.body).success(function(response) {
//If successful we assign the response to the global user model
console.log('success', $window.location);
//And redirect to the index page
$window.location = '/';
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.reset = function() {
//console.log('reset', $scope.body, $location, $location.absUrl().split('reset/')[1]);
var token = $location.absUrl().split('reset/')[1];
console.log('/forgot/'+token);
$http.post('/reset/' + token, $scope.body).success(function(response) {
//If successful we assign the response to the global user model
console.log('success');
//And redirect to the index page
$window.location = '/';
}).error(function(response) {
$scope.error = response.message;
});
};
}
]); |
/* eslint-disable jsx-a11y/anchor-has-content */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import MarkdownView from 'react-showdown';
import semver from 'semver';
import Paper from '@material-ui/core/Paper';
import Accordion from '@material-ui/core/Accordion';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionActions from '@material-ui/core/AccordionDetails';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import IconButton from '@material-ui/core/IconButton';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Snackbar from '@material-ui/core/Snackbar';
import {MdEdit as IconEdit} from 'react-icons/md';
import {MdClose as IconClose} from 'react-icons/md';
import {MdMenu as IconMenu} from 'react-icons/md';
import {MdExpandMore as IconExpandMore} from 'react-icons/md';
import {FaGithub as IconGithub} from 'react-icons/fa';
import IconGlobe from '../assets/globe.svg';
import IconLink from '../assets/link.svg';
import Loader from '@iobroker/adapter-react/Components/Loader';
import I18n from '@iobroker/adapter-react/i18n';
import Utils from './MDUtils';
//import Page404 from '@iobroker/adapter-react/Components/404';
const styles = theme => ({
root: {
width: 'calc(100% - 10px)',
maxWidth: 1400,
margin: 5,
'& .md-link': {
display: 'inline-block'
},
'& h2': {
width: '100%',
textAlign: 'left',
paddingBottom: 10,
borderBottom: '1px solid lightgray'
},
'& hr': {
borderWidth: '0 0 1px 0'
},
'& a': {
color: 'inherit'
},
'& pre': {
background: '#e3e3e3',
},
'& code': {
margin: '0 0.15em',
padding: '0.125em 0.4em',
borderRadius: 2,
background: '#e3e3e3',
color: '#000000',
whiteSpace: 'pre',
},
'& img': {
maxWidth: '100%'
}
},
logoImage: {
width: 64,
verticalAlign: 'middle',
},
infoEdit: {
float: 'right',
textDecoration: 'none',
color: 'gray'
},
infoEditLocal: {
float: 'right',
textDecoration: 'none',
marginRight: 15,
cursor: 'pointer',
display: 'inline-block'
},
adapterCard: {
marginBottom: 0,
marginTop: 0,
},
badgesDetails: {
display: 'block',
'& img': {
marginRight: 5,
}
},
titleText: {
display: 'inline-block',
marginLeft: 10,
},
adapterCardAttr:{
fontWeight: 'bold',
width: 150,
display: 'inline-block'
},
adapterCardListItem: {
paddingTop: 3,
paddingBottom: 3,
},
description: {
fontStyle: 'italic'
},
contentDiv: {
position: 'fixed',
width: '20%',
minWidth: 200,
overflowX: 'hidden',
opacity: 0.8,
top: 60,
right: 20,
background: theme.palette.type === 'dark' ? '#111111': '#EEEEEE',
maxHeight: 'calc(100% - 70px)',
},
contentDivClosed: {
position: 'fixed',
opacity: 0.8,
top: 60,
right: 20,
width: 25,
height: 25,
cursor: 'pointer'
},
contentClose: {
position: 'fixed',
top: 60 + 5,
right: 20 + 5,
cursor: 'pointer',
'&:hover': {
color: '#111111'
}
},
contentLinks: {
cursor: 'pointer',
'&:hover': {
color: theme.palette.type === 'dark' ? '#AAA' : '#666',
}
},
headerTranslated: {
borderColor: '#009c4f',
borderWidth: '0 0 0 3px',
padding: 10,
marginTop: 5,
marginBottom: 5,
borderStyle: 'solid',
background: '#bdded5',
cursor: 'pointer',
'&:before': {
content: `url(${IconGlobe})`,
marginRight: 10,
color: '#000000',
height: 20,
width: 20,
}
},
license: {
paddingLeft: 10,
fontWeight: 'bold',
marginTop: 0,
paddingTop: 1,
},
mdLink: {
cursor: 'pointer',
textDecoration: 'underline',
'&:after': {
//content: '"🔗"',
content: 'url(' + IconLink + ')',
width: 16,
height: 16,
opacity: 0.7,
fontSize: 14,
//marginLeft: 5
}
},
mdHeaderLink: {
textDecoration: 'none',
'&:after': {
content: '"🔗"',
width: 16,
height: 16,
opacity: 0,
fontSize: 14,
//marginLeft: 5
},
'&:hover:after': {
opacity: 0.7,
}
},
info: {
paddingTop: 10,
paddingBottom: 10,
},
email: {
fontStyle: 'italic',
cursor: 'pointer',
textDecoration: 'underline'
},
name: {
fontStyle: 'italic'
},
table: {
width: 'auto',
},
tableHead: {
background: '#555555',
},
tableRowHead: {
height: 24,
},
tableCellHead: {
color: '#FFFFFF',
padding: '3px 10px',
border: '1px solid rgba(224, 224, 224, 1)',
margin: 0,
'&>p': {
margin: 0,
}
},
tableBody: {
},
tableRow: {
height: 24,
},
tableCell: {
padding: '3px 10px',
margin: 0,
border: '1px solid rgba(224, 224, 224, 1)',
'&>p': {
margin: 0,
}
},
summary: {
transition: 'background 0.5s, color: 0.5s',
fontSize: 20,
backgroundColor: theme.palette.type === 'dark' ? '#444' : '#DDD'
},
summaryExpanded: {
//fontWeight: 'bold',
},
warn: {
borderColor: '#0b87da',
borderWidth: '0 0 0 3px',
padding: 10,
marginTop: 5,
marginBottom: 5,
borderStyle: 'solid',
background: '#eff6fb',
'&:before': {
content: '"⚠"',
//borderRadius: '50%',
//background: '#008aff',
}
},
alarm: {
borderColor: '#da0b50',
borderWidth: '0 0 0 3px',
padding: 10,
marginTop: 5,
marginBottom: 5,
borderStyle: 'solid',
background: '#fbeff3',
'&:before': {
content: '"⚠"',
//borderRadius: '50%',
//background: '#008aff',
}
},
notice: {
borderColor: '#9c989b',
borderWidth: '0 0 0 3px',
padding: 10,
marginTop: 5,
marginBottom: 5,
borderStyle: 'solid',
background: '#dedede',
'&:before': {
content: '"✋"',
//borderRadius: '50%',
//background: '#dedede',
}
},
todo: {
borderColor: '#00769c',
borderWidth: '0 0 0 3px',
paddingLeft: 10,
paddingRight: 10,
paddingTop: 0,
paddingBottom: 0,
marginTop: 5,
marginBottom: 5,
borderStyle: 'solid',
background: '#c4d2de',
/*&:before': {
content: '"✋"',
//borderRadius: '50%',
//background: '#dedede',
}*/
},
paragraph: {
},
changeLog: {
display: 'block',
width: '100%'
},
changeLogDiv: {
display: 'block',
paddingBottom: theme.spacing(2),
'&:hover': {
backgroundColor: theme.palette.type === 'dark' ? '#333' : '#DDD',
},
width: '100%'
},
changeLogVersion: {
fontWeight: 'bold',
fontSize: 18,
},
changeLogDate: {
fontSize: 16,
fontStyle: 'italic',
marginLeft: theme.spacing(1),
opacity: 0.7
},
changeLogLine: {
display: 'block',
fontSize: 14,
marginLeft: theme.spacing(1),
'&:before': {
content: '"• "',
}
},
changeLogUL: {
paddingLeft: theme.spacing(1),
marginTop: 4,
},
changeLogAuthor: {
fontStyle: 'italic',
fontWeight: 'bold',
marginRight: theme.spacing(1),
},
changeLogLineText: {
},
changeLogAccordion: {
justifyContent: 'flex-start',
}
});
const CONVERTER_OPTIONS = {
emoji: true,
underline: true,
strikethrough: true,
simplifiedAutoLink: true,
parseImgDimensions: true,
splitAdjacentBlockquotes: true
};
let title;
const ADAPTER_CARD = ['version', 'authors', 'keywords', 'mode', 'materialize', 'compact'];
const EXPAND_LANGUAGE = {
en: 'english',
de: 'german',
ru: 'russian',
'zh-cn': 'chinese (simplified)'
};
class Markdown extends Component {
constructor(props) {
super(props);
// load page
this.state = {
parts: [],
title: '',
loadTimeout: false,
header: {},
content: {},
license: '',
changeLog: '',
tooltip: '',
text: this.props.text || '',
notFound: false,
affiliate: null,
adapterNews: null,
hideContent: window.localStorage ? window.localStorage.getItem('Docs.hideContent') === 'true' : false,
};
if (!title) {
title = window.title;
}
this.mounted = false;
if (!this.state.text) {
this.load();
// Give 300ms to load the page. After that show the loading indicator.
setTimeout(() => !this.state.parts.length && this.setState({loadTimeout: true}), 300);
} else {
this.parseText();
}
this.contentRef = React.createRef();
this.customLink = ({ text, link }) =>
<a className={this.props.classes.mdLink + ' md-link'} onClick={() => {
if (link) {
if (link.startsWith('#')) {
this.onNavigate(Utils.text2link(link.substring(1)))
} else {
let href = link;
if (!href.match(/^https?:\/\//)) {
const parts = (this.props.path || '').split('/');
// const fileName = parts.pop();
const prefix = parts.join('/') + '/';
href = prefix + link;
}
this.onNavigate(null, href);
}
}
}} title={link}>{text}</a>;
/*
if (reactObj && (reactObj.type === 'h1' || reactObj.type === 'h2' || reactObj.type === 'h3' || reactObj.type === 'h3')) {
reactObj.props.children[0] = (<span>{reactObj.props.children[0]}<a
href={prefix + '?' + reactObj.props.id}
className={this.props.classes.mdHeaderLink + ' md-h-link'}>
</a></span>);
}
*/
this.customH = ({text, id, level, prefix}) => {
const _level = parseInt(level, 10);
if (_level === 1) {
return <h1 id={id}><span>{text}</span><a href={prefix + '?' + id} className={this.props.classes.mdHeaderLink + ' md-h-link'}/></h1>;
} else if (_level === 2) {
return <h2 id={id}><span>{text}</span><a href={prefix + '?' + id} className={this.props.classes.mdHeaderLink + ' md-h-link'}/></h2>;
} else if (_level === 3) {
return <h3 id={id}><span>{text}</span><a href={prefix + '?' + id} className={this.props.classes.mdHeaderLink + ' md-h-link'}/></h3>;
} else if (_level === 4) {
return <h4 id={id}><span>{text}</span><a href={prefix + '?' + id} className={this.props.classes.mdHeaderLink + ' md-h-link'}/></h4>;
} else if (_level === 5) {
return <h5 id={id}><span>{text}</span><a href={prefix + '?' + id} className={this.props.classes.mdHeaderLink + ' md-h-link'}/></h5>;
} else {
return <h6 id={id}><span>{text}</span><a href={prefix + '?' + id} className={this.props.classes.mdHeaderLink + ' md-h-link'}/></h6>;
}
};
}
componentDidMount() {
this.mounted = true;
this.state.text && this.parseText(this.state.text);
this.props.socket && this.props.socket.getRepository()
.then(repo => this.setState({adapterNews: repo[this.props.adapter]?.news}))
}
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
if (this.props.path !== nextProps.path) {
this.mounted && this.setState({notFound: false, parts :[]});
this.load(nextProps.path);
} else if (this.props.text !== nextProps.text) {
this.setState({text: nextProps.text});
if (!nextProps.text) {
if (this.props.path !== nextProps.path) {
this.mounted && this.setState({notFound: false, parts :[]});
this.load(nextProps.path);
}
} else {
this.mounted && this.setState({text: nextProps.text}, () =>
this.parseText());
}
} else
if (this.props.language !== nextProps.language) {
this.mounted && this.setState({notFound: false, parts :[]});
this.load(null, nextProps.language);
}
}
/*onHashChange(location) {
location = location || Router.getLocation();
if (location.chapter) {
const el = window.document.getElementById(location.chapter);
el && el.scrollIntoView(true);
}
}*/
onNavigate(id, link) {
if (link && link.match(/^https?:\/\//)) {
Utils.openLink(link);
} else if (id) {
const el = window.document.getElementById(id) || window.document.getElementById(id.replace('nbsp', ''));
if (el) {
el.scrollIntoView(true);
}
} else if (link) {
// if relative path
if (!link.startsWith('#')) {
// ../../download
/*const ppp = link.replace(this.props.path + '/', '').split('#');
let _link = ppp[1];
let _path = ppp[0].replace(/\.MD$/, '.md');
if (!_path.endsWith('.md')) {
_path += '.md';
}
const location = Router.getLocation();
if (_path.startsWith('.')) {
const parts = _path.split('/');
const locParts = location.page.split('/');
locParts.pop();
parts.forEach(part => {
if (part === '.') return;
if (part === '..') {
locParts.pop();
return;
}
locParts.push(part);
});
_path = locParts.join('/')
}
this.props.onNavigate(null, this.props.rootPath || location.tab, _path, _link);*/
} else if (link) {
//this.props.onNavigate(null, null, link);
link = link.replace(/^#/, '');
const el = window.document.getElementById(link) || window.document.getElementById(link.replace('nbsp', ''));
if (el) {
el.scrollIntoView(true);
}
}
}
}
parseChangeLog(changeLog) {
const lines = changeLog.split('\n');
const entries = {};
let oneEntry;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (line.startsWith('##')) {
if (oneEntry) {
entries[oneEntry.version] = oneEntry;
oneEntry = null;
}
// ### 3.0.5 (2020-10-30) or ### 3.0.5 [2020-10-30] or ### 3.0.5
const [version, date] = line.replace(/^#+\s?/, '').split(/[\s([]+/);
if (version) {
oneEntry = {lines: []};
oneEntry.version = version.trim();
oneEntry.date = (date || '').trim().replace(/\)/, '');
}
} else if (line.trim() && oneEntry) {
// extract author
// *(bluefox) if group
line = line.replace(/^[+*]+\s?/, '').trim();
if (line.startsWith('(') && line.includes(')')) {
const p = line.split(')');
const author = p[0].replace('(', '');
line = line.replace('(' + author + ')', '').trim();
oneEntry.lines.push({author, line});
} else {
oneEntry.lines.push(line);
}
}
}
if (oneEntry) {
entries[oneEntry.version] = oneEntry;
}
return entries;
}
parseText(text) {
text = text || this.state.text || '';
if (this.props.editEnabled) {
this.editText = text;
}
if (!text || text.startsWith('<!DOCTYPE html>')) {
// page not found
return this.setState({notFound: true});
}
const {header, parts, content, license, changeLog, title} = this.format(text);
let _title = header.title || title || Utils.getTitle(text);
/*if (_title) {
window.document.title = _title;
} else if (title) {
_title = title;
window.document.title = title;
}*/
let affiliate = null;
if (header.affiliate) {
try {
affiliate = JSON.parse(header.affiliate);
} catch (e) {
console.error('Cannot parse affiliate: ' + header.affiliate);
}
}
let _changeLog;
// try to add missing news
if (changeLog) {
// split news
_changeLog = this.parseChangeLog(changeLog);
if (_changeLog && typeof _changeLog === 'object' && this.state.adapterNews) {
const lang = I18n.getLanguage();
Object.keys(this.state.adapterNews).forEach(version => {
if (!_changeLog[version]) {
let news = this.state.adapterNews[version];
if (typeof news === 'object') {
news = news[lang] || news.en || '';
}
_changeLog[version] = {version, lines: news.split('\\n')};
}
});
}
}
this.mounted && this.setState({
affiliate,
notFound: false,
parts,
header,
loadTimeout: false,
content,
license,
changeLog: _changeLog || changeLog,
title: _title
});
this.onHashChange && setTimeout(() => this.onHashChange(), 200);
}
load(path, language) {
path = path || this.props.path;
language = language || this.props.language;
if (path && language) {
fetch(`${language}${path[0] === '/' ? path : '/' + path}`)
.then(res => res.text())
.then(text => this.parseText(text));
}
}
format(text) {
text = (text || '').trim();
let {header, body} = Utils.extractHeader(text);
if (body.startsWith('# ')) {
// there is no header and readme starts with
// 
// # ioBroker IoT Adapter
}
// remove comments like <!-- -->
body = body.replace(/\r\n|\n/g, '§$§$');
body = body.replace(/<!--[^>]*-->/gm, '\n');
body = body.replace(/<! -[^>]* ->/gm, '\n'); // translator make it wrong
body = body.replace(/§\$§\$/g, '\n');
body = body.replace(/\[\*\*\*\s(.+)\s\*\*\*]/g, '[***$1***]');
body = body.replace(/\[\*\*\s(.+)\s\*\*]/g, '[**$1**]');
body = body.replace(/\[\*\s(.+)\s\*]/g, '[*$1*]');
body = body.replace(/\*\*\*\s(.+)\s\*\*\*/g, '***$1***');
body = body.replace(/\*\*\s(.+)\s\*\*/g, '**$1**');
body = body.replace(/\*\s(.+)\s\*/g, '*$1*');
body = body.replace(/`` `(.+)```/g, '```$1```');
body = Utils.removeDocsify(body);
let {parts, content, license, changeLog, title} = Utils.decorateText(body, header, `${this.props.path && (this.props.path[0] === '/' ? this.props.path : '/' + this.props.path)}`);
return {header, parts, content, license, changeLog, title};
}
formatAuthors(text) {
const parts = text.split(',').map(t => t.trim()).filter(t => t);
const authors = [];
for (let i = 0; i < parts.length; i++) {
const m = parts[i].trim().match(/<([-.\w\d_@]+)>$/);
if (m) {
const email = m[1];
authors.push(<span key={parts[i]} className={this.props.classes.email} title={I18n.t('Click to copy %s', email)} onClick={e => {
Utils.onCopy(e, email);
this.setState({tooltip: I18n.t('Copied')});
}}>{parts[i].replace(m[0], '').trim() + (parts.length - 1 === i ? '' : ', ')}</span>);
} else {
authors.push(<span key={parts[i]} className={this.props.classes.name}>{parts[i] + (parts.length - 1 === i ? '' : ', ')}</span>);
}
}
return authors;
}
renderHeader() {
const data = [];
if (this.state.header.translatedFrom) {
let translatedFrom = EXPAND_LANGUAGE[this.state.header.translatedFrom] || this.state.header.translatedFrom;
// Translate language from english to actual language
translatedFrom = I18n.t(translatedFrom);
data.push(<div
key="translatedFrom"
className={this.props.classes.headerTranslated}
onClick={() => {
if (this.props.onNavigate) {
this.props.onNavigate && this.props.onNavigate(this.state.header.translatedFrom);
} else {
// read this.props.link
fetch(this.props.link)
.then(res => res.text())
.then(text => this.setState({text}, () =>
this.parseText()))
.catch(e => window.alert(`Cannot fetch "${this.props.link}": ${e}`));
}
}}
title={I18n.t('Go to original')}
>{I18n.t('Translated from %s', translatedFrom)}
</div>);
}
if (this.state.header.adapter) {
data.push(<h1 key="h1">{[
this.state.header.logo ? <img key="logo" src={'https://www.iobroker.net/' + this.state.header.logo} alt="logo" className={this.props.classes.logoImage}/> : null,
<div key="title" className={this.props.classes.titleText}>{this.state.header.title}</div>
]}</h1>);
if (this.state.header.readme) {
const link = this.state.header.readme.replace(/blob\/master\/README.md$/, '');
data.push(<IconButton key="github" title={I18n.t('Open repository')} onClick={() => Utils.openLink(link)}><IconGithub/></IconButton>);
}
}
if (this.state.header.description) {
data.push(<span key="description" className={this.props.classes.description}>{this.state.header.description}</span>);
}
if (Object.keys(this.state.header).find(attr => ADAPTER_CARD.indexOf(attr) !== -1)) {
data.push(<Accordion key="header" className={this.props.classes.adapterCard}>
<AccordionSummary className={this.props.classes.summary} classes={{expanded: this.props.classes.summaryExpanded}} expandIcon={<IconExpandMore />}>{I18n.t('Information')}</AccordionSummary>
<AccordionActions><List>{
ADAPTER_CARD
.filter(attr => this.state.header.hasOwnProperty(attr))
.map(attr =>
<ListItem key={attr} className={this.props.classes.adapterCardListItem}>
<div className={this.props.classes.adapterCardAttr}>{I18n.t(attr)}: </div>
<span>{attr === 'authors' ? this.formatAuthors(this.state.header[attr]) : this.state.header[attr].toString()}</span>
</ListItem>)}
</List></AccordionActions>
</Accordion>);
}
if (Object.keys(this.state.header).find(attr => attr.startsWith('BADGE-'))) {
data.push(<Accordion key="header_badges" className={this.props.classes.adapterCard}>
<AccordionSummary className={this.props.classes.summary} classes={{expanded: this.props.classes.summaryExpanded}} expandIcon={<IconExpandMore />}>{I18n.t('Badges')}</AccordionSummary>
<AccordionActions classes={{root: this.props.classes.badgesDetails}}>{
Object.keys(this.state.header).filter(attr => attr.startsWith('BADGE-'))
.map((attr, i) => [
this.state.header[attr].indexOf('nodei.co') !== -1 ? (<br key={'br' + i}/>) : null,
<img key={'img' + i} src={this.state.header[attr]} alt={attr.substring(6)}/>
])}
</AccordionActions>
</Accordion>);
}
return data;
}
renderInfo() {
return <div className={this.props.classes.info}>
{this.state.header.lastChanged ? [
<span key="lastChangedTitle" className={this.props.classes.infoTitle}>{I18n.t('Last changed:')} </span>,
<span key="lastChangedValue" className={this.props.classes.infoValue}>{this.state.header.lastChanged}</span>,
] : null}
{this.props.editMode && this.state.header.editLink ?
<a className={this.props.classes.infoEdit}
href={this.state.header.editLink.replace(/\/edit\//, '/blob/')}
rel="noopener noreferrer"
target="_blank"><IconGithub style={{marginRight: 4}}/>{I18n.t('See on github')}
</a> : null}
{this.props.editEnabled && this.editText ?
<div className={this.props.classes.infoEditLocal} onClick={() => {
this.props.onEditMode && this.props.onEditMode(true);
}}><IconEdit />{I18n.t('Edit local')}</div> : null}
</div>;
}
_renderSubContent(menu) {
return <ul>{
menu.children.map(item => {
const ch = this.state.content[item].children;
const link = this.state.content[item].external && this.state.content[item].link;
return <li><span onClick={() => this.onNavigate(item, link)} className={this.props.classes.contentLinks}>{this.state.content[item].title}</span>
{ch ? this._renderSubContent(this.state.content[item]) : null}
</li>;
}).filter(e => e)
}</ul>;
}
renderAffiliates() {
if (!this.state.affiliate || !this.props.affiliates) {
return null;
}
const Affiliates = this.props.affiliates;
return <Affiliates
key="affiliates"
language={this.props.language}
mobile={this.props.mobile}
theme={this.props.theme}
data={this.state.affiliate}
/>;
}
onToggleContentButton() {
this.setState({hideContent: !this.state.hideContent});
window.localStorage && window.localStorage.setItem('Docs.hideContent', this.state.hideContent ? 'false' : 'true');
}
renderContentCloseButton() {
if (this.state.hideContent) {
return <IconMenu className={this.props.classes.contentClose}/>;
} else {
return <IconClose className={this.props.classes.contentClose} onClick={() => this.onToggleContentButton()}/>;
}
}
renderContent() {
const links = Object.keys(this.state.content);
if (!links.length) {
return null;
}
if (this.state.hideContent) {
return <Paper className={this.props.classes.contentDivClosed} onClick={() => this.onToggleContentButton()}>
{this.renderContentCloseButton()}
</Paper>;
} else {
return <Paper className={this.props.classes.contentDiv}>
{this.renderContentCloseButton()}
<ul>{
links.map(item => {
const link = this.state.content[item].external && this.state.content[item].link;
const level = this.state.content[item].level;
let title = this.state.content[item].title.replace('>', '>').replace('<', '<').replace('&', '&');
return <li key={title} style={{ fontSize: 16 - level * 2, paddingLeft: level * 8, fontWeight: !level ? 'bold' : 'normal' }}>
<span onClick={() => this.onNavigate(item, link)} className={this.props.classes.contentLinks}>{title}</span>
{this.state.content[item].children ? this._renderSubContent(this.state.content[item]) : null}
</li>;
}).filter(e => e)
}</ul>
</Paper>;
}
}
renderLicense() {
if (!this.state.license) {
return null;
} else {
const CustomLink = this.customLink;
const CustomH = this.customH;
return <Accordion>
<AccordionSummary
className={this.props.classes.summary}
classes={{expanded: this.props.classes.summaryExpanded}}
expandIcon={<IconExpandMore />}>{I18n.t('License')} <span className={this.props.classes.license}> {this.state.header.license}</span></AccordionSummary>
<AccordionActions>
<MarkdownView markdown={this.state.license} options={CONVERTER_OPTIONS} components={{CustomLink, CustomH}}/>
</AccordionActions>
</Accordion>;
}
}
renderChangeLogLines() {
const classes = this.props.classes;
const versions = Object.keys(this.state.changeLog);
try {
versions.sort(semver.gt);
} catch (e) {
console.warn('Cannot semver: ' + e);
}
return <div className={classes.changeLog} key="change-log">{versions.map(version => {
const item = this.state.changeLog[version];
return <div key={version} className={classes.changeLogDiv}>
<div className={classes.changeLogVersion}>{version}{item.date ? <span className={classes.changeLogDate}>{item.date }</span> : ''}</div>
<ul className={classes.changeLogUL}>{item.lines.map((line, i) => typeof line === 'object' ?
<li key={i} className={classes.changeLogLine}><span className={classes.changeLogAuthor}>{line.author}</span><span className={classes.changeLogLineText}>{line.line}</span></li>
:
<li key={i} className={classes.changeLogLine}><span className={classes.changeLogLineText}>{line}</span></li>
)}</ul>
</div>
})}</div>;
}
renderChangeLog() {
if (!this.state.changeLog) {
return null;
} else {
const CustomLink = this.customLink;
const CustomH = this.customH;
return <Accordion>
<AccordionSummary className={this.props.classes.summary} classes={{expanded: this.props.classes.summaryExpanded}} expandIcon={<IconExpandMore />}>{I18n.t('Changelog')}</AccordionSummary>
<AccordionActions classes={{root: this.props.classes.changeLogAccordion}}>
{typeof this.state.changeLog === 'string' ?
<MarkdownView markdown={this.state.changeLog} options={CONVERTER_OPTIONS} components={{CustomLink, CustomH}}/>
:
this.renderChangeLogLines()
}
</AccordionActions>
</Accordion>;
}
}
renderSnackbar() {
return <Snackbar
anchorOrigin={{vertical: 'top', horizontal: 'right'}}
open={!!this.state.tooltip}
autoHideDuration={6000}
onClose={() => this.setState({tooltip: ''})}
message={<span id="message-id">{this.state.tooltip}</span>}
action={[
<IconButton
key="close"
color="inherit"
className={this.props.classes.close}
onClick={() => this.setState({tooltip: ''})}
>
<IconClose/>
</IconButton>,
]}
/>;
}
replaceHref(line) {
if (!line) {
return '';
}
const m = line.match(/\[.*]\(#[^)]+\)/g);
if (m) {
m.forEach(link => {
const pos = link.lastIndexOf('](');
let text = link.substring(0, pos).replace(/^\[/, '');
let href = link.substring(pos + 2).replace(/\)$/, '');
line = line.replace(link, `<CustomLink text="${text}" link="${href}" />`);
});
}
const mm = line.match(/!?\[.*]\([^)]+\)/g);
if (mm) {
// https://raw.githubusercontent.com/ioBroker/ioBroker.iot/master/README.md
// https://github.com/ioBroker/ioBroker.iot/blob/master/README.md
const prefixHttp = this.props.link
.substring(0, this.props.link.lastIndexOf('/'))
.replace('https://raw.githubusercontent.com/', 'https://github.com/')
.replace(/\/master$/, '/blob/master');
const prefixImage = this.props.link.substring(0, this.props.link.lastIndexOf('/'));
mm.forEach(link => {
const isImage = link.startsWith('!');
link = link.replace(/^!/, '');
const pos = link.lastIndexOf('](');
let text = link.substring(0, pos).replace(/^\[/, '');
let href = link.substring(pos + 2).replace(/\)$/, '');
if (!href.startsWith('http')) {
if (isImage) {
line = line.replace(link, `[${text}](${prefixImage}/${href})`);
} else {
// <a href="http://www.google.com" target="blank">google</a>
line = line.replace(link, `<a href="${prefixHttp}/${href}" target="blank">${text}</a>`);
}
} else if (!isImage) {
line = line.replace(link, `<a href="${href}" target="blank">${text}</a>`);
}
});
}
return line;
/*const parts = (this.props.path || '').split('/');
// const fileName = parts.pop();
const prefix = parts.join('/') + '/';
if (reactObj && reactObj.props && reactObj.props.children) {
reactObj.props.children.forEach((item, i) => {
if (item && item.type === 'a') {
let link = item.props.href;
if (link) {
if (link.startsWith('#')) {
link = Utils.text2link(link.substring(1));
reactObj.props.children[i] = (<div
key={'link' + i}
className={this.props.classes.mdLink + ' md-link'}
title={link}
onClick={() => this.onNavigate(link)}>
{item.props.children ? item.props.children[0] : ''}
</div>);
} else {
const oldLink = link;
if (!link.match(/^https?:\/\//)) {
link = prefix + link;
}
reactObj.props.children[i] = (<div
key={'link' + i}
className={this.props.classes.mdLink + ' md-link'}
title={oldLink}
onClick={() => this.onNavigate(null, link)}>
{item.props.children ? item.props.children[0] : ''}
</div>);
}
}
}
if (typeof item === 'object') {
this.replaceHref(item);
}
});
}*/
}
makeHeadersAsLink(line, prefix) {
if (!line) {
return '';
}
const mm = line.match(/^#+\s.+/g);
if (mm) {
mm.forEach(header => {
const level = header.match(/^(#+)\s/)[1].length;
let text = header.substring(level + 1);
line = line.replace(header, `<CustomH text="${text}" id="${Utils.text2link(text)}" level="${level}" prefix="${prefix}"/>`);
});
}
return line;
/*if (reactObj && (reactObj.type === 'h1' || reactObj.type === 'h2' || reactObj.type === 'h3' || reactObj.type === 'h3')) {
reactObj.props.children[0] = (<span>{reactObj.props.children[0]}<a
href={prefix + '?' + reactObj.props.id}
className={this.props.classes.mdHeaderLink + ' md-h-link'}>
</a></span>);
}*/
}
renderTable(lines, key) {
const header = lines[0].replace(/^\||\|$/g, '').split('|').map(h => h.trim());
const CustomLink = this.customLink;
const CustomH = this.customH;
const rows = [];
for (let i = 2; i < lines.length; i++) {
const parts = lines[i].replace(/^\||\|$/g, '').split('|').map(a => a.trim());
const cells = [];
for (let j = 0; j < header.length; j++) {
parts[j] = this.replaceHref(parts[j]);
const crt = <MarkdownView markdown={parts[j] || ''} options={CONVERTER_OPTIONS} components={{CustomLink, CustomH}}/>;
cells.push(<TableCell className={this.props.classes.tableCell} key={'cell' + i + '_' + j}>{crt}</TableCell>);
}
rows.push(<TableRow className={this.props.classes.tableRow} key={'row' + i}>{cells}</TableRow>);
}
return <Table key={'table_' + key} size="small" className={this.props.classes.table}>
<TableHead className={this.props.classes.tableHead}>
<TableRow className={this.props.classes.tableRowHead}>
{
header.map((h, i) =>
<TableCell className={this.props.classes.tableCellHead} key={'header' + i}>
<MarkdownView markdown={h} options={CONVERTER_OPTIONS} components={{CustomLink, CustomH}}/>
</TableCell>)
}
</TableRow>
</TableHead>
<TableBody className={this.props.classes.tableBody}>{rows}</TableBody>
</Table>;
}
render() {
if (this.state.notFound) {
return null; //<Page404 className={this.props.classes.root} language={this.props.language}/>;
}
if (this.props.editMode && this.props.editor) {
const Editor = this.props.editor;
return <Editor
language={this.props.language}
mobile={this.props.mobile}
theme={this.props.theme}
path={this.state.header.editLink}
onClose={() => this.props.onEditMode && this.props.onEditMode(false)}
/>;
}
if (this.state.loadTimeout && !this.state.parts.length) {
return <Loader theme={this.props.theme}/>;
}
const prefix = window.location.hash.split('?')[0];
const CustomLink = this.customLink;
const CustomH = this.customH;
const reactElements = this.state.parts.map((part, i) => {
if (part.type === 'table') {
return this.renderTable(part.lines, i);
} else {
let line = part.lines.join('\n');
if (part.type === 'code') {
line = line.trim().replace(/^```javascript/, '```');
}
const trimmed = line.trim();
if (trimmed.match(/^\*[^\s]/) && trimmed.match(/[^\s]\*$/)) {
line = trimmed;
}
// find all "[text](#link)" and replace it with <link text="text" link="link"/>
// Detect "[iobroker repo \[repoName\]](#iobroker-repo)"
line = this.replaceHref(line);
line = this.makeHeadersAsLink(line, prefix);
// replace <- with <
line = line.replace(/<-/g, '<-');
line = line.replace(/<\/ br>/g, '<br/>');
const rct = <MarkdownView markdown={line} options={CONVERTER_OPTIONS} components={{CustomLink, CustomH}}/>;
if (part.type === 'warn') {
return <div key={'parts' + i} className={this.props.classes.warn}>{rct}</div>;
} else if (part.type === 'alarm') {
return <div key={'parts' + i} className={this.props.classes.alarm}>{rct}</div>;
} else if (part.type === 'notice') {
return <div key={'parts' + i} className={this.props.classes.notice}>{rct}</div>;
} else if (part.type === '@@@') {
return <div key={'parts' + i} className={this.props.classes.todo}>{rct}</div>;
} else {
return <div key={'parts' + i} className={this.props.classes.paragraph}>{rct}</div>;
}
}
});
return <div className={Utils.clsx(this.props.classes.root, this.props.className)} ref={this.contentRef}>
{this.renderHeader()}
{this.state.title && !this.state.header.adapter ? <h1>{this.state.title}</h1> : null}
{this.renderAffiliates()}
{reactElements}
<hr/>
{this.renderLicense()}
{this.renderChangeLog()}
{this.renderInfo()}
{this.renderContent()}
{this.renderSnackbar()}
</div>;
}
}
Markdown.propTypes = {
language: PropTypes.string,
onNavigate: PropTypes.func,
theme: PropTypes.object,
themeName: PropTypes.string,
themeType: PropTypes.string,
mobile: PropTypes.bool,
rootPath: PropTypes.string,
path: PropTypes.string,
text: PropTypes.string,
editMode: PropTypes.bool,
onEditMode: PropTypes.func,
editEnabled: PropTypes.bool,
affiliates: PropTypes.object,
editor: PropTypes.object,
className: PropTypes.string,
socket: PropTypes.object,
adapter: PropTypes.string,
};
export default withStyles(styles)(Markdown);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m12 6-2-2H2v16h20V6H12zm6 6h-2v2h2v2h-2v2h-2v-2h2v-2h-2v-2h2v-2h-2V8h2v2h2v2z"
}), 'FolderZipSharp');
exports.default = _default; |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({root:{other:"Other"},ar:1,bs:1,ca:1,cs:1,da:1,de:1,el:1,es:1,et:1,fi:1,fr:1,he:1,hi:1,hr:1,hu:1,id:1,it:1,ja:1,ko:1,lv:1,lt:1,nl:1,nb:1,pl:1,"pt-br":1,"pt-pt":1,ro:1,ru:1,sl:1,sr:1,sv:1,th:1,tr:1,vi:1,"zh-cn":1,"zh-hk":1,"zh-tw":1}); |
exports.info = { FormatID: '692',
FormatName: 'Windows Media Audio',
FormatVersion: '',
FormatAliases: 'WMA',
FormatFamilies: '',
FormatTypes: 'Audio',
FormatDisclosure: 'Full',
FormatDescription: 'Windows Media Audio Format is a subtype of the Advanced Systems Format, developed by Microsoft for storing audio data streams. It comprises a Header Object, which describes the properties of the data streams, a Data Object, which contains the actual data streams stored in Data Packets and, optionally, one or more Index Objects. Audio data is stored using the Windows Media Audio codec, and the format supports streaming across networks.',
BinaryFileFormat: 'Binary',
ByteOrders: 'Little-endian (Intel)',
ReleaseDate: '01 Dec 2004',
WithdrawnDate: '',
ProvenanceSourceID: '1',
ProvenanceName: 'Digital Preservation Department / The National Archives',
ProvenanceSourceDate: '11 Mar 2005',
ProvenanceDescription: '',
LastUpdatedDate: '02 Aug 2005',
FormatNote: '',
FormatRisk: '',
TechnicalEnvironment: '',
FileFormatIdentifier:
[ { Identifier: 'audio/x-ms-wma', IdentifierType: 'MIME' },
{ Identifier: 'com.microsoft.windows-media-wma',
IdentifierType: 'Apple Uniform Type Identifier' },
{ Identifier: 'fmt/132', IdentifierType: 'PUID' } ],
Document:
{ DocumentID: '3',
DisplayText: 'Microsoft Corporation, 2004, Advanced Systems Format (ASF) Specification: Revision 01.20.03',
DocumentType: 'Authoritative',
AvailabilityDescription: 'Public',
AvailabilityNote: '',
PublicationDate: '01 Dec 2004',
TitleText: 'Advanced Systems Format (ASF) Specification: Revision 01.20.03',
DocumentIPR: '',
DocumentNote: '',
DocumentIdentifier:
{ Identifier: 'www.microsoft.com/windows/windowsmedia/format/asfspec.aspx',
IdentifierType: 'URL' },
Author:
{ AuthorID: '93',
AuthorName: '',
OrganisationName: 'Microsoft Corporation',
AuthorCompoundName: 'Microsoft Corporation' },
Publisher:
{ PublisherID: '93',
PublisherName: '',
OrganisationName: 'Microsoft Corporation',
PublisherCompoundName: 'Microsoft Corporation' } },
ExternalSignature:
[ { ExternalSignatureID: '613',
Signature: 'wma',
SignatureType: 'File extension' },
{ ExternalSignatureID: '731',
Signature: 'asf',
SignatureType: 'File extension' } ],
InternalSignature:
{ SignatureID: '81',
SignatureName: 'Windows Media Audio',
SignatureNote: 'Header Object + Stream Properties Object (stream type = Audio Stream) with WMA Codec ID',
ByteSequence:
[ { ByteSequenceID: '148',
PositionType: 'Absolute from BOF',
Offset: '0',
MaxOffset: '',
IndirectOffsetLocation: '',
IndirectOffsetLength: '',
Endianness: '',
ByteSequenceValue: '3026B2758E66CF11A6D900AA0062CE6C{12}0102' },
{ ByteSequenceID: '149',
PositionType: 'Variable',
Offset: '',
MaxOffset: '',
IndirectOffsetLocation: '',
IndirectOffsetLength: '',
Endianness: '',
ByteSequenceValue: '{30}9107DCB7B7A9CF118EE600C00C205365{8}409E69F84D5BCF11A8FD00805F5C442B{38}(6101|6201|6301)' } ] },
RelatedFormat:
[ { RelationshipType: 'Has lower priority than',
RelatedFormatID: '693',
RelatedFormatName: 'Windows Media Video',
RelatedFormatVersion: '' },
{ RelationshipType: 'Has lower priority than',
RelatedFormatID: '1228',
RelatedFormatName: 'Windows Media Video 9 Advanced Profile (WVC1)',
RelatedFormatVersion: '9 Advanced Profile (WVC1)' },
{ RelationshipType: 'Has priority over',
RelatedFormatID: '691',
RelatedFormatName: 'Advanced Systems Format',
RelatedFormatVersion: '' },
{ RelationshipType: 'Is subtype of',
RelatedFormatID: '691',
RelatedFormatName: 'Advanced Systems Format',
RelatedFormatVersion: '' } ] } |
'use strict';
var mongoose = require('mongoose');
var chai = require('chai');
var chaihttp = require('chai-http');
chai.use(chaihttp);
var expect = chai.expect;
var Note = require('../note.js');
process.env.MONGOLAB_URI = 'mongodb://localhost/restAPI';
require('../app');
describe('REST api', function() {
var noteId = null;
after(function(done) {
mongoose.connection.db.dropDatabase(function() {
done();
});
});
it('should POST a new note to be tested', function(done) {
chai.request('localhost:8888')
.post('/note')
.send({author:'test', body:'test'})
.end(function(err, res) {
expect(err).to.eql(null);
expect(res.body.author).to.eql('test');
noteId = res.body._id;
expect(res.body).to.have.property('_id');
done();
});
});
it('should GET the notes', function(done) {
chai.request('localhost:8888')
.get('/note')
.end(function(err, res) {
expect(err).to.eql(null);
expect(typeof res.body).to.eql('object');
done();
});
});
describe('new note for test', function() {
beforeEach(function(done) {
var testNote = new Note({noteBody: 'test note'});
testNote.save(function(err, data) {
if(err) throw err;
this.testNote = data;
done();
}.bind(this));
});
it('should update a note', function(done) {
var id = this.testNote._id;
chai.request('localhost:8888')
.put('/note' + id)
.send({noteBody: 'here is a new note'})
.end(function(err, res) {
expect(err).to.eql(null);
done();
});
});
});
describe('404 route', function() {
it('should 404 if you go to a bad path', function(done) {
chai.request('localhost:8888')
.get('/badbadbadroute')
.end(function(err, res) {
expect(err).to.equal(null);
expect(res.status).to.equal(404);
done();
});
});
});
});
|
/**
* o--------------------------------------------------------------------------------o
* | This file is part of the RGraph package. RGraph is Free Software, licensed |
* | under the MIT license - so it's free to use for all purposes. If you want to |
* | donate to help keep the project going then you can do so here: |
* | |
* | http://www.rgraph.net/donate |
* o--------------------------------------------------------------------------------o
*/
RGraph = window.RGraph || {isRGraph: true};
/**
* The constructor
*
* @param object id The canvas tag ID
* @param array min The minimum value
* @param array max The maximum value
* @param array value The indicated value
*/
RGraph.CornerGauge = function (id, min, max, value)
{
var tmp = RGraph.getCanvasTag(id);
// Get the canvas and context objects
this.id = tmp[0];
this.canvas = tmp[1];
this.context = this.canvas.getContext ? this.canvas.getContext("2d") : null;
this.canvas.__object__ = this;
this.type = 'cornergauge';
this.min = min;
this.max = max;
this.value = value;
this.angles = {};
this.angles.needle = [];
this.centerpin = {};
this.isRGraph = true;
this.currentValue = null;
this.uid = RGraph.CreateUID();
this.canvas.uid = this.canvas.uid ? this.canvas.uid : RGraph.CreateUID();
this.coordsText = [];
this.original_colors = [];
/**
* Range checking
*/
if (typeof(this.value) == 'object') {
for (var i=0; i<this.value.length; ++i) {
if (this.value[i] > this.max) this.value[i] = max;
if (this.value[i] < this.min) this.value[i] = min;
}
} else {
if (this.value > this.max) this.value = max;
if (this.value < this.min) this.value = min;
}
/**
* Compatibility with older browsers
*/
//RGraph.OldBrowserCompat(this.context);
// Various config type stuff
this.properties =
{
'chart.centerx': null,
'chart.centery': null,
'chart.radius': null,
'chart.gutter.left': 25,
'chart.gutter.right': 25,
'chart.gutter.top': 25,
'chart.gutter.bottom': 25,
'chart.strokestyle': 'black',
'chart.linewidth': 2,
'chart.title': '',
'chart.title.vpos': 0.5,
'chart.title.size': null,
'chart.title.x': null,
'chart.title.y': null,
'chart.title.bold': true,
'chart.text.font': 'Arial',
'chart.text.color': '#666',
'chart.text.size': 10,
'chart.background.gradient.color1': '#ddd',
'chart.background.gradient.color2': 'white',
'chart.shadow': true,
'chart.shadow.color': 'gray',
'chart.shadow.offsetx': 0,
'chart.shadow.offsety': 0,
'chart.shadow.blur': 15,
'chart.scale.decimals': 0,
'chart.scale.point': '.',
'chart.scale.thousand': ',',
'chart.units.pre': '',
'chart.units.post': '',
'chart.resizable': false,
'chart.chart.resize.handle.background': null,
'chart.adjustable': false,
'chart.annotatable': false,
'chart.annotate.color': 'black',
'chart.colors.ranges': null,
'chart.red.start': min + (0.9 * (this.max - min)),
'chart.green.end': min + (0.7 * (this.max - min)),
'chart.red.color': 'red',
'chart.yellow.color': 'yellow',
'chart.green.color': '#0f0',
'chart.value.text': true,
'chart.value.text.units.pre': '',
'chart.value.text.units.post': '',
'chart.value.text.boxed': true,
'chart.value.text.font': 'Arial',
'chart.value.text.size': 18,
'chart.value.text.bold': false,
'chart.value.text.decimals': 0,
'chart.centerpin.stroke': 'rgba(0,0,0,0)',
'chart.centerpin.fill': null, // Set in the DrawCenterpin function
'chart.centerpin.color': 'blue',
'chart.needle.colors': ['#ccc', '#D5604D', 'red', 'green', 'yellow'],
'chart.zoom.factor': 1.5,
'chart.zoom.fade.in': true,
'chart.zoom.fade.out': true,
'chart.zoom.hdir': 'right',
'chart.zoom.vdir': 'down',
'chart.zoom.frames': 25,
'chart.zoom.delay': 16.666,
'chart.zoom.shadow': true,
'chart.zoom.background': true
}
/*
* Translate half a pixel for antialiasing purposes - but only if it hasn't beeen
* done already
*/
if (!this.canvas.__rgraph_aa_translated__) {
this.context.translate(0.5,0.5);
this.canvas.__rgraph_aa_translated__ = true;
}
// Short variable names
var RG = RGraph;
var ca = this.canvas;
var co = ca.getContext('2d');
var prop = this.properties;
var jq = jQuery;
var pa = RG.Path;
var win = window;
var doc = document;
var ma = Math;
/**
* An all encompassing accessor
*
* @param string name The name of the property
* @param mixed value The value of the property
*/
this.set =
this.Set = function (name, value)
{
name = name.toLowerCase();
/**
* This should be done first - prepend the property name with "chart." if necessary
*/
if (name.substr(0,6) != 'chart.') {
name = 'chart.' + name;
}
prop[name] = value;
return this;
};
/**
* An all encompassing accessor
*
* @param string name The name of the property
*/
this.get =
this.Get = function (name)
{
/**
* This should be done first - prepend the property name with "chart." if necessary
*/
if (name.substr(0,6) != 'chart.') {
name = 'chart.' + name;
}
return prop[name];
};
/**
* The function you call to draw the line chart
*/
this.draw =
this.Draw = function ()
{
/**
* Fire the onbeforedraw event
*/
RG.FireCustomEvent(this, 'onbeforedraw');
/**
* Store the value (for animation primarily
*/
this.currentValue = this.value;
if (typeof this.gutterLeft == 'undefined') {
this.gutterLeft = prop['chart.gutter.left'];
this.gutterRight = prop['chart.gutter.right'];
this.gutterTop = prop['chart.gutter.top'];
this.gutterBottom = prop['chart.gutter.bottom'];
}
/**
* Work out the radius first
*/
this.radius = Math.min(
(ca.width - this.gutterLeft - this.gutterRight),
(ca.height - this.gutterTop - this.gutterBottom)
);
if (typeof(prop['chart.radius']) == 'number') this.radius = prop['chart.radius'];
/**
* Now use the radius in working out the centerX/Y
*/
this.centerx = (ca.width / 2) - (this.radius / 2) + Math.max(30, this.radius * 0.1);
this.centery = (ca.height / 2) + (this.radius / 2) - (this.radius * 0.1);
if (typeof prop['chart.centerx'] === 'number') this.centerx = prop['chart.centerx'];
if (typeof prop['chart.centery'] === 'number') this.centery = prop['chart.centery'];
/**
* Parse the colors for gradients. Its down here so that the center X/Y can be used
*/
if (!this.colorsParsed) {
this.parseColors();
// Don't want to do this again
this.colorsParsed = true;
}
/**
* Start with the background
*/
this.DrawBackGround();
/**
* Draw the tickmarks
*/
this.DrawTickmarks();
/**
* Draw the color bands
*/
this.DrawColorBands();
/**
* Draw the label/value in text
*/
this.DrawLabel();
/**
* Start with the labels/scale
*/
this.DrawLabels();
/**
* Draw the needle(s)
*/
if (typeof this.value === 'object') {
for (var i=0,len=this.value.length; i<len; ++i) {
this.DrawNeedle(
i,
this.value[i],
this.radius - 65
);
}
} else {
this.DrawNeedle(0, this.value, this.radius - 65);
}
/**
* Draw the centerpin of the needle
*/
this.DrawCenterpin();
/**
* Draw the title
*/
var size = prop['chart.title.size'] ? prop['chart.title.size'] : prop['chart.text.size'] + 2
prop['chart.title.y'] = this.centery + 20 - this.radius - ((1.5 * size) / 2);
RGraph.DrawTitle(this,
prop['chart.title'],
this.guttertop,
this.centerx + (this.radius / 2),
size);
/**
* Setup the context menu if required
*/
if (prop['chart.contextmenu']) {
RGraph.ShowContext(this);
}
/**
* This function enables resizing
*/
if (prop['chart.resizable']) {
RGraph.AllowResizing(this);
}
/**
* This installs the event listeners
*/
RGraph.InstallEventListeners(this);
/**
* Fire the RGraph ondraw event
*/
RGraph.FireCustomEvent(this, 'ondraw');
return this;
};
/**
* Draw the background
*/
this.drawBackGround =
this.DrawBackGround = function ()
{
if (prop['chart.shadow']) {
RGraph.SetShadow(this, prop['chart.shadow.color'], prop['chart.shadow.offsetx'], prop['chart.shadow.offsety'], prop['chart.shadow.blur']);
}
co.strokeStyle = prop['chart.strokestyle'];
co.lineWidth = prop['chart.linewidth'] ? prop['chart.linewidth'] : 0.0001;
/**
* Draw the corner circle first
*/
co.beginPath();
co.arc(this.centerx,this.centery,30,0,RGraph.TWOPI,false);
co.stroke();
/**
* Draw the quarter circle background
*/
co.beginPath();
co.moveTo(this.centerx - 20, this.centery + 20);
co.arc(this.centerx - 20,this.centery + 20,this.radius,RGraph.PI + RGraph.HALFPI, RGraph.TWOPI,false);
co.closePath();
co.fill();
co.stroke();
// ==================================================================================================================== //
RG.NoShadow(this);
co.strokeStyle = prop['chart.strokestyle'];
co.lineWidth = prop['chart.linewidth'] ? prop['chart.linewidth'] : 0.0001;
/**
* Draw the quarter circle background
*/
co.beginPath();
co.moveTo(this.centerx - 20, this.centery + 20);
co.arc(this.centerx - 20,this.centery + 20,this.radius,RGraph.PI + RGraph.HALFPI, RGraph.TWOPI,false);
co.closePath();
co.stroke();
// ==================================================================================================================== //
/**
* Draw the background background again but with no shadow on
*/
RGraph.NoShadow(this);
co.lineWidth = 0;
co.fillStyle = RGraph.RadialGradient(this, this.centerx,this.centery, 0,
this.centerx, this.centery, this.radius * 0.5,
prop['chart.background.gradient.color1'],
prop['chart.background.gradient.color2']);
// Go over the bulge again in the gradient
co.beginPath();
co.moveTo(this.centerx, this.centery);
co.arc(this.centerx,this.centery,30,0,RGraph.TWOPI,0);
co.closePath();
co.fill();
// Go over the main part of the gauge with just the fill
co.beginPath();
co.moveTo(this.centerx - 20, this.centery + 20);
co.lineTo(this.centerx - 20, this.centery + 20 - this.radius);
co.arc(this.centerx - 20,this.centery + 20,this.radius,RGraph.PI + RGraph.HALFPI,RGraph.TWOPI,false);
co.closePath();
co.fill();
// Draw the gray background lines.
co.beginPath();
co.lineWidth = 1;
co.strokeStyle = '#eee';
for (var i=0; i<=5; ++i) {
var p1 = RG.getRadiusEndPoint(this.centerx, this.centery, (RGraph.HALFPI / 5 * i) + RGraph.PI + RGraph.HALFPI, 30);
var p2 = RG.getRadiusEndPoint(this.centerx, this.centery, (RGraph.HALFPI / 5 * i) + RGraph.PI + RGraph.HALFPI, this.radius - 90);
co.moveTo(p1[0], p1[1]);
co.lineTo(p2[0], p2[1]);
}
co.stroke();
};
/**
* Draw the needle
*/
this.drawNeedle =
this.DrawNeedle = function (index, value, radius)
{
var grad = RG.RadialGradient(this, this.centerx, this.centery, 0,
this.centerx, this.centery, 20,
'rgba(0,0,0,0)', prop['chart.needle.colors'][index])
this.angles.needle[index] = (((value - this.min) / (this.max - this.min)) * RG.HALFPI) + RG.PI + RG.HALFPI;
co.lineWidth = 1
co.strokeStyle = 'rgba(0,0,0,0)';
co.fillStyle = grad;
co.beginPath();
co.moveTo(this.centerx, this.centery);
co.arc(this.centerx,
this.centery,
10,
this.angles.needle[index] - RG.HALFPI,
this.angles.needle[index] - RG.HALFPI + 0.000001,
false);
co.arc(this.centerx,
this.centery,
radius - 30,
this.angles.needle[index],
this.angles.needle[index] + 0.000001,
false);
co.arc(this.centerx,
this.centery,
10,
this.angles.needle[index] + RG.HALFPI,
this.angles.needle[index] + RG.HALFPI + 0.000001,
false);
co.stroke();
co.fill();
};
/**
* Draw the centerpin for the needle
*/
this.drawCenterpin =
this.DrawCenterpin = function ()
{
if (!prop['chart.centerpin.fill']) {
prop['chart.centerpin.fill'] = RG.RadialGradient(this, this.centerx + 5,
this.centery - 5,
0,
this.centerx + 5,
this.centery - 5,
20,
'white',
prop['chart.centerpin.color'])
}
co.strokeStyle = prop['chart.centerpin.stroke'];
co.fillStyle = prop['chart.centerpin.fill'];
co.beginPath();
co.lineWidth = 2;
co.arc(this.centerx,this.centery, 15,0,RGraph.TWOPI,false);
co.stroke();
co.fill();
};
/**
* Drawthe labels
*/
this.drawLabels =
this.DrawLabels = function ()
{
var numLabels = 6;
co.fillStyle = prop['chart.text.color'];
for (var i=0; i<numLabels; ++i) {
co.beginPath();
var num = Number(this.min + ((this.max - this.min) * (i / (numLabels - 1)))).toFixed(prop['chart.scale.decimals']);
num = RG.number_format(this, num, prop['chart.units.pre'], prop['chart.units.post']);
var angle = (i * 18) / (180 / RG.PI);
RG.Text2(this,{'font':prop['chart.text.font'],
'size':prop['chart.text.size'],
'x':this.centerx + ma.sin(angle) * (this.radius - 53),
'y':this.centery - ma.cos(angle) * (this.radius - 53),
'text':String(num),
'valign':'top',
'halign':'center',
'angle': 90 * (i / (numLabels - 1)),
'tag': 'scale'
});
co.fill();
}
};
/**
* Drawthe tickmarks
*/
this.drawTickmarks =
this.DrawTickmarks = function ()
{
var bigTicks = 5;
var smallTicks = 25;
/**
* Draw the smaller tickmarks
*/
for (var i=0; i<smallTicks; ++i) {
co.beginPath();
var angle = (RG.HALFPI / (smallTicks - 1)) * i
co.lineWidth = 1;
co.arc(this.centerx,
this.centery,
this.radius - 44,
RG.PI + RG.HALFPI + angle,
RG.PI + RG.HALFPI + angle + 0.0001,
false);
co.arc(this.centerx,
this.centery,
this.radius - 46,
RG.PI + RG.HALFPI + angle,
RG.PI + RG.HALFPI + angle + 0.0001,
false);
co.stroke();
}
/**
* Now draw the larger tickmarks
*/
for (var i=0; i<bigTicks; ++i) {
co.beginPath();
var angle = (RG.HALFPI / (bigTicks - 1)) * i
co.lineWidth = 1;
co.arc(this.centerx,
this.centery,
this.radius - 43,
RG.PI + RG.HALFPI + angle,
RG.PI + RG.HALFPI + angle + 0.0001,
false);
co.arc(this.centerx,
this.centery,
this.radius - 47,
RG.PI + RG.HALFPI + angle,
RG.PI + RG.HALFPI + angle + 0.0001,
false);
co.stroke();
}
};
/**
* This draws the green background to the tickmarks
*/
this.DrawColorBands = function ()
{
if (RG.is_array(prop['chart.colors.ranges'])) {
var ranges = prop['chart.colors.ranges'];
for (var i=0,len=ranges.length; i<len; ++i) {
co.fillStyle = ranges[i][2];
co.lineWidth = 0;
co.beginPath();
co.arc(this.centerx,
this.centery,
this.radius - 54 - (prop['chart.text.size'] * 1.5),
(((ranges[i][0] - this.min) / (this.max - this.min)) * RG.HALFPI) + (RG.PI + RG.HALFPI),
(((ranges[i][1] - this.min) / (this.max - this.min)) * RG.HALFPI) + (RG.PI + RG.HALFPI),
false);
co.arc(this.centerx,
this.centery,
this.radius - 54 - 10 - (prop['chart.text.size'] * 1.5),
(((ranges[i][1] - this.min) / (this.max - this.min)) * RG.HALFPI) + (RG.PI + RG.HALFPI),
(((ranges[i][0] - this.min) / (this.max - this.min)) * RG.HALFPI) + (RG.PI + RG.HALFPI),
true);
co.closePath();
co.fill();
}
return;
}
/**
* Draw the GREEN region
*/
co.strokeStyle = prop['chart.green.color'];
co.fillStyle = prop['chart.green.color'];
var greenStart = RG.PI + RG.HALFPI;
var greenEnd = greenStart + (RG.TWOPI - greenStart) * ((prop['chart.green.end'] - this.min) / (this.max - this.min))
co.beginPath();
co.arc(this.centerx, this.centery, this.radius - 54 - (prop['chart.text.size'] * 1.5), greenStart, greenEnd, false);
co.arc(this.centerx, this.centery, this.radius - 54 - (prop['chart.text.size'] * 1.5) - 10, greenEnd, greenStart, true);
co.fill();
/**
* Draw the YELLOW region
*/
co.strokeStyle = prop['chart.yellow.color'];
co.fillStyle = prop['chart.yellow.color'];
var yellowStart = greenEnd;
var yellowEnd = (((prop['chart.red.start'] - this.min) / (this.max - this.min)) * RG.HALFPI) + RG.PI + RG.HALFPI;
co.beginPath();
co.arc(this.centerx, this.centery, this.radius - 54 - (prop['chart.text.size'] * 1.5), yellowStart, yellowEnd, false);
co.arc(this.centerx, this.centery, this.radius - 54 - (prop['chart.text.size'] * 1.5) - 10, yellowEnd, yellowStart, true);
co.fill();
/**
* Draw the RED region
*/
co.strokeStyle = prop['chart.red.color'];
co.fillStyle = prop['chart.red.color'];
var redStart = yellowEnd;
var redEnd = RGraph.TWOPI;
co.beginPath();
co.arc(this.centerx, this.centery, this.radius - 54 - (prop['chart.text.size'] * 1.5), redStart, redEnd, false);
co.arc(this.centerx, this.centery, this.radius - 54 - (prop['chart.text.size'] * 1.5) - 10, redEnd, redStart, true);
co.fill();
};
/**
* Draw the value in text
*/
this.drawLabel =
this.DrawLabel = function ()
{
if (prop['chart.value.text']) {
co.strokeStyle = prop['chart.text.color'];
co.fillStyle = prop['chart.text.color'];
var value = typeof(this.value) == 'number' ? this.value.toFixed(prop['chart.value.text.decimals']) : this.value;
if (typeof(value) == 'object') {
for (var i=0; i<value.length; ++i) {
value[i] = Number(value[i]).toFixed(prop['chart.value.text.decimals']);
}
value = value.toString();
}
RG.Text2(this,{'font':prop['chart.value.text.font'],
'size':prop['chart.value.text.size'],
'x':this.centerx + (ma.cos((RG.PI / 180) * 45) * (this.radius / 3)),
'y':this.centery - (ma.sin((RG.PI / 180) * 45) * (this.radius / 3)),
'text':RG.number_format(this, String(value), prop['chart.value.text.units.pre'], prop['chart.value.text.units.post']),
'valign':'center',
'halign':'center',
'bounding':prop['chart.value.text.boxed'],
'boundingFill':'white',
'bold': prop['chart.value.text.bold'],
'tag': 'value.text'
});
}
};
/**
* A placeholder function
*
* @param object The event object
*/
this.getShape = function (e) {};
/**
* A getValue method
*
* @param object e An event object
*/
this.getValue = function (e)
{
var mouseXY = RGraph.getMouseXY(e);
var mouseX = mouseXY[0];
var mouseY = mouseXY[1];
var angle = RG.getAngleByXY(this.centerx, this.centery, mouseX, mouseY);
if (angle > RG.TWOPI && angle < (RG.PI + RG.HALFPI)) {
return null;
}
var value = ((angle - (RG.PI + RG.HALFPI)) / (RG.TWOPI - (RG.PI + RG.HALFPI))) * (this.max - this.min);
value = value + this.min;
if (value < this.min) {
value = this.min
}
if (value > this.max) {
value = this.max
}
// Special case for this chart
if (mouseX > this.centerx && mouseY > this.centery) {
value = this.max;
}
return value;
};
/**
* The getObjectByXY() worker method. Don't call this call:
*
* RGraph.ObjectRegistry.getObjectByXY(e)
*
* @param object e The event object
*/
this.getObjectByXY = function (e)
{
var mouseXY = RGraph.getMouseXY(e);
if (
mouseXY[0] > (this.centerx - 5)
&& mouseXY[0] < (this.centerx + this.radius)
&& mouseXY[1] > (this.centery - this.radius)
&& mouseXY[1] < (this.centery + 5)
&& RG.getHypLength(this.centerx, this.centery, mouseXY[0], mouseXY[1]) <= this.radius
) {
return this;
}
};
/**
* This method handles the adjusting calculation for when the mouse is moved
*
* @param object e The event object
*/
this.adjusting_mousemove =
this.Adjusting_mousemove = function (e)
{
/**
* Handle adjusting for the Bar
*/
if (prop['chart.adjustable'] && RG.Registry.Get('chart.adjusting') && RG.Registry.Get('chart.adjusting').uid == this.uid) {
this.value = this.getValue(e);
RG.Clear(ca);
RG.RedrawCanvas(ca);
RG.FireCustomEvent(this, 'onadjust');
}
};
/**
* This method returns the appropriate angle for a value
*
* @param number value The value to get the angle for
*/
this.getAngle = function (value)
{
if (value < this.min || value > this.max) {
return null;
}
var angle = ((value - this.min) / (this.max - this.min)) * RG.HALFPI
angle += (RG.PI + RG.HALFPI);
return angle;
};
/**
* This allows for easy specification of gradients
*/
this.parseColors = function ()
{
// Save the original colors so that they can be restored when the canvas is reset
if (this.original_colors.length === 0) {
this.original_colors['chart.colors.ranges'] = RG.array_clone(prop['chart.colors.ranges']);
this.original_colors['chart.green.color'] = RG.array_clone(prop['chart.green.color']);
this.original_colors['chart.yellow.color'] = RG.array_clone(prop['chart.yellow.color']);
this.original_colors['chart.red.color'] = RG.array_clone(prop['chart.red.color']);
}
if (!RG.is_null(prop['chart.colors.ranges'])) {
for (var i=0; i<prop['chart.colors.ranges'].length; ++i) {
prop['chart.colors.ranges'][i][2] = this.parseSingleColorForGradient(prop['chart.colors.ranges'][i][2]);
}
} else {
prop['chart.green.color'] = this.parseSingleColorForGradient(prop['chart.green.color']);
prop['chart.yellow.color'] = this.parseSingleColorForGradient(prop['chart.yellow.color']);
prop['chart.red.color'] = this.parseSingleColorForGradient(prop['chart.red.color']);
}
};
/**
* This parses a single color value
*/
this.parseSingleColorForGradient = function (color)
{
if (!color || typeof(color) != 'string') {
return color;
}
if (color.match(/^gradient\((.*)\)$/i)) {
var parts = RegExp.$1.split(':');
var radius_start = this.radius - 54 - prop['chart.text.size'];
var radius_end = radius_start - 15;
// Create the gradient
var grad = co.createRadialGradient(this.centerx, this.centery, radius_start, this.centerx, this.centery, radius_end);
var diff = 1 / (parts.length - 1);
grad.addColorStop(0, RG.trim(parts[0]));
for (var j=1,len=parts.length; j<len; ++j) {
grad.addColorStop(j * diff, RG.trim(parts[j]));
}
}
return grad ? grad : color;
};
/**
* Using a function to add events makes it easier to facilitate method chaining
*
* @param string type The type of even to add
* @param function func
*/
this.on = function (type, func)
{
if (type.substr(0,2) !== 'on') {
type = 'on' + type;
}
this[type] = func;
return this;
};
/**
* CornerGauge Grow
*
* This effect gradually increases the represented value
*
* @param object obj The chart object
* @param Not used - pass null
* @param function An optional callback function
*/
this.grow = function ()
{
var opt = arguments[0];
var callback = arguments[1];
var numFrames = 30;
var frame = 0;
var obj = this;
// Single pointer
if (typeof this.value === 'number') {
var origValue = Number(this.currentValue);
if (this.currentValue === null) {
this.currentValue = this.min;
origValue = this.min;
}
var newValue = this.value;
var diff = newValue - origValue;
var step = (diff / numFrames);
var frame = 0;
var iterator = function ()
{
frame++;
obj.value = ((frame / numFrames) * diff) + origValue
if (obj.value > obj.max) obj.value = obj.max;
if (obj.value < obj.min) obj.value = obj.min;
RGraph.Clear(obj.canvas);
RGraph.RedrawCanvas(obj.canvas);
if (frame < 30) {
RGraph.Effects.updateCanvas(iterator);
} else if (typeof callback === 'function') {
callback(obj);
}
};
iterator();
// Multiple pointers
} else {
if (obj.currentValue == null) {
obj.currentValue = [];
for (var i=0,len=obj.value.length; i<len; ++i) {
obj.currentValue[i] = obj.min;
}
origValue = RG.array_clone(obj.currentValue);
}
var origValue = RG.array_clone(obj.currentValue);
var newValue = RG.array_clone(obj.value);
var diff = [];
var step = [];
for (var i=0,len=newValue.length; i<len; ++i) {
diff[i] = newValue[i] - Number(obj.currentValue[i]);
step[i] = (diff[i] / numFrames);
}
var max = this.max;
var min = this.min;
var iterator = function ()
{
frame++;
for (var i=0,len=obj.value.length; i<len; ++i) {
obj.value[i] = ((frame / numFrames) * diff[i]) + origValue[i];
if (obj.value[i] > max) obj.value[i] = max;
if (obj.value[i] < min) obj.value[i] = min;
RG.clear(obj.canvas);
RG.redrawCanvas(obj.canvas);
}
if (frame < 30) {
RG.Effects.updateCanvas(iterator);
} else if (typeof callback === 'function') {
callback(obj);
}
};
iterator();
}
return this;
}
/**
* Register the object
*/
RG.Register(this);
};
// version: 2014-03-28
|
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { resetState } from '../actions/boilerplate';
class Boilerplate extends Component {
constructor(props) {
super(props);
this.resetState = this.resetState.bind(this);
}
resetState() {
return this.props.dispatch(resetState());
}
render() {
return (
<div>
<button onClick={this.resetState}>Click me</button>
</div>
);
}
}
Boilerplate.propTypes = {
dispatch: PropTypes.func.isRequired
};
export default connect()(Boilerplate); // adds dispatch prop |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Ui5Title = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12, _descriptor13;
var _aureliaTemplating = require('aurelia-templating');
var _aureliaDependencyInjection = require('aurelia-dependency-injection');
var _aureliaFramework = require('aurelia-framework');
var _attributeManager = require('../common/attributeManager');
var _attributes = require('../common/attributes');
var _element = require('../element/element');
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var Ui5Title = exports.Ui5Title = (_dec = (0, _aureliaTemplating.customElement)('ui5-title'), _dec2 = (0, _aureliaDependencyInjection.inject)(Element), _dec3 = (0, _aureliaTemplating.bindable)(), _dec4 = (0, _aureliaTemplating.bindable)(), _dec5 = (0, _aureliaTemplating.bindable)(), _dec6 = (0, _aureliaTemplating.bindable)(), _dec7 = (0, _aureliaTemplating.bindable)(), _dec8 = (0, _aureliaTemplating.bindable)(), _dec9 = (0, _aureliaTemplating.bindable)(), _dec10 = (0, _aureliaTemplating.bindable)(), _dec11 = (0, _aureliaTemplating.bindable)(), _dec12 = (0, _aureliaFramework.computedFrom)('_title'), _dec(_class = _dec2(_class = (_class2 = function (_Ui5Element) {
_inherits(Ui5Title, _Ui5Element);
function Ui5Title(element) {
_classCallCheck(this, Ui5Title);
var _this = _possibleConstructorReturn(this, _Ui5Element.call(this, element));
_this._title = null;
_this._parent = null;
_this._relation = null;
_initDefineProp(_this, 'ui5Id', _descriptor, _this);
_initDefineProp(_this, 'ui5Class', _descriptor2, _this);
_initDefineProp(_this, 'ui5Tooltip', _descriptor3, _this);
_initDefineProp(_this, 'prevId', _descriptor4, _this);
_initDefineProp(_this, 'text', _descriptor5, _this);
_initDefineProp(_this, 'icon', _descriptor6, _this);
_initDefineProp(_this, 'level', _descriptor7, _this);
_initDefineProp(_this, 'emphasized', _descriptor8, _this);
_initDefineProp(_this, 'validationSuccess', _descriptor9, _this);
_initDefineProp(_this, 'validationError', _descriptor10, _this);
_initDefineProp(_this, 'parseError', _descriptor11, _this);
_initDefineProp(_this, 'formatError', _descriptor12, _this);
_initDefineProp(_this, 'modelContextChange', _descriptor13, _this);
_this.element = element;
_this.attributeManager = new _attributeManager.AttributeManager(_this.element);
return _this;
}
Ui5Title.prototype.fillProperties = function fillProperties(params) {
params.text = this.text;
params.icon = this.icon;
params.level = this.level;
params.emphasized = (0, _attributes.getBooleanFromAttributeValue)(this.emphasized);
_Ui5Element.prototype.fillProperties.call(this, params);
};
Ui5Title.prototype.defaultFunc = function defaultFunc() {};
Ui5Title.prototype.attached = function attached() {
var that = this;
var params = {};
this.fillProperties(params);
if (this.ui5Id) this._title = new sap.ui.core.Title(this.ui5Id, params);else this._title = new sap.ui.core.Title(params);
if (this.ui5Class) this._title.addStyleClass(this.ui5Class);
if (this.ui5Tooltip) this._title.setTooltip(this.ui5Tooltip);
if ($(this.element).closest("[ui5-container]").length > 0) {
this._parent = $(this.element).closest("[ui5-container]")[0].au.controller.viewModel;
if (!this._parent.UIElement || this._parent.UIElement.sId != this._title.sId) {
var prevSibling = null;
this._relation = this._parent.addChild(this._title, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
} else {
this._parent = $(this.element.parentElement).closest("[ui5-container]")[0].au.controller.viewModel;
var prevSibling = null;
this._relation = this._parent.addChild(this._title, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
}
} else {
if (this._title.placeAt) this._title.placeAt(this.element.parentElement);
this.attributeManager.addAttributes({ "ui5-container": '' });
this.attributeManager.addClasses("ui5-hide");
}
this.attributeManager.addAttributes({ "ui5-id": this._title.sId });
};
Ui5Title.prototype.detached = function detached() {
try {
if ($(this.element).closest("[ui5-container]").length > 0) {
if (this._parent && this._relation) {
if (this._title) this._parent.removeChildByRelation(this._title, this._relation);
}
} else {
this._title.destroy();
}
_Ui5Element.prototype.detached.call(this);
} catch (err) {}
};
Ui5Title.prototype.addChild = function addChild(child, elem, afterElement) {
var path = jQuery.makeArray($(elem).parentsUntil(this.element));
for (var _iterator = path, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
if (_isArray) {
if (_i >= _iterator.length) break;
elem = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
elem = _i.value;
}
try {
if (elem.localName == 'tooltip') {
this._title.setTooltip(child);return elem.localName;
}
if (elem.localName == 'customdata') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._title.insertCustomData(child, _index);else this._title.addCustomData(child, 0);return elem.localName;
}
if (elem.localName == 'layoutdata') {
this._title.setLayoutData(child);return elem.localName;
}
if (elem.localName == 'dependents') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._title.insertDependent(child, _index);else this._title.addDependent(child, 0);return elem.localName;
}
if (elem.localName == 'dragdropconfig') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._title.insertDragDropConfig(child, _index);else this._title.addDragDropConfig(child, 0);return elem.localName;
}
} catch (err) {}
}
};
Ui5Title.prototype.removeChildByRelation = function removeChildByRelation(child, relation) {
try {
if (relation == 'tooltip') {
this._title.destroyTooltip(child);
}
if (relation == 'customdata') {
this._title.removeCustomData(child);
}
if (relation == 'layoutdata') {
this._title.destroyLayoutData(child);
}
if (relation == 'dependents') {
this._title.removeDependent(child);
}
if (relation == 'dragdropconfig') {
this._title.removeDragDropConfig(child);
}
} catch (err) {}
};
Ui5Title.prototype.textChanged = function textChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.setText(newValue);
}
};
Ui5Title.prototype.iconChanged = function iconChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.setIcon(newValue);
}
};
Ui5Title.prototype.levelChanged = function levelChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.setLevel(newValue);
}
};
Ui5Title.prototype.emphasizedChanged = function emphasizedChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.setEmphasized((0, _attributes.getBooleanFromAttributeValue)(newValue));
}
};
Ui5Title.prototype.validationSuccessChanged = function validationSuccessChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.attachValidationSuccess(newValue);
}
};
Ui5Title.prototype.validationErrorChanged = function validationErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.attachValidationError(newValue);
}
};
Ui5Title.prototype.parseErrorChanged = function parseErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.attachParseError(newValue);
}
};
Ui5Title.prototype.formatErrorChanged = function formatErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.attachFormatError(newValue);
}
};
Ui5Title.prototype.modelContextChangeChanged = function modelContextChangeChanged(newValue) {
if (newValue != null && newValue != undefined && this._title !== null) {
this._title.attachModelContextChange(newValue);
}
};
_createClass(Ui5Title, [{
key: 'UIElement',
get: function get() {
return this._title;
}
}]);
return Ui5Title;
}(_element.Ui5Element), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'ui5Id', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'ui5Class', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'ui5Tooltip', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'prevId', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, 'text', [_dec3], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor6 = _applyDecoratedDescriptor(_class2.prototype, 'icon', [_dec4], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor7 = _applyDecoratedDescriptor(_class2.prototype, 'level', [_dec5], {
enumerable: true,
initializer: function initializer() {
return 'Auto';
}
}), _descriptor8 = _applyDecoratedDescriptor(_class2.prototype, 'emphasized', [_dec6], {
enumerable: true,
initializer: function initializer() {
return false;
}
}), _descriptor9 = _applyDecoratedDescriptor(_class2.prototype, 'validationSuccess', [_dec7], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor10 = _applyDecoratedDescriptor(_class2.prototype, 'validationError', [_dec8], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor11 = _applyDecoratedDescriptor(_class2.prototype, 'parseError', [_dec9], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor12 = _applyDecoratedDescriptor(_class2.prototype, 'formatError', [_dec10], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor13 = _applyDecoratedDescriptor(_class2.prototype, 'modelContextChange', [_dec11], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _applyDecoratedDescriptor(_class2.prototype, 'UIElement', [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, 'UIElement'), _class2.prototype)), _class2)) || _class) || _class); |
export default
{
"type": "group",
"id": "9a99988a-0123-4456-b89a-b1607f326fd8",
"children1": {
"a98ab9b9-cdef-4012-b456-71607f326fd9": {
"type": "rule",
"properties": {
"field": "user.login",
"operator": "equal",
"value": [
{
"func": "LOWER",
"args": {
"str": {
"valueSrc": "field",
"value": "user.firstName"
}
}
}
],
"valueSrc": [
"func"
],
"valueType": [
"text"
],
"valueError": [
null
]
}
},
"98a8a9ba-0123-4456-b89a-b16e721c8cd0": {
"type": "rule",
"properties": {
"field": "stock",
"operator": "equal",
"value": [
false
],
"valueSrc": [
"value"
],
"valueType": [
"boolean"
],
"valueError": [
null
]
}
},
"aabbab8a-cdef-4012-b456-716e85c65e9c": {
"type": "rule",
"properties": {
"field": "slider",
"operator": "equal",
"value": [
35
],
"valueSrc": [
"value"
],
"valueType": [
"number"
],
"valueError": [
null
]
}
},
"aaab8999-cdef-4012-b456-71702cd50090": {
"type": "rule_group",
"properties": {
"conjunction": "AND",
"field": "results"
},
"children1": {
"99b8a8a8-89ab-4cde-b012-31702cd5078b": {
"type": "rule",
"properties": {
"field": "results.product",
"operator": "select_equals",
"value": [
"abc"
],
"valueSrc": [
"value"
],
"valueType": [
"select"
],
"valueError": [
null
]
}
},
"88b9bb89-4567-489a-bcde-f1702cd53266": {
"type": "rule",
"properties": {
"field": "results.score",
"operator": "greater",
"value": [
8
],
"valueSrc": [
"value"
],
"valueType": [
"number"
],
"valueError": [
null
]
}
}
}
},
"a99a9b9b-cdef-4012-b456-7175a7d54553": {
"type": "rule_group",
"properties": {
"mode": "array",
"operator": "greater",
"valueType": [
"number"
],
"value": [
2
],
"valueSrc": [
"value"
],
"conjunction": "AND",
"valueError": [
null
],
"field": "cars"
},
"children1": {
"99a9a9a8-89ab-4cde-b012-3175a7d55374": {
"type": "rule",
"properties": {
"field": "cars.vendor",
"operator": "select_equals",
"value": [
"Toyota"
],
"valueSrc": [
"value"
],
"valueError": [
null
],
"valueType": [
"select"
]
}
},
"988bbbab-4567-489a-bcde-f175a7d58793": {
"type": "rule",
"properties": {
"field": "cars.year",
"operator": "greater_or_equal",
"value": [
2010
],
"valueSrc": [
"value"
],
"valueError": [
null
],
"valueType": [
"number"
]
}
}
}
}
},
"properties": {
"conjunction": "AND",
"not": false
}
}; |
var gulp = require('gulp');
var util = require('gulp-util');
var bowerFiles = require('main-bower-files');
var less = require('gulp-less');
var inject = require('gulp-inject');
var angularSort = require('gulp-angular-filesort');
var path =
{
bower : './src/main/webapp/bower_components',
js : './src/main/webapp/assets/js',
main : './src/main/webapp/index.html',
css : './src/main/webapp/assets/css',
media : './src/main/webapp/assets/media',
fonts : './src/main/webapp/assets/fonts'
}
gulp.task('default', ['assets:js','assets:css','assets:fonts','inject']);
gulp.task('assets:js', function(){
gulp.src(bowerFiles({includeDev : true, filter: '**/*.js'}))
.pipe(gulp.dest(path.js));
});
gulp.task('assets:css', function(){
gulp.src([path.bower + '/bootstrap/dist/css/bootstrap-theme.css', path.bower + '/bootstrap/dist/css/bootstrap.css'])
.pipe(gulp.dest(path.css));
});
gulp.task('assets:fonts', function(){
gulp.src([path.bower + '/bootstrap/dist/fonts/**/*'])
.pipe(gulp.dest(path.fonts));
});
gulp.task('inject', function () {
var target = gulp.src('./src/main/webapp/index.html');
var jsSrc = gulp.src(['./src/main/webapp/assets/**/*.js'], {read : true});
target.pipe(inject(jsSrc.pipe(angularSort()), {relative : true})).pipe(gulp.dest('./src/main/webapp'));
var cssSrc = gulp.src('./src/main/webapp/assets/css/bootstrap.css');
return target.pipe(inject(cssSrc, {relative : true})).pipe(gulp.dest('./src/main/webapp'));
});
/*gulp.task('assets:less', function(){
gulp.src('./bower_components/bootstrap/less/bootstrap.less')
.pipe(less())
.pipe(gulp.dest("./assets"));
});*/
|
var gulp = require('gulp'),
blanket = require('../../gulp-blanket'),
mocha = require('gulp-mocha');
gulp.task('blanketTest', function () {
gulp.src(['src.js'], { read: false })
.pipe(mocha({
reporter: 'spec'
}))
.pipe(blanket({
instrument:['src.js'],
captureFile: 'coverage.html',
reporter: 'html-cov'
}));
});
gulp.task('watch', function () {
gulp.watch(['src.js'], function(event) {
console.log('File '+event.path+' was '+event.type+', running tasks...');
gulp.run('blanketTest');
});
});
|
window.onload = function() {
configToolbar();
document.getElementById("roundDropDown").onclick = function() {
listenToSelect();
};
};
function listenToSelect() {
for (i = 1; i < document.getElementById("roundDropDown").length; i++) {
console.log(document.getElementById("roundDropDown").length);
if (document.getElementById("roundDropDown").value == i.toString()) {
createGameWindow(i);
}
}
} |
import Ember from 'ember';
export default Ember.Mixin.create({
// Solution based on: http://flightschool.acylt.com/devnotes/caret-position-woes/
getCaretPosition: function(oField) {
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// Get Position
var oSel = document.selection.createRange ();
oSel.moveStart ('character', -oField.value.length);
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart === '0') {
// Get position
iCaretPos = oField.selectionStart;
}
// Return results
return (iCaretPos);
},
/**
* Click action checks if toUpdate has been set.
* If not we check the caret position to determine which number should be updated when "+" or "-" are clicked.
*/
click: function() {
if (this.get('parentView.toUpdate') !== null) {
return;
}
var caretPos = this.getCaretPosition(this.$()[0]);
var keys = Object.keys(this.get('parentView.parts'));
var len = 0;
for (var i = 0; i < keys.length; i++) {
len += keys[i].length;
if (len >= caretPos) {
this.set('parentView._toUpdate', keys[i]);
break;
}
len++;
}
}
});
|
var createListItemTemplate = function (schema, id, deletable, readOnly) {
return '' +
(
!readOnly ?
'<td>' +
(deletable ? '<input type="checkbox" class="crud-list-selected"/>' : '') +
(readOnly ? '' : '<input type="button" class="crud-edit-button" value="Edit"/>') +
'</td>' : ''
) +
(id ? '<td name="id">{{id}}</td>' : '') +
reduce(schema, function (acc, item) {
return (acc || '') +
'<td name="' + item.name + '">{{' + item.name + '}}</td>';
});
};
|
/**
* sprite plugin
*
* @copy Copyright (c) 2012 Skype Limited
* @author Martin Kapp <skype:kappmartin>
* @author Thibault Martin-Lagardette
*/
(function($) {
/**
* @constructor Extend jQuery elements set here with 'sprite' function
*/
$.fn.extend({
sprite: function(options) {
// Apply to each element matched with selector
return this.each(function() {
var newOptions = $.extend({}, $.sprite.defaults, options);
$.sprite(this, newOptions);
});
},
unsprite: function() {
return this.each(function() {
$.unsprite(this);
});
},
deleteSprite: function() {
return this.each(function() {
$.deleteSprite(this);
});
},
sprite_debug: function() {
console.log(SpriteCore);
}
});
var SpriteCore = {
animations: [],
timer: null,
addAnimation: function(el, options) {
// Add animation timer if it doesn't already exist
SpriteCore.resumeAnimations();
var sprite_id = $(el).data('sprite_id');
// If the animation already exist, just run it :)
// Otherwise, let's create it.
if ((typeof sprite_id !== "undefined") && (typeof this.animations[sprite_id] !== "undefined")) {
this.animations[sprite_id].running = true;
}
else {
var obj = {
element: el,
current_frame: 0,
no_of_frames: options.no_of_frames,
frame_width: $(el).width(),
running: true
};
if ((typeof sprite_id === "undefined")) {
var index = this.animations.push(obj) - 1;
$(el).data('sprite_id', index);
}
else {
this.animations[sprite_id] = obj;
}
}
},
removeAnimation: function(el) {
var sprite_id = $(el).data('sprite_id');
if (typeof sprite_id !== "undefined" && typeof this.animations[sprite_id] !== "undefined") {
this.animations[sprite_id].running = false;
}
},
deleteSprite: function(el) {
var sprite_id = $(el).data('sprite_id');
if (typeof sprite_id !== "undefined" && typeof this.animations[sprite_id] !== "undefined") {
this.animations[sprite_id] = undefined;
}
},
pauseAnimations: function() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
},
resumeAnimations: function() {
if (this.timer === null) {
this.timer = setTimeout(function() {
SpriteCore.updateFrame();
}, 1000 / $.sprite.defaults.fps);
}
},
updateFrame: function() {
for (var x in this.animations) {
if (!this.animations.hasOwnProperty(x)) {
continue;
}
var d = this.animations[x];
if (typeof d !== "undefined" && d.running === true) {
if (++d.current_frame >= d.no_of_frames) {
d.current_frame = 0;
}
$(this.animations[x].element).css('backgroundPosition', '0 ' + (-(d.current_frame * d.frame_width)) + 'px');
this.animations[x].current_frame = d.current_frame;
}
}
this.timer = null;
SpriteCore.resumeAnimations();
},
x: 0
};
/**
* $.sprite class that is applied to all the elements found with the selectors.
*
* @class The actual sprite class
* @param element The input field to attach the sprite results
* @param options Options for the sprite class
*/
$.sprite = function(/**HTMLElement*/ element, /**Object*/ options) {
options.current_frame = 0;
options.frame_height = $(element).height();
options.frame_width = $(element).width();
var str = $(element).css("background-image");
var i = new Image();
var h, w;
var expectedWidth = parseInt($(element).css("width"), 10);
i.src = str.replace(/^url\(\"?([^"]+)\"?\)$/, "$1");
i.onload = function() {
divider = parseInt(i.width / expectedWidth, 10);
h = i.height / divider;
w = i.width / divider;
options.no_of_frames = (options.dir == 'vertical') ? (h / options.frame_height)|0 : (w / options.frame_width)|0;
SpriteCore.addAnimation(element, options);
};
};
$.unsprite = function(/**HTMLElement*/ element) {
SpriteCore.removeAnimation(element);
};
$.deleteSprite = function(/**HTMLElement*/ element) {
SpriteCore.deleteSprite(element);
};
$.pauseAnimations = function() {
SpriteCore.pauseAnimations();
};
$.resumeAnimations = function() {
SpriteCore.resumeAnimations();
};
$.sprite.defaults = {
fps: 24,
dir: 'vertical'
};
})(jQuery); |
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
function foobar() {
if(arguments.length === 2) {
let __ks_i = -1;
let a = arguments[++__ks_i];
if(a === void 0 || a === null) {
throw new TypeError("'a' is not nullable");
}
else if(!Type.isString(a)) {
throw new TypeError("'a' is not of type 'String'");
}
let b = arguments[++__ks_i];
if(b === void 0 || b === null) {
throw new TypeError("'b' is not nullable");
}
else if(!Type.isString(b)) {
throw new TypeError("'b' is not of type 'String'");
}
return a;
}
else if(arguments.length === 3 || arguments.length === 4) {
let __ks_i = -1;
let a = arguments[++__ks_i];
if(a === void 0 || a === null) {
throw new TypeError("'a' is not nullable");
}
else if(!Type.isString(a)) {
throw new TypeError("'a' is not of type 'String'");
}
let b = arguments[++__ks_i];
if(b === void 0 || b === null) {
throw new TypeError("'b' is not nullable");
}
else if(!Type.isNumber(b)) {
throw new TypeError("'b' is not of type 'Number'");
}
let c;
if(arguments.length > 3 && (c = arguments[++__ks_i]) !== void 0 && c !== null) {
if(!Type.isBoolean(c)) {
throw new TypeError("'c' is not of type 'Boolean'");
}
}
else {
c = false;
}
let d = arguments[++__ks_i];
if(d === void 0 || d === null) {
throw new TypeError("'d' is not nullable");
}
else if(!Type.isArray(d)) {
throw new TypeError("'d' is not of type 'Array'");
}
return b;
}
else {
throw new SyntaxError("Wrong number of arguments");
}
};
function quxbaz(a, b, c, d) {
if(arguments.length < 4) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 4)");
}
if(a === void 0 || a === null) {
throw new TypeError("'a' is not nullable");
}
else if(!Type.isString(a)) {
throw new TypeError("'a' is not of type 'String'");
}
if(b === void 0 || b === null) {
throw new TypeError("'b' is not nullable");
}
else if(!Type.isNumber(b)) {
throw new TypeError("'b' is not of type 'Number'");
}
if(c === void 0 || c === null) {
throw new TypeError("'c' is not nullable");
}
else if(!Type.isBoolean(c)) {
throw new TypeError("'c' is not of type 'Boolean'");
}
if(d === void 0 || d === null) {
throw new TypeError("'d' is not nullable");
}
else if(!Type.isArray(d)) {
throw new TypeError("'d' is not of type 'Array'");
}
foobar(a, b, c, d);
}
}; |
/*! flatpickr v2.3.4, @license MIT */
function Flatpickr(element, config) {
const self = this;
function init() {
if (element._flatpickr)
destroy(element._flatpickr);
element._flatpickr = self;
self.element = element;
self.instanceConfig = config || {};
setupFormats();
parseConfig();
setupLocale();
setupInputs();
setupDates();
setupHelperFunctions();
self.isOpen = self.config.inline;
self.changeMonth = changeMonth;
self.clear = clear;
self.close = close;
self.destroy = destroy;
self.formatDate = formatDate;
self.jumpToDate = jumpToDate;
self.open = open;
self.redraw = redraw;
self.set = set;
self.setDate = setDate;
self.toggle = toggle;
self.isMobile = (
!self.config.disableMobile &&
!self.config.inline &&
self.config.mode === "single" &&
!self.config.disable.length &&
!self.config.enable.length &&
!self.config.weekNumbers &&
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
);
if (!self.isMobile)
build();
bind();
if (!self.isMobile) {
Object.defineProperty(self, "dateIsPicked", {
set: function(bool) {
if (bool)
return self.calendarContainer.classList.add("dateIsPicked");
self.calendarContainer.classList.remove("dateIsPicked");
}
});
}
self.dateIsPicked = self.selectedDates.length > 0 || self.config.noCalendar;
if (self.selectedDates.length) {
if (self.config.enableTime)
setHoursFromDate();
updateValue();
}
if (self.config.weekNumbers) {
self.calendarContainer.style.width = self.days.clientWidth
+ self.weekWrapper.clientWidth + "px";
}
triggerEvent("Ready");
}
function updateTime(e) {
if (self.config.noCalendar && !self.selectedDates.length)
// picking time only
self.selectedDates = [self.now];
timeWrapper(e);
if (!self.selectedDates.length)
return;
if (!self.minDateHasTime || e.type !== "input" || e.target.value.length >= 2) {
setHoursFromInputs();
updateValue();
}
else {
setTimeout(function(){
setHoursFromInputs();
updateValue();
}, 1000);
}
}
function setHoursFromInputs(){
if (!self.config.enableTime)
return;
let hours = (parseInt(self.hourElement.value, 10) || 0),
minutes = (parseInt(self.minuteElement.value, 10) || 0),
seconds = self.config.enableSeconds
? (parseInt(self.secondElement.value, 10) || 0)
: 0;
if (self.amPM)
hours = (hours % 12) + (12 * (self.amPM.textContent === "PM"));
if (
self.minDateHasTime
&& compareDates(self.latestSelectedDateObj, self.config.minDate) === 0
) {
hours = Math.max(hours, self.config.minDate.getHours());
if (hours === self.config.minDate.getHours())
minutes = Math.max(minutes, self.config.minDate.getMinutes());
}
else if (
self.maxDateHasTime
&& compareDates(self.latestSelectedDateObj, self.config.maxDate) === 0
) {
hours = Math.min(hours, self.config.maxDate.getHours());
if (hours === self.config.maxDate.getHours())
minutes = Math.min(minutes, self.config.maxDate.getMinutes());
}
setHours(hours, minutes, seconds);
}
function setHoursFromDate(dateObj){
const date = dateObj || self.latestSelectedDateObj;
if (date)
setHours(date.getHours(), date.getMinutes(), date.getSeconds());
}
function setHours(hours, minutes, seconds) {
if (self.selectedDates.length) {
self.latestSelectedDateObj.setHours(
hours % 24, minutes, seconds || 0, 0
);
}
if (!self.config.enableTime || self.isMobile)
return;
self.hourElement.value = self.pad(
!self.config.time_24hr ? (12 + hours) % 12 + 12 * (hours % 12 === 0) : hours
);
self.minuteElement.value = self.pad(minutes);
if (!self.config.time_24hr && self.selectedDates.length)
self.amPM.textContent = self.latestSelectedDateObj.getHours() >= 12 ? "PM" : "AM";
if (self.config.enableSeconds)
self.secondElement.value = self.pad(seconds);
}
function onYearInput(event) {
if (event.target.value.length === 4) {
self.currentYearElement.blur();
handleYearChange(event.target.value);
event.target.value = self.currentYear;
}
}
function bind() {
if (self.config.wrap) {
["open", "close", "toggle", "clear"].forEach(el => {
try {
self.element.querySelector(`[data-${el}]`)
.addEventListener("click", self[el]);
}
catch (e) {
//
}
});
}
if (window.document.createEvent !== undefined) {
self.changeEvent = window.document.createEvent("HTMLEvents");
self.changeEvent.initEvent("change", false, true);
}
if (self.isMobile)
return setupMobile();
self.debouncedResize = debounce(onResize, 50);
self.triggerChange = () => {
triggerEvent("Change");
};
self.debouncedChange = debounce(self.triggerChange, 300);
if (self.config.mode === "range" && self.days)
self.days.addEventListener("mouseover", onMouseOver);
window.document.addEventListener("keydown", onKeyDown);
if (!self.config.inline && !self.config.static)
window.addEventListener("resize", self.debouncedResize);
if (window.ontouchstart)
window.document.addEventListener("touchstart", documentClick);
window.document.addEventListener("click", documentClick);
window.document.addEventListener("blur", documentClick);
if (self.config.clickOpens)
(self.altInput || self.input).addEventListener("focus", open);
if (!self.config.noCalendar) {
self.prevMonthNav.addEventListener("click", () => changeMonth(-1));
self.nextMonthNav.addEventListener("click", () => changeMonth(1));
self.currentYearElement.addEventListener("wheel", e => debounce(yearScroll(e), 50));
self.currentYearElement.addEventListener("focus", () => {
self.currentYearElement.select();
});
self.currentYearElement.addEventListener("input", onYearInput);
self.currentYearElement.addEventListener("increment", onYearInput);
self.days.addEventListener("click", selectDate);
}
if (self.config.enableTime) {
self.timeContainer.addEventListener("transitionend", positionCalendar);
self.timeContainer.addEventListener("wheel", e => debounce(updateTime(e), 5));
self.timeContainer.addEventListener("input", updateTime);
self.timeContainer.addEventListener("increment", updateTime);
self.timeContainer.addEventListener("increment", self.debouncedChange);
self.timeContainer.addEventListener("wheel", self.debouncedChange);
self.timeContainer.addEventListener("input", self.triggerChange);
self.hourElement.addEventListener("focus", () => {
self.hourElement.select();
});
self.minuteElement.addEventListener("focus", () => {
self.minuteElement.select();
});
if (self.secondElement) {
self.secondElement.addEventListener("focus", () => {
self.secondElement.select();
});
}
if (self.amPM) {
self.amPM.addEventListener("click", (e) => {
updateTime(e);
self.triggerChange(e);
});
}
}
}
function jumpToDate(jumpDate) {
jumpDate = jumpDate
? self.parseDate(jumpDate)
: self.latestSelectedDateObj || (self.config.minDate > self.now
? self.config.minDate
: self.config.maxDate && self.config.maxDate < self.now
? self.config.maxDate
: self.now
);
try {
self.currentYear = jumpDate.getFullYear();
self.currentMonth = jumpDate.getMonth();
}
catch (e) {
console.error(e.stack);
console.warn("Invalid date supplied: " + jumpDate);
}
self.redraw();
}
function incrementNumInput(e, delta) {
const input = e.target.parentNode.childNodes[0];
input.value = parseInt(input.value, 10) + delta * (input.step || 1);
try {
input.dispatchEvent(new Event("increment", { "bubbles": true }));
}
catch (e) {
const ev = window.document.createEvent("CustomEvent");
ev.initCustomEvent("increment", true, true, {});
input.dispatchEvent(ev);
}
}
function createNumberInput(inputClassName) {
const wrapper = createElement("div", "numInputWrapper"),
numInput = createElement("input", "numInput " + inputClassName),
arrowUp = createElement("span", "arrowUp"),
arrowDown = createElement("span", "arrowDown");
numInput.type = "text";
wrapper.appendChild(numInput);
wrapper.appendChild(arrowUp);
wrapper.appendChild(arrowDown);
arrowUp.addEventListener("click", e => incrementNumInput(e, 1));
arrowDown.addEventListener("click", e => incrementNumInput(e, -1));
return wrapper;
}
function build() {
const fragment = window.document.createDocumentFragment();
self.calendarContainer = createElement("div", "flatpickr-calendar");
self.numInputType = navigator.userAgent.indexOf("MSIE 9.0") > 0 ? "text" : "number";
if (!self.config.noCalendar) {
fragment.appendChild(buildMonthNav());
self.innerContainer = createElement("div", "flatpickr-innerContainer")
if (self.config.weekNumbers)
self.innerContainer.appendChild(buildWeeks());
self.rContainer = createElement("div", "flatpickr-rContainer");
self.rContainer.appendChild(buildWeekdays());
self.rContainer.appendChild(buildDays());
self.innerContainer.appendChild(self.rContainer);
fragment.appendChild(self.innerContainer);
}
if (self.config.enableTime)
fragment.appendChild(buildTime());
if (self.config.mode === "range")
self.calendarContainer.classList.add("rangeMode");
self.calendarContainer.appendChild(fragment);
const customAppend = self.config.appendTo && self.config.appendTo.nodeType;
if (self.config.inline || self.config.static) {
self.calendarContainer.classList.add(self.config.inline ? "inline" : "static");
positionCalendar();
if (self.config.inline && !customAppend) {
return self.element.parentNode.insertBefore(
self.calendarContainer,
(self.altInput || self.input).nextSibling
);
}
if (self.config.static){
const wrapper = createElement("div", "flatpickr-wrapper");
self.element.parentNode.insertBefore(wrapper, self.element);
wrapper.appendChild(self.element);
wrapper.appendChild(self.calendarContainer);
return;
}
}
(customAppend ? self.config.appendTo : window.document.body)
.appendChild(self.calendarContainer);
}
function createDay(className, date, dayNumber) {
const dateIsEnabled = isEnabled(date, true),
dayElement = createElement(
"span",
"flatpickr-day " + className,
date.getDate()
);
dayElement.dateObj = date;
if (compareDates(date, self.now) === 0)
dayElement.classList.add("today");
if (dateIsEnabled) {
dayElement.tabIndex = 0;
if (isDateSelected(date)){
dayElement.classList.add("selected");
if (self.config.mode === "range") {
dayElement.classList.add(
compareDates(date, self.selectedDates[0]) === 0
? "startRange"
: "endRange"
);
}
else
self.selectedDateElem = dayElement;
}
}
else {
dayElement.classList.add("disabled");
if (
self.selectedDates[0]
&& date > self.minRangeDate
&& date < self.selectedDates[0]
)
self.minRangeDate = date;
else if (
self.selectedDates[0]
&& date < self.maxRangeDate
&& date > self.selectedDates[0]
)
self.maxRangeDate = date;
}
if (self.config.mode === "range") {
if (isDateInRange(date) && !isDateSelected(date))
dayElement.classList.add("inRange");
if (
self.selectedDates.length === 1 &&
(date < self.minRangeDate || date > self.maxRangeDate)
)
dayElement.classList.add("notAllowed");
}
if (self.config.weekNumbers && className !== "prevMonthDay" && dayNumber % 7 === 1) {
self.weekNumbers.insertAdjacentHTML(
"beforeend",
"<span class='disabled flatpickr-day'>" + self.config.getWeek(date) + "</span>"
);
}
triggerEvent("DayCreate", dayElement);
return dayElement;
}
function buildDays() {
if (!self.days) {
self.days = createElement("div", "flatpickr-days");
self.days.tabIndex = -1;
}
self.firstOfMonth = (
new Date(self.currentYear, self.currentMonth, 1).getDay() -
self.l10n.firstDayOfWeek + 7
) % 7;
self.prevMonthDays = self.utils.getDaysinMonth((self.currentMonth - 1 + 12) % 12);
const daysInMonth = self.utils.getDaysinMonth(),
days = window.document.createDocumentFragment();
let dayNumber = self.prevMonthDays + 1 - self.firstOfMonth;
if (self.config.weekNumbers && self.weekNumbers.firstChild)
self.weekNumbers.textContent = "";
if (self.config.mode === "range") {
// const dateLimits = self.config.enable.length || self.config.disable.length || self.config.mixDate || self.config.maxDate;
self.minRangeDate = new Date(self.currentYear, self.currentMonth - 1, dayNumber);
self.maxRangeDate = new Date(
self.currentYear,
self.currentMonth + 1,
(42 - self.firstOfMonth) % daysInMonth
);
}
if (self.days.firstChild)
self.days.textContent = "";
// prepend days from the ending of previous month
for (let i = 0; dayNumber <= self.prevMonthDays; i++, dayNumber++) {
days.appendChild(
createDay("prevMonthDay", new Date(self.currentYear, self.currentMonth - 1, dayNumber), dayNumber)
);
}
// Start at 1 since there is no 0th day
for (dayNumber = 1; dayNumber <= daysInMonth; dayNumber++) {
days.appendChild(
createDay("", new Date(self.currentYear, self.currentMonth, dayNumber), dayNumber)
);
}
// append days from the next month
for (let dayNum = daysInMonth + 1; dayNum <= 42 - self.firstOfMonth; dayNum++) {
days.appendChild(
createDay(
"nextMonthDay",
new Date(self.currentYear, self.currentMonth + 1, dayNum % daysInMonth),
dayNum
)
);
}
self.days.appendChild(days);
return self.days;
}
function buildMonthNav() {
const monthNavFragment = window.document.createDocumentFragment();
self.monthNav = createElement("div", "flatpickr-month");
self.prevMonthNav = createElement("span", "flatpickr-prev-month");
self.prevMonthNav.innerHTML = self.config.prevArrow;
self.currentMonthElement = createElement("span", "cur-month");
const yearInput = createNumberInput("cur-year");
self.currentYearElement = yearInput.childNodes[0];
self.currentYearElement.title = self.l10n.scrollTitle;
if (self.config.minDate)
self.currentYearElement.min = self.config.minDate.getFullYear();
if (self.config.maxDate) {
self.currentYearElement.max = self.config.maxDate.getFullYear();
self.currentYearElement.disabled = self.config.minDate &&
self.config.minDate.getFullYear() === self.config.maxDate.getFullYear();
}
self.nextMonthNav = createElement("span", "flatpickr-next-month");
self.nextMonthNav.innerHTML = self.config.nextArrow;
self.navigationCurrentMonth = createElement("span", "flatpickr-current-month");
self.navigationCurrentMonth.appendChild(self.currentMonthElement);
self.navigationCurrentMonth.appendChild(yearInput);
monthNavFragment.appendChild(self.prevMonthNav);
monthNavFragment.appendChild(self.navigationCurrentMonth);
monthNavFragment.appendChild(self.nextMonthNav);
self.monthNav.appendChild(monthNavFragment);
updateNavigationCurrentMonth();
return self.monthNav;
}
function buildTime() {
self.calendarContainer.classList.add("hasTime");
if (self.config.noCalendar)
self.calendarContainer.classList.add("noCalendar");
self.timeContainer = createElement("div", "flatpickr-time");
self.timeContainer.tabIndex = -1;
const separator = createElement("span", "flatpickr-time-separator", ":");
const hourInput = createNumberInput("flatpickr-hour");
self.hourElement = hourInput.childNodes[0];
const minuteInput = createNumberInput("flatpickr-minute");
self.minuteElement = minuteInput.childNodes[0];
self.hourElement.tabIndex = self.minuteElement.tabIndex = 0;
self.hourElement.pattern = self.minuteElement.pattern = "\\d*";
self.hourElement.value = self.pad(self.latestSelectedDateObj
? self.latestSelectedDateObj.getHours()
: self.config.defaultHour
);
self.minuteElement.value = self.pad(self.latestSelectedDateObj
? self.latestSelectedDateObj.getMinutes()
: self.config.defaultMinute
);
self.hourElement.step = self.config.hourIncrement;
self.minuteElement.step = self.config.minuteIncrement;
self.hourElement.min = self.config.time_24hr ? 0 : 1;
self.hourElement.max = self.config.time_24hr ? 23 : 12;
self.minuteElement.min = 0;
self.minuteElement.max = 59;
self.hourElement.title = self.minuteElement.title = self.l10n.scrollTitle;
self.timeContainer.appendChild(hourInput);
self.timeContainer.appendChild(separator);
self.timeContainer.appendChild(minuteInput);
if (self.config.time_24hr)
self.timeContainer.classList.add("time24hr");
if (self.config.enableSeconds) {
self.timeContainer.classList.add("hasSeconds");
const secondInput = createNumberInput("flatpickr-second");
self.secondElement = secondInput.childNodes[0];
self.secondElement.pattern = self.hourElement.pattern;
self.secondElement.value =
self.latestSelectedDateObj ? self.pad(self.latestSelectedDateObj.getSeconds()) : "00";
self.secondElement.step = self.minuteElement.step;
self.secondElement.min = self.minuteElement.min;
self.secondElement.max = self.minuteElement.max;
self.timeContainer.appendChild(
createElement("span", "flatpickr-time-separator", ":")
);
self.timeContainer.appendChild(secondInput);
}
if (!self.config.time_24hr) { // add self.amPM if appropriate
self.amPM = createElement(
"span",
"flatpickr-am-pm",
["AM", "PM"][(self.hourElement.value > 11) | 0]
);
self.amPM.title = self.l10n.toggleTitle;
self.amPM.tabIndex = 0;
self.timeContainer.appendChild(self.amPM);
}
return self.timeContainer;
}
function buildWeekdays() {
if (!self.weekdayContainer)
self.weekdayContainer = createElement("div", "flatpickr-weekdays");
const firstDayOfWeek = self.l10n.firstDayOfWeek;
let weekdays = self.l10n.weekdays.shorthand.slice();
if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays.length) {
weekdays = [].concat(
weekdays.splice(firstDayOfWeek, weekdays.length),
weekdays.splice(0, firstDayOfWeek)
);
}
self.weekdayContainer.innerHTML = `
<span class=flatpickr-weekday>
${weekdays.join("</span><span class=flatpickr-weekday>")}
</span>
`;
return self.weekdayContainer;
}
/* istanbul ignore next */
function buildWeeks() {
self.calendarContainer.classList.add("hasWeeks");
self.weekWrapper = createElement("div", "flatpickr-weekwrapper");
self.weekWrapper.appendChild(
createElement("span", "flatpickr-weekday", self.l10n.weekAbbreviation)
);
self.weekNumbers = createElement("div", "flatpickr-weeks");
self.weekWrapper.appendChild(self.weekNumbers);
return self.weekWrapper;
}
function changeMonth(value, is_offset) {
self.currentMonth = (typeof is_offset === "undefined" || is_offset)
? self.currentMonth + value
: value;
handleYearChange();
updateNavigationCurrentMonth();
buildDays();
if (!(self.config.noCalendar))
self.days.focus();
triggerEvent("MonthChange");
}
function clear(triggerChangeEvent) {
self.input.value = "";
if (self.altInput)
self.altInput.value = "";
if (self.mobileInput)
self.mobileInput.value = "";
self.selectedDates = [];
self.latestSelectedDateObj = null;
self.dateIsPicked = false;
self.redraw();
if (triggerChangeEvent !== false)
// triggerChangeEvent is true (default) or an Event
triggerEvent("Change");
}
function close() {
self.isOpen = false;
if (!self.isMobile) {
self.calendarContainer.classList.remove("open");
(self.altInput || self.input).classList.remove("active");
}
triggerEvent("Close");
}
function destroy(instance) {
instance = instance || self;
instance.clear(false);
window.document.removeEventListener("keydown", onKeyDown);
window.removeEventListener("resize", instance.debouncedResize);
window.document.removeEventListener("click", documentClick);
window.document.removeEventListener("touchstart", documentClick);
window.document.removeEventListener("blur", documentClick);
if (instance.timeContainer)
instance.timeContainer.removeEventListener("transitionend", positionCalendar);
if (instance.mobileInput && instance.mobileInput.parentNode)
instance.mobileInput.parentNode.removeChild(instance.mobileInput);
else if (instance.calendarContainer && instance.calendarContainer.parentNode)
instance.calendarContainer.parentNode.removeChild(instance.calendarContainer);
if (instance.altInput) {
instance.input.type = "text";
if (instance.altInput.parentNode)
instance.altInput.parentNode.removeChild(instance.altInput);
}
instance.input.type = instance.input._type;
instance.input.classList.remove("flatpickr-input");
instance.input.removeEventListener("focus", open);
instance.input.removeAttribute("readonly");
delete instance.input._flatpickr;
}
function isCalendarElem(elem) {
let e = elem;
while (e) {
if (/flatpickr-day|flatpickr-calendar/.test(e.className))
return true;
e = e.parentNode;
}
return false;
}
function documentClick(e) {
const isInput = self.element.contains(e.target)
|| e.target === self.input
|| e.target === self.altInput
|| (
// web components
e.path && e.path.indexOf &&
(~e.path.indexOf(self.input) || ~e.path.indexOf(self.altInput))
);
if (self.isOpen && !self.config.inline && !isCalendarElem(e.target) && !isInput) {
e.preventDefault();
self.close();
if (self.config.mode === "range" && self.selectedDates.length === 1) {
self.clear();
self.redraw();
}
}
}
function formatDate(frmt, dateObj) {
if (self.config.formatDate)
return self.config.formatDate(frmt, dateObj);
const chars = frmt.split("");
return chars.map((c, i) => self.formats[c] && chars[i - 1] !== "\\"
? self.formats[c](dateObj)
: c !== "\\" ? c : ""
).join("");
}
function handleYearChange(newYear) {
if (self.currentMonth < 0 || self.currentMonth > 11) {
self.currentYear += self.currentMonth % 11;
self.currentMonth = (self.currentMonth + 12) % 12;
triggerEvent("YearChange");
}
else if (
newYear
&& (!self.currentYearElement.min || newYear >= self.currentYearElement.min)
&& (!self.currentYearElement.max || newYear <= self.currentYearElement.max)
) {
self.currentYear = parseInt(newYear, 10) || self.currentYear;
if (
self.config.maxDate
&& self.currentYear === self.config.maxDate.getFullYear()
) {
self.currentMonth = Math.min(
self.config.maxDate.getMonth(),
self.currentMonth
);
}
else if (
self.config.minDate
&& self.currentYear === self.config.minDate.getFullYear()
) {
self.currentMonth = Math.max(
self.config.minDate.getMonth(),
self.currentMonth
);
}
self.redraw();
triggerEvent("YearChange");
}
}
function isEnabled(date, timeless) {
const ltmin = compareDates(
date,
self.config.minDate,
typeof timeless !== "undefined" ? timeless : !self.minDateHasTime
) < 0;
const gtmax = compareDates(
date,
self.config.maxDate,
typeof timeless !== "undefined" ? timeless : !self.maxDateHasTime
) > 0;
if (ltmin || gtmax)
return false;
if (!self.config.enable.length && !self.config.disable.length)
return true;
const dateToCheck = self.parseDate(date, true); // timeless
const bool = self.config.enable.length > 0,
array = bool ? self.config.enable : self.config.disable;
for (let i = 0, d; i < array.length; i++) {
d = array[i];
if (d instanceof Function && d(dateToCheck)) // disabled by function
return bool;
else if (d instanceof Date && d.getTime() === dateToCheck.getTime())
// disabled by date
return bool;
else if (typeof d === "string" && self.parseDate(d, true).getTime() === dateToCheck.getTime())
// disabled by date string
return bool;
else if ( // disabled by range
typeof d === "object" && d.from && d.to &&
dateToCheck >= d.from && dateToCheck <= d.to
)
return bool;
}
return !bool;
}
function onKeyDown(e) {
if (self.isOpen) {
switch (e.which) {
case 13:
if (self.timeContainer && self.timeContainer.contains(e.target))
updateValue();
else
selectDate(e);
break;
case 27: // escape
self.clear();
self.redraw();
self.close();
break;
case 37:
if (e.target !== self.input & e.target !== self.altInput)
changeMonth(-1);
break;
case 38:
e.preventDefault();
if (self.timeContainer && self.timeContainer.contains(e.target))
updateTime(e);
else {
self.currentYear++;
self.redraw();
}
break;
case 39:
if (e.target !== self.input & e.target !== self.altInput)
changeMonth(1);
break;
case 40:
e.preventDefault();
if (self.timeContainer && self.timeContainer.contains(e.target))
updateTime(e);
else {
self.currentYear--;
self.redraw();
}
break;
default: break;
}
}
}
function onMouseOver(e) {
if (self.selectedDates.length !== 1 || !e.target.classList.contains("flatpickr-day"))
return;
let hoverDate = e.target.dateObj,
initialDate = self.parseDate(self.selectedDates[0], true),
rangeStartDate = Math.min(hoverDate.getTime(), self.selectedDates[0].getTime()),
rangeEndDate = Math.max(hoverDate.getTime(), self.selectedDates[0].getTime()),
containsDisabled = false;
for (let t = rangeStartDate; t < rangeEndDate; t += self.utils.duration.DAY) {
if (!isEnabled(new Date(t))) {
containsDisabled = true;
break;
}
}
for (
let timestamp = self.days.childNodes[0].dateObj.getTime(), i = 0;
i < 42;
i++, timestamp += self.utils.duration.DAY
) {
const outOfRange = timestamp < self.minRangeDate.getTime()
|| timestamp > self.maxRangeDate.getTime();
if (outOfRange) {
self.days.childNodes[i].classList.add("notAllowed");
["inRange", "startRange", "endRange"].forEach(c => {
self.days.childNodes[i].classList.remove(c)
});
continue;
}
else if (containsDisabled && !outOfRange)
continue;
["startRange", "inRange", "endRange", "notAllowed"].forEach(c => {
self.days.childNodes[i].classList.remove(c)
});
const minRangeDate = Math.max(self.minRangeDate.getTime(), rangeStartDate),
maxRangeDate = Math.min(self.maxRangeDate.getTime(), rangeEndDate);
e.target.classList.add(hoverDate < self.selectedDates[0] ? "startRange" : "endRange");
if (initialDate > hoverDate && timestamp === initialDate.getTime())
self.days.childNodes[i].classList.add("endRange");
else if (initialDate < hoverDate && timestamp === initialDate.getTime())
self.days.childNodes[i].classList.add("startRange");
else if (timestamp > minRangeDate && timestamp < maxRangeDate)
self.days.childNodes[i].classList.add("inRange");
}
}
function onResize() {
if (self.isOpen && !self.config.static && !self.config.inline)
positionCalendar();
}
function open(e) {
if (self.isMobile) {
if (e) {
e.preventDefault();
e.target.blur();
}
setTimeout(() => {
self.mobileInput.click();
}, 0);
triggerEvent("Open");
return;
}
else if (self.isOpen || (self.altInput || self.input).disabled || self.config.inline)
return;
self.calendarContainer.classList.add("open");
if (!self.config.static && !self.config.inline)
positionCalendar();
self.isOpen = true;
if (!self.config.allowInput) {
(self.altInput || self.input).blur();
(self.config.noCalendar
? self.timeContainer
: self.selectedDateElem
? self.selectedDateElem
: self.days).focus();
}
(self.altInput || self.input).classList.add("active");
triggerEvent("Open");
}
function minMaxDateSetter(type) {
return function(date) {
const dateObj = self.config[`_${type}Date`] = self.parseDate(date);
const inverseDateObj = self.config[`_${type === "min" ? "max" : "min"}Date`];
if (self.selectedDates) {
self.selectedDates = self.selectedDates.filter(isEnabled);
updateValue();
}
if(self.days)
redraw();
if (!self.currentYearElement)
return;
if (date && dateObj instanceof Date) {
self[`${type}DateHasTime`] = dateObj.getHours()
|| dateObj.getMinutes()
|| dateObj.getSeconds();
self.currentYearElement[type] = dateObj.getFullYear();
}
else
self.currentYearElement.removeAttribute(type);
self.currentYearElement.disabled = inverseDateObj && dateObj &&
inverseDateObj.getFullYear() === dateObj.getFullYear();
}
}
function parseConfig() {
var boolOpts = [
"utc", "wrap", "weekNumbers", "allowInput", "clickOpens", "time_24hr", "enableTime", "noCalendar", "altInput", "shorthandCurrentMonth", "inline", "static", "enableSeconds", "disableMobile"
];
self.config = Object.create(Flatpickr.defaultConfig);
Object.defineProperty(self.config, "minDate", {
get: function() {
return this._minDate;
},
set: minMaxDateSetter("min")
});
Object.defineProperty(self.config, "maxDate", {
get: function() {
return this._maxDate;
},
set: minMaxDateSetter("max")
});
let userConfig = Object.assign(
{},
self.instanceConfig,
JSON.parse(JSON.stringify(self.element.dataset || {}))
);
Object.assign(self.config, userConfig);
for (var i = 0; i < boolOpts.length; i++)
self.config[boolOpts[i]] = (self.config[boolOpts[i]] === true) || self.config[boolOpts[i]] === "true";
if (!userConfig.dateFormat && userConfig.enableTime) {
self.config.dateFormat = self.config.noCalendar
? "H:i" + (self.config.enableSeconds ? ":S" : "")
: Flatpickr.defaultConfig.dateFormat + " H:i" + (self.config.enableSeconds ? ":S" : "");
}
if (userConfig.altInput && userConfig.enableTime && !userConfig.altFormat) {
self.config.altFormat = self.config.noCalendar
? "h:i" + (self.config.enableSeconds ? ":S K" : " K")
: Flatpickr.defaultConfig.altFormat + ` h:i${self.config.enableSeconds ? ":S" : ""} K`;
}
}
function setupLocale() {
if (typeof self.config.locale !== "object" &&
typeof Flatpickr.l10ns[self.config.locale] === "undefined"
)
console.warn(`flatpickr: invalid locale ${self.config.locale}`);
self.l10n = Object.assign(
Object.create(Flatpickr.l10ns.default),
typeof self.config.locale === "object"
? self.config.locale
: self.config.locale !== "default"
? Flatpickr.l10ns[self.config.locale] || {}
: {}
);
}
function positionCalendar(e) {
if (e && e.target !== self.timeContainer)
return;
const calendarHeight = self.calendarContainer.offsetHeight,
calendarWidth = self.calendarContainer.offsetWidth,
input = (self.altInput || self.input),
inputBounds = input.getBoundingClientRect(),
distanceFromBottom = window.innerHeight - inputBounds.bottom + input.offsetHeight;
let top;
if (distanceFromBottom < calendarHeight + 60) {
top = (window.pageYOffset - calendarHeight + inputBounds.top) - 2;
self.calendarContainer.classList.remove("arrowTop");
self.calendarContainer.classList.add("arrowBottom");
}
else {
top = (window.pageYOffset + input.offsetHeight + inputBounds.top) + 2;
self.calendarContainer.classList.remove("arrowBottom");
self.calendarContainer.classList.add("arrowTop");
}
if (!self.config.static && !self.config.inline) {
self.calendarContainer.style.top = `${top}px`;
const left = window.pageXOffset + inputBounds.left;
const right = window.document.body.offsetWidth - inputBounds.right;
if (left + calendarWidth <= window.document.body.offsetWidth) {
self.calendarContainer.style.left = `${left}px`;
self.calendarContainer.style.right = "auto";
self.calendarContainer.classList.remove("rightMost");
}
else {
self.calendarContainer.style.left = "auto";
self.calendarContainer.style.right = `${right}px`;
self.calendarContainer.classList.add("rightMost");
}
}
}
function redraw() {
if (self.config.noCalendar || self.isMobile)
return;
buildWeekdays();
updateNavigationCurrentMonth();
buildDays();
}
function selectDate(e) {
e.preventDefault();
if (
self.config.allowInput &&
e.which === 13 &&
(e.target === (self.altInput || self.input))
)
return self.setDate((self.altInput || self.input).value), e.target.blur();
if (
!e.target.classList.contains("flatpickr-day") ||
e.target.classList.contains("disabled") ||
e.target.classList.contains("notAllowed")
)
return;
const selectedDate
= self.latestSelectedDateObj
= new Date(e.target.dateObj.getTime());
self.selectedDateElem = e.target;
if (self.config.mode === "single")
self.selectedDates = [selectedDate];
else if (self.config.mode === "multiple") {
const selectedIndex = isDateSelected(selectedDate);
if (selectedIndex)
self.selectedDates.splice(selectedIndex, 1);
else
self.selectedDates.push(selectedDate);
}
else if (self.config.mode === "range") {
if (self.selectedDates.length === 2)
self.clear();
self.selectedDates.push(selectedDate);
self.selectedDates.sort((a,b) => a.getTime() - b.getTime());
}
setHoursFromInputs();
if (selectedDate.getMonth() !== self.currentMonth && self.config.mode !== "range") {
self.currentYear = selectedDate.getFullYear();
self.currentMonth = selectedDate.getMonth();
updateNavigationCurrentMonth();
}
buildDays();
if (self.minDateHasTime && self.config.enableTime
&& compareDates(selectedDate, self.config.minDate) === 0
)
setHoursFromDate(self.config.minDate);
updateValue();
setTimeout(() => self.dateIsPicked = true, 50);
if (self.config.mode === "range" && self.selectedDates.length === 1)
onMouseOver(e);
if (self.config.mode === "single" && !self.config.enableTime)
self.close();
triggerEvent("Change");
}
function set(option, value) {
self.config[option] = value;
self.redraw();
jumpToDate();
}
function setSelectedDate(inputDate) {
if (Array.isArray(inputDate))
self.selectedDates = inputDate.map(self.parseDate);
else if (inputDate) {
switch (self.config.mode) {
case "single":
self.selectedDates = [self.parseDate(inputDate)];
break;
case "multiple":
self.selectedDates = inputDate.split("; ").map(self.parseDate);
break;
case "range":
self.selectedDates = inputDate
.split(self.l10n.rangeSeparator)
.map(self.parseDate);
break;
default: break;
}
}
self.selectedDates = self.selectedDates.filter(
d => d instanceof Date && d.getTime() && isEnabled(d, false)
);
self.selectedDates.sort((a,b) => a.getTime() - b.getTime());
}
function setDate(date, triggerChange) {
if (!date)
return self.clear();
setSelectedDate(date);
if (self.selectedDates.length > 0) {
self.dateIsPicked = true;
self.latestSelectedDateObj = self.selectedDates[0];
}
else
self.latestSelectedDateObj = null;
self.redraw();
jumpToDate();
setHoursFromDate();
updateValue();
if (triggerChange === true)
triggerEvent("Change");
}
function setupDates() {
function parseDateRules(arr) {
for (let i = arr.length; i--;) {
if (typeof arr[i] === "string" || +arr[i])
arr[i] = self.parseDate(arr[i], true);
else if (arr[i] && arr[i].from && arr[i].to) {
arr[i].from = self.parseDate(arr[i].from);
arr[i].to = self.parseDate(arr[i].to);
}
}
return arr.filter(x => x); // remove falsy values
}
self.selectedDates = [];
self.now = new Date();
setSelectedDate(self.config.defaultDate || self.input.value);
if (self.config.disable.length)
self.config.disable = parseDateRules(self.config.disable);
if (self.config.enable.length)
self.config.enable = parseDateRules(self.config.enable);
const initialDate = (self.selectedDates.length
? self.selectedDates[0]
: self.config.minDate && self.config.minDate.getTime() > self.now
? self.config.minDate
: self.config.maxDate && self.config.maxDate.getTime() < self.now
? self.config.maxDate
: self.now
);
self.currentYear = initialDate.getFullYear();
self.currentMonth = initialDate.getMonth();
if (self.selectedDates.length)
self.latestSelectedDateObj = self.selectedDates[0];
self.minDateHasTime = self.config.minDate && (self.config.minDate.getHours()
|| self.config.minDate.getMinutes()
|| self.config.minDate.getSeconds());
self.maxDateHasTime = self.config.maxDate && (self.config.maxDate.getHours()
|| self.config.maxDate.getMinutes()
|| self.config.maxDate.getSeconds());
Object.defineProperty(self, "latestSelectedDateObj", {
get() {
return self._selectedDateObj
|| self.selectedDates[self.selectedDates.length - 1]
|| null;
},
set(date) {
self._selectedDateObj = date;
}
});
}
function setupHelperFunctions() {
self.utils = {
duration: {
DAY: 86400000,
},
getDaysinMonth (month, yr) {
month = typeof month === "undefined"
? self.currentMonth
: month;
yr = typeof yr === "undefined"
? self.currentYear
: yr;
if (month === 1 && (((yr % 4 === 0) && (yr % 100 !== 0)) || (yr % 400 === 0)))
return 29;
return self.l10n.daysInMonth[month];
},
monthToStr (monthNumber, shorthand) {
shorthand = typeof shorthand === "undefined"
? self.config.shorthandCurrentMonth
: shorthand;
return self.l10n.months[(`${shorthand ? "short" : "long"}hand`)][monthNumber];
}
};
}
/* istanbul ignore next */
function setupFormats() {
self.formats = {
// weekday name, short, e.g. Thu
D: date => self.l10n.weekdays.shorthand[self.formats.w(date)],
// full month name e.g. January
F: date => self.utils.monthToStr(self.formats.n(date) - 1, false),
// hours with leading zero e.g. 03
H: date => Flatpickr.prototype.pad(date.getHours()),
// day (1-30) with ordinal suffix e.g. 1st, 2nd
J: date => date.getDate() + self.l10n.ordinal(date.getDate()),
// AM/PM
K: date => date.getHours() > 11 ? "PM" : "AM",
// shorthand month e.g. Jan, Sep, Oct, etc
M: date => self.utils.monthToStr(date.getMonth(), true),
// seconds 00-59
S: date => Flatpickr.prototype.pad(date.getSeconds()),
// unix timestamp
U: date => date.getTime() / 1000,
// full year e.g. 2016
Y: date => date.getFullYear(),
// day in month, padded (01-30)
d: date => Flatpickr.prototype.pad(self.formats.j(date)),
// hour from 1-12 (am/pm)
h: date => date.getHours() % 12 ? date.getHours() % 12 : 12,
// minutes, padded with leading zero e.g. 09
i: date => Flatpickr.prototype.pad(date.getMinutes()),
// day in month (1-30)
j: date => date.getDate(),
// weekday name, full, e.g. Thursday
l: date => self.l10n.weekdays.longhand[self.formats.w(date)],
// padded month number (01-12)
m: date => Flatpickr.prototype.pad(self.formats.n(date)),
// the month number (1-12)
n: date => date.getMonth() + 1,
// seconds 0-59
s: date => date.getSeconds(),
// number of the day of the week
w: date => date.getDay(),
// last two digits of year e.g. 16 for 2016
y: date => String(self.formats.Y(date)).substring(2)
};
}
function setupInputs() {
self.input = self.config.wrap
? self.element.querySelector("[data-input]")
: self.element;
if (!self.input)
return console.warn("Error: invalid input element specified", self.input);
self.input._type = self.input.type;
self.input.type = "text";
self.input.classList.add("flatpickr-input");
if (self.config.altInput) {
// replicate self.element
self.altInput = createElement(
self.input.nodeName,
self.input.className + " " + self.config.altInputClass
);
self.altInput.placeholder = self.input.placeholder;
self.altInput.type = "text";
self.input.type = "hidden";
if (self.input.parentNode)
self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling);
}
if (!self.config.allowInput)
(self.altInput || self.input).setAttribute("readonly", "readonly");
}
function setupMobile() {
const inputType = self.config.enableTime
? (self.config.noCalendar ? "time" : "datetime-local")
: "date";
self.mobileInput = createElement("input", self.input.className + " flatpickr-mobile");
self.mobileInput.step = "any";
self.mobileInput.tabIndex = 1;
self.mobileInput.type = inputType;
self.mobileInput.disabled = self.input.disabled;
self.mobileFormatStr = inputType === "datetime-local"
? "Y-m-d\\TH:i:S"
: inputType === "date"
? "Y-m-d"
: "H:i:S";
if (self.selectedDates.length) {
self.mobileInput.defaultValue
= self.mobileInput.value
= formatDate(self.mobileFormatStr, self.selectedDates[0]);
}
if (self.config.minDate)
self.mobileInput.min = formatDate("Y-m-d", self.config.minDate);
if (self.config.maxDate)
self.mobileInput.max = formatDate("Y-m-d", self.config.maxDate);
self.input.type = "hidden";
if (self.config.altInput)
self.altInput.type = "hidden";
try {
self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
}
catch (e) {
//
}
self.mobileInput.addEventListener("change", e => {
self.latestSelectedDateObj = self.parseDate(e.target.value);
self.setDate(self.latestSelectedDateObj);
triggerEvent("Change");
triggerEvent("Close");
});
}
function toggle() {
if (self.isOpen)
self.close();
else
self.open();
}
function triggerEvent(event, data) {
if (self.config["on" + event]) {
const hooks = Array.isArray(self.config["on" + event])
? self.config["on" + event]
: [self.config["on" + event]];
for (var i = 0; i < hooks.length; i++)
hooks[i](self.selectedDates, self.input.value, self, data);
}
if (event === "Change") {
if (typeof Event === "function" && Event.constructor) {
self.input.dispatchEvent(new Event("change", { "bubbles": true }));
// many front-end frameworks bind to the input event
self.input.dispatchEvent(new Event("input", { "bubbles": true }));
}
else {
if (window.document.createEvent !== undefined)
return self.input.dispatchEvent(self.changeEvent);
self.input.fireEvent("onchange");
}
}
}
function isDateSelected(date) {
for (let i = 0; i < self.selectedDates.length; i++) {
if (compareDates(self.selectedDates[i], date) === 0)
return "" + i;
}
return false;
}
function isDateInRange(date){
if (self.config.mode !== "range" || self.selectedDates.length < 2)
return false;
return compareDates(date,self.selectedDates[0]) >= 0
&& compareDates(date,self.selectedDates[1]) <= 0;
}
function updateNavigationCurrentMonth() {
if (self.config.noCalendar || self.isMobile || !self.monthNav)
return;
self.currentMonthElement.textContent = self.utils.monthToStr(self.currentMonth) + " ";
self.currentYearElement.value = self.currentYear;
if (self.config.minDate) {
const hidePrevMonthArrow = self.currentYear === self.config.minDate.getFullYear()
? self.currentMonth <= self.config.minDate.getMonth()
: self.currentYear < self.config.minDate.getFullYear();
self.prevMonthNav.style.display = hidePrevMonthArrow ? "none" : "block";
}
else
self.prevMonthNav.style.display = "block";
if (self.config.maxDate) {
const hideNextMonthArrow = self.currentYear === self.config.maxDate.getFullYear()
? self.currentMonth + 1 > self.config.maxDate.getMonth()
: self.currentYear > self.config.maxDate.getFullYear();
self.nextMonthNav.style.display = hideNextMonthArrow ? "none" : "block";
}
else
self.nextMonthNav.style.display = "block";
}
function updateValue() {
if (!self.selectedDates.length)
return self.clear();
if (self.isMobile) {
self.mobileInput.value = self.selectedDates.length
? formatDate(self.mobileFormatStr, self.latestSelectedDateObj)
: "";
}
const joinChar = self.config.mode !== "range" ? "; " : self.l10n.rangeSeparator;
self.input.value = self.selectedDates
.map(dObj => formatDate(self.config.dateFormat, dObj))
.join(joinChar);
if (self.config.altInput) {
self.altInput.value = self.selectedDates
.map(dObj => formatDate(self.config.altFormat, dObj))
.join(joinChar);
}
triggerEvent("ValueUpdate");
}
function yearScroll(e) {
e.preventDefault();
const delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.deltaY))),
newYear = parseInt(e.target.value, 10) + delta;
handleYearChange(newYear);
e.target.value = self.currentYear;
}
function createElement(tag, className, content) {
const e = window.document.createElement(tag);
className = className || "";
content = content || "";
e.className = className;
if (content)
e.textContent = content;
return e;
}
/* istanbul ignore next */
function debounce(func, wait, immediate) {
let timeout;
return function (...args) {
const context = this;
const later = function () {
timeout = null;
if (!immediate)
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (immediate && !timeout)
func.apply(context, args);
};
}
function compareDates(date1, date2, timeless) {
if (!(date1 instanceof Date) || !(date2 instanceof Date))
return false;
if (timeless !== false) {
return new Date(date1.getTime()).setHours(0,0,0,0)
- new Date(date2.getTime()).setHours(0,0,0,0);
}
return date1.getTime() - date2.getTime();
}
function timeWrapper(e) {
e.preventDefault();
if (e && (
(e.target.value || e.target.textContent).length >= 2 || // typed two digits
(e.type !== "keydown" && e.type !== "input") // scroll event
))
e.target.blur();
if (self.amPM && e.target === self.amPM)
return e.target.textContent = ["AM", "PM"][(e.target.textContent === "AM") | 0];
const min = Number(e.target.min),
max = Number(e.target.max),
step = Number(e.target.step),
curValue = parseInt(e.target.value, 10),
delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.deltaY)));
let newValue = Number(curValue);
switch(e.type) {
case "wheel":
newValue = curValue + step * delta;
break;
case "keydown":
newValue = curValue + step * (e.which === 38 ? 1 : -1);
break;
}
if (e.type !== "input" || e.target.value.length === 2) {
if (newValue < min) {
newValue = max + newValue + (e.target !== self.hourElement)
+ (e.target === self.hourElement && !self.amPM);
}
else if (newValue > max) {
newValue = e.target === self.hourElement
? newValue - max - (!self.amPM)
: min;
}
if (
self.amPM && e.target === self.hourElement && (step === 1
? newValue + curValue === 23
: Math.abs(newValue - curValue) > step)
)
self.amPM.textContent = self.amPM.textContent === "PM" ? "AM" : "PM";
e.target.value = self.pad(newValue);
}
else
e.target.value = newValue;
}
init();
return self;
}
/* istanbul ignore next */
Flatpickr.defaultConfig = {
mode: "single",
/* if true, dates will be parsed, formatted, and displayed in UTC.
preloading date strings w/ timezones is recommended but not necessary */
utc: false,
// wrap: see https://chmln.github.io/flatpickr/#strap
wrap: false,
// enables week numbers
weekNumbers: false,
// allow manual datetime input
allowInput: false,
/*
clicking on input opens the date(time)picker.
disable if you wish to open the calendar manually with .open()
*/
clickOpens: true,
// display time picker in 24 hour mode
time_24hr: false,
// enables the time picker functionality
enableTime: false,
// noCalendar: true will hide the calendar. use for a time picker along w/ enableTime
noCalendar: false,
// more date format chars at https://chmln.github.io/flatpickr/#dateformat
dateFormat: "Y-m-d",
// altInput - see https://chmln.github.io/flatpickr/#altinput
altInput: false,
// the created altInput element will have this class.
altInputClass: "flatpickr-input form-control input",
// same as dateFormat, but for altInput
altFormat: "F j, Y", // defaults to e.g. June 10, 2016
// defaultDate - either a datestring or a date object. used for datetimepicker"s initial value
defaultDate: null,
// the minimum date that user can pick (inclusive)
minDate: null,
// the maximum date that user can pick (inclusive)
maxDate: null,
// dateparser that transforms a given string to a date object
parseDate: null,
// dateformatter that transforms a given date object to a string, according to passed format
formatDate: null,
getWeek: function (givenDate) {
const date = new Date(givenDate.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
const week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 +
(week1.getDay() + 6) % 7) / 7);
},
// see https://chmln.github.io/flatpickr/#disable
enable: [],
// see https://chmln.github.io/flatpickr/#disable
disable: [],
// display the short version of month names - e.g. Sep instead of September
shorthandCurrentMonth: false,
// displays calendar inline. see https://chmln.github.io/flatpickr/#inline-calendar
inline: false,
// position calendar inside wrapper and next to the input element
// leave at false unless you know what you"re doing
static: false,
// DOM node to append the calendar to in *static* mode
appendTo: null,
// code for previous/next icons. this is where you put your custom icon code e.g. fontawesome
prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",
nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",
// enables seconds in the time picker
enableSeconds: false,
// step size used when scrolling/incrementing the hour element
hourIncrement: 1,
// step size used when scrolling/incrementing the minute element
minuteIncrement: 5,
// initial value in the hour element
defaultHour: 12,
// initial value in the minute element
defaultMinute: 0,
// disable native mobile datetime input support
disableMobile: false,
// default locale
locale: "default",
// onChange callback when user selects a date or time
onChange: null, // function (dateObj, dateStr) {}
// called every time calendar is opened
onOpen: null, // function (dateObj, dateStr) {}
// called every time calendar is closed
onClose: null, // function (dateObj, dateStr) {}
// called after calendar is ready
onReady: null, // function (dateObj, dateStr) {}
onValueUpdate: null,
onDayCreate: null
};
/* istanbul ignore next */
Flatpickr.l10ns = {
en: {
weekdays: {
shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
longhand: [
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
]
},
months: {
shorthand: [
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"
],
longhand: [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
]
},
daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
firstDayOfWeek: 0,
ordinal: (nth) => {
const s = nth % 100;
if (s > 3 && s < 21) return "th";
switch (s % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
},
rangeSeparator: " to ",
weekAbbreviation: "Wk",
scrollTitle: "Scroll to increment",
toggleTitle: "Click to toggle"
}
};
Flatpickr.l10ns.default = Object.create(Flatpickr.l10ns.en);
Flatpickr.localize = l10n => Object.assign(Flatpickr.l10ns.default, l10n || {});
Flatpickr.setDefaults = config => Object.assign(Flatpickr.defaultConfig, config || {});
Flatpickr.prototype = {
pad (number) {
return `0${number}`.slice(-2);
},
parseDate(date, timeless) {
if (!date)
return null;
const dateTimeRegex = /(\d+)/g,
timeRegex = /^(\d{1,2})[:\s](\d\d)?[:\s]?(\d\d)?\s?(a|p)?/i,
timestamp = /^(\d+)$/g,
date_orig = date;
if (date.toFixed || timestamp.test(date)) // timestamp
date = new Date(date);
else if (typeof date === "string") {
date = date.trim();
if (date === "today") {
date = new Date();
timeless = true;
}
else if (this.config && this.config.parseDate)
date = this.config.parseDate(date);
else if (timeRegex.test(date)) { // time picker
const m = date.match(timeRegex),
hours = !m[4]
? m[1] // military time, no conversion needed
: (m[1] % 12) + (m[4].toLowerCase() === "p" ? 12 : 0); // am/pm
date = new Date();
date.setHours(hours, m[2] || 0, m[3] || 0);
}
else if (/Z$/.test(date) || /GMT$/.test(date)) // datestrings w/ timezone
date = new Date(date);
else if (dateTimeRegex.test(date) && /^[0-9]/.test(date)) {
const d = date.match(dateTimeRegex);
date = new Date(
`${d[0]}/${d[1] || 1}/${d[2] || 1} ${d[3] || 0}:${d[4] || 0}:${d[5] || 0}`
);
}
else // fallback
date = new Date(date);
}
else if (date instanceof Date)
date = new Date(date.getTime()); // create a copy
if (!(date instanceof Date)) {
console.warn(`flatpickr: invalid date ${date_orig}`);
console.info(this.element);
return null;
}
if (this.config && this.config.utc && !date.fp_isUTC)
date = date.fp_toUTC();
if (timeless === true)
date.setHours(0, 0, 0, 0);
return date;
}
};
function _flatpickr(nodeList, config) {
const nodes = Array.prototype.slice.call(nodeList); // static list
let instances = [];
for (let i = 0; i < nodes.length; i++) {
try {
nodes[i]._flatpickr = new Flatpickr(nodes[i], config || {});
instances.push(nodes[i]._flatpickr);
}
catch (e) {
console.warn(e, e.stack);
}
}
return instances.length === 1 ? instances[0] : instances;
}
if (typeof HTMLElement !== "undefined") { // browser env
HTMLCollection.prototype.flatpickr =
NodeList.prototype.flatpickr = function (config) {
return _flatpickr(this, config);
};
HTMLElement.prototype.flatpickr = function (config) {
return _flatpickr([this], config);
};
}
function flatpickr(selector, config) {
return _flatpickr(window.document.querySelectorAll(selector), config);
}
if (typeof jQuery !== "undefined") {
jQuery.fn.flatpickr = function (config) {
return _flatpickr(this, config);
};
}
Date.prototype.fp_incr = function (days) {
return new Date(
this.getFullYear(),
this.getMonth(),
this.getDate() + parseInt(days, 10)
);
};
Date.prototype.fp_isUTC = false;
Date.prototype.fp_toUTC = function () {
const newDate = new Date(
this.getUTCFullYear(),
this.getUTCMonth(),
this.getUTCDate(),
this.getUTCHours(),
this.getUTCMinutes(),
this.getUTCSeconds()
);
newDate.fp_isUTC = true;
return newDate;
};
// IE9 classList polyfill
/* istanbul ignore next */
if (
!(window.document.documentElement.classList) &&
Object.defineProperty && typeof HTMLElement !== "undefined"
) {
Object.defineProperty(HTMLElement.prototype, "classList", {
get: function () {
let self = this;
function update(fn) {
return function (value) {
let classes = self.className.split(/\s+/),
index = classes.indexOf(value);
fn(classes, index, value);
self.className = classes.join(" ");
};
}
let ret = {
add: update((classes, index, value) => {
if (!(~index))
classes.push(value);
}),
remove: update((classes, index) => {
if (~index)
classes.splice(index, 1);
}),
toggle: update((classes, index, value) => {
if (~index)
classes.splice(index, 1);
else
classes.push(value);
}),
contains: value => !!~self.className.split(/\s+/).indexOf(value),
item: function (i) {
return self.className.split(/\s+/)[i] || null;
}
};
Object.defineProperty(ret, "length", {
get: function () {
return self.className.split(/\s+/).length;
}
});
return ret;
}
});
}
if (typeof module !== "undefined")
module.exports = Flatpickr;
|
"use strict";
const _ = require('lodash');
class ExpenseUtils {
constructor() {
}
sumUp (expenses) {
var sum = 0;
_(expenses).forEach((e) => {
sum += parseFloat(e.amount);
});
return sum.toFixed(2);
}
prettyPrintAll(expenses) {
var s = '';
_(expenses).forEach((e) => {
s += e.toString() + '\n';
});
return s;
}
}
module.exports = ExpenseUtils;
|
define([
'extensions/views/graph/interleavedbar'
],
function (InterleavedBar) {
var ConversionBar = InterleavedBar.extend({
interactive: true,
strokeAlign: 'inner',
blockWidth: function (group, groupIndex, model, index) {
var x0 = this.scales.x(this.graph.getXPos(0, 0));
var x1 = this.scales.x(this.graph.getXPos(0, 1));
return x1 - x0;
},
text: function (model, i) {
return this.formatNumericLabel(model.get('uniqueEvents'));
}
});
return ConversionBar;
});
|
// NOTE: This example uses the ALPHA release of the next generation Twilio
// helper library - for more information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/node#accessing-preview-twilio-features
// These consts are your accountSid and authToken from https://www.twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.preview.proxy
.services('KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.sessions('KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.participants.create({
identifier: '+15558675309',
friendly_name: 'Alice',
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
|
/* :indentSize=2:tabSize=2:noTabs=true: */
var jsdom = require("jsdom"),
expect = require('chai').expect,
coffeescript = require("coffee-script"),
jqueryFactory = require('jquery');
glyphtreeFactory = require(__dirname+"/../src/glyphtree.coffee");
describe('.glyphtree', function() {
describe('#options', function() {
it('should allow global options to be set', function (done) {
jsdom.env(
'<body><div id="test"></div></body>',
function(errors, window) {
var document = window.document,
$ = jqueryFactory.create(window),
glyphtree = glyphtreeFactory.create(window);
expect(glyphtree($('#test'))['_options'].classPrefix)
.to.equal('glyphtree-');
glyphtree.options.classPrefix = 'foobar-';
expect(glyphtree($('#test'))['_options'].classPrefix)
.to.equal('foobar-');
done();
}
);
});
});
});
describe('GlyphTree', function() {
var testTreeStructure = [
{
id: '25018945-704e-40d6-98c1-a30729277663',
name: "root",
attributes: {
foo: "bar"
},
children: [
{
id: '05089265-5f13-4fc8-a728-7a987c0c096e',
name: "subfolder",
children: [
{
id: '888c3513-9ab0-47e8-ab69-5b11effb1f6a',
name: "README"
},
{
// Intentionally no ID field, which should be fine
name: "file.txt"
}
]
}
]
}
];
describe('#options', function () {
it('should allow options to be specified', function(done) {
withTestTree(testTreeStructure,{
classPrefix: 'foobar-'
})(function(tree, $) {
// Prefix should change
expect($('.foobar-node').length).to.be.above(0);
expect($('.glyphtree-node').length).to.equal(0);
}, done);
});
});
describe('#load()', function() {
it('should load and render a tree', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
// Four nodes (root, subfolder, README, file.txt)
expect($('.glyphtree-node').length).to.equal(4);
// Four nodes name spans (root, subfolder, README, file.txt)
expect($('span.glyphtree-node-label').length).to.equal(4);
// Three trees
expect($('.glyphtree-tree').length).to.equal(3);
// Two leaf nodes
expect($('.glyphtree-leaf').length).to.equal(2);
}, done);
});
});
describe('#add()', function() {
it('should add nodes to the root', function(done) {
withTestTree({})(function(tree, $) {
// No nodes initially
expect($('.glyphtree-node').length).to.equal(0);
for (var i = 1; i <= 5; i++) {
var nodeName = "root node "+i;
// Add a node
tree.add({
name: nodeName
});
// A single node should exist
expect($('.glyphtree-node').length).to.equal(i);
expect($('.glyphtree-node:contains('+nodeName+')').length)
.to.equal(1);
expect($('.glyphtree-tree').length).to.equal(1);
}
}, done);
});
it('should add nodes to a parent designated by ID', function(done) {
withTestTree({})(function(tree, $) {
// No nodes initially
expect($('.glyphtree-node').length).to.equal(0);
for (var i = 1; i <= 5; i++) {
var nodeName = "root node "+i;
// Add a node
tree.add({
id: i,
name: nodeName
}, i > 1 ? i-1 : null);
// A single node should exist
expect($('.glyphtree-node').length).to.equal(i);
expect($('.glyphtree-node > .glyphtree-node-label:contains('
+nodeName+')').length).to.equal(1);
expect($('.glyphtree-tree').length).to.equal(i);
}
}, done);
});
it('should add nodes using natural ordering on name', function(done) {
function randomId() {
return (Math.random() * Math.pow(2,32))+"";
}
withTestTree({})(function(tree, $) {
// No nodes initially
expect($('.glyphtree-node').length).to.equal(0);
for (var i = 9; i > 0; i--) {
var nodeName = "root node "+i;
// Add a node
tree.add({
id: randomId(),
name: nodeName
});
}
var names = [];
$.each(tree.nodes(), function(i, v) {
names.push(v.name);
});
var sortedNames = names.concat().sort();
$.each(names, function(i, v) {
expect(v).to.equal(sortedNames[i]);
});
}, done);
});
});
describe('#update()', function() {
it('should update node', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
var newData = {
id: '888c3513-9ab0-47e8-ab69-5b11effb1f6a',
name: 'README.md',
type: 'file',
attributes: {
'Content-Type': 'text/plain'
}
};
expect(tree).to.respondTo('update');
tree.update(newData);
// Check the node updates
var node = tree.find(newData.id);
expect(node.name).to.equal(newData.name);
for (var k in Object.keys(node.attributes)) {
expect(node.attributes[k]).to.equal(newData.attributes[k])
}
// Check the node elements update
expect($('.glyphtree-node > .glyphtree-node-label:contains('
+newData.name+')').length).to.equal(1);
}, done);
});
it('should not update node children', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
var newData = {
id: '05089265-5f13-4fc8-a728-7a987c0c096e',
name: 'modified subfolder',
type: 'folder'
};
expect(tree).to.respondTo('update');
tree.update(newData);
// Check the node updates
var node = tree.find(newData.id);
expect(node.name).to.equal(newData.name);
// Check the children haven't been modified
expect(node.children.nodes).to.have.length(2);
}, done);
});
});
describe('#remove()', function() {
it('should remove nodes designated by ID', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
var nodeName = 'README'
expect($('.glyphtree-node > .glyphtree-node-label:contains('
+nodeName+')').length).to.equal(1);
tree.remove('888c3513-9ab0-47e8-ab69-5b11effb1f6a');
expect($('.glyphtree-node > .glyphtree-node-label:contains('
+nodeName+')').length).to.equal(0);
}, done);
});
it('should remove nodes previously added', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
var testNode = {
id: 'newly-added-node',
name: 'Foo Bar'
};
tree.add({
id: 'newly-added-node',
name: 'Foo Bar'
});
expect($('.glyphtree-node > .glyphtree-node-label:contains('
+testNode.name+')').length).to.equal(1);
tree.remove(testNode.id);
expect($('.glyphtree-node > .glyphtree-node-label:contains('
+testNode.name+')').length).to.equal(0);
}, done);
});
});
describe('#find()', function () {
it('should return the node with the given ID', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
var node;
node = tree.find('888c3513-9ab0-47e8-ab69-5b11effb1f6a');
expect(node.name).to.equal('README');
expect(node.isLeaf()).to.be.true;
node = tree.find('25018945-704e-40d6-98c1-a30729277663');
expect(node.name).to.equal('root');
expect(node.isLeaf()).to.be.false;
}, done);
});
it('should return null if no node found', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
var node;
node = tree.find('foobar');
expect(node).to.be.null;
node = tree.find(null);
expect(node).to.be.null;
}, done);
});
});
describe('#nodes()', function () {
it('should produce array of nodes in depth-first order', function(done) {
withTestTree(testTreeStructure)(function(tree, $) {
var nodes = tree.nodes();
expect(nodes[0].name).to.equal('root');
expect(nodes[1].name).to.equal('subfolder');
expect(nodes[2].name).to.equal('README');
expect(nodes[3].name).to.equal('file.txt');
expect(nodes[1].parent()).to.equal(nodes[0]);
expect(nodes[2].parent()).to.equal(nodes[1]);
expect(nodes[3].parent()).to.equal(nodes[1]);
}, done);
});
});
describe("#expandAll()", function() {
it ("should expand all trees", function(done) {
withTestTree(testTreeStructure)(function (tree, $) {
// Tree starts unexpanded
expect($('.glyphtree-expanded').length).to.equal(0);
// Click a node
tree.expandAll();
// The hierarchy should expand all nodes
expect($('.glyphtree-expanded').length).to.equal(4);
}, done);
});
});
describe("#collapseAll()", function() {
it ("should collapse all trees", function(done) {
withTestTree(testTreeStructure,{
startExpanded: true
})( function (tree, $) {
// Tree starts expanded
expect($('.glyphtree-expanded').length).to.equal(4);
// Click a node
tree.collapseAll();
// The hierarchy should expand all nodes
expect($('.glyphtree-expanded').length).to.equal(0);
}, done);
});
});
describe("#walk()", function() {
it ("should perform a function for all nodes in the tree", function(done){
withTestTree(testTreeStructure)(function (tree, $) {
var nodeCount = 0, leafCount = 0;
tree.walk(function(node) { nodeCount++ });
tree.walk(function(node) { if (node.isLeaf()) leafCount++ });
expect(nodeCount).to.equal(4);
expect(leafCount).to.equal(2);
}, done);
});
it ("should be safe to perform before tree load", function(done){
withTestTree(null)(function (tree, $) {
var nodeCount = 0;
tree.walk(function(node) { nodeCount++ });
expect(nodeCount).to.equal(0);
}, done);
});
});
describe("default user events", function() {
describe('click', function() {
it ("should toggle expansion of non-leaf nodes", function(done) {
withTestTree(testTreeStructure)(function (tree, $) {
var $e =
$([ '#test', '.glyphtree-tree',
'.glyphtree-node:not(.glyphtree-leaf)',
'.glyphtree-node-icon'
].join(' > ')).first()
// Tree starts unexpanded
expect($('.glyphtree-expanded').length).to.equal(0);
// Expand
$e.click();
// The hierarchy should expand one level
expect($('.glyphtree-expanded').length).to.equal(1);
// Collapse
$e.click();
// The hierarchy should collapse one level
expect($('.glyphtree-expanded').length).to.equal(0);
}, done);
});
it ("should not toggle leaf nodes", function(done) {
withTestTree(testTreeStructure)(function (tree, $) {
var $e =
$([ '#test .glyphtree-tree', // Subtree containing leaves
'.glyphtree-node.glyphtree-leaf',
'.glyphtree-node-icon'
].join(' > ')).first();
expect($e.length).to.equal(1);
// Tree starts unexpanded
expect($e.hasClass('glyphtree-expanded')).to.be.false;
// Expand
$e.click();
// The hierarchy should be the same
expect($e.hasClass('glyphtree-expanded')).to.be.false;
// Collapse
$e.click();
// The hierarchy should still be the same
expect($e.hasClass('glyphtree-expanded')).to.be.false;
}, done);
});
});
});
function withTestTree(structure, options) {
return function (jqueryTestFunc, callback) {
if (typeof(callback) != 'function')
throw new Error('Callback function is missing!');
jsdom.env(
'<body><div id="test"></div></body>',
function(errors, window) {
var document = window.document,
$ = jqueryFactory.create(window),
glyphtree = glyphtreeFactory.create(window);
var tree = glyphtree($('#test'), options);
if (structure != null) {
tree.load(structure);
}
jqueryTestFunc(tree, $);
callback();
}
);
}
}
});
|
import express from 'express';
import { db } from './db';
import cors from 'express-cors';
import path from 'path';
const app = express();
let rootPath;
switch(process.env.NODE_ENV) {
case 'production':
rootPath = path.resolve(__dirname, '../../public');
break;
case 'test':
rootPath = path.resolve(__dirname, '../../tmp');
break;
default:
rootPath = path.resolve(__dirname, '../../dist');
break;
}
app.use(express.static(rootPath));
app.use(cors({
allowedOrigins: ['localhost:3001']
}));
app.get('/', (req, res)=> {
res.sendFile(path.join(rootPath, 'index.html'));
});
app.delete('/messages', (req, res)=> {
db.clearMessages().then(()=> {
res.sendStatus(200);
}, (error)=> {
res.status(500).send(error);
});
});
export default app;
export function start() {
return app.listen(3000, ()=> {
console.log('WatchDog on guard.');
});
}
|
/**
* Created by maxvasterd on 14/12/15.
*/
angular.module('myApp.gamesOverview', ['ngRoute', 'ngMaterial'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/gameOverview', {
templateUrl: 'views/gameOverview/gameOverview.html',
controller: 'gameController'
});
}])
.controller('gameController', [function() {
var self = this;
self.games = [
{ quests: '3',name: 'Informatica'},
{ quests: '6',name: 'Economie'},
{ quests: '22',name: 'Rechten'},
{ quests: '15',name: 'Schilder'},
{ quests: '14',name: 'Gamedesign'}
];
}]); |
import _ from 'underscore';
this.t = function(key, ...replaces) {
if (_.isObject(replaces[0])) {
return TAPi18n.__(key, replaces);
} else {
return TAPi18n.__(key, {
postProcess: 'sprintf',
sprintf: replaces,
});
}
};
this.tr = function(key, options, ...replaces) {
if (_.isObject(replaces[0])) {
return TAPi18n.__(key, options, replaces);
} else {
return TAPi18n.__(key, options, {
postProcess: 'sprintf',
sprintf: replaces,
});
}
};
this.isRtl = (lang) => {
const language = lang || localStorage.getItem('userLanguage') || 'en-US';
return ['ar', 'dv', 'fa', 'he', 'ku', 'ps', 'sd', 'ug', 'ur', 'yi'].includes(language.split('-').shift().toLowerCase());
};
|
/// Jquery used for filter form sticky
$(document).ready(function(){
"use strict";
$("#headersticky").sticky({topSpacing:0});
});
|
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
var oDefaults = {
sName: '',
sLabel: '',
oClasses: {
sFieldClass: 'field-price',
sFieldSpanClass: 'field',
sPrefixClass: 'prefix',
sSuffixClass: 'suffix',
sFocusedClass: 'focus',
sInvalidClass: 'invalid',
sRequiredClass: 'required',
sWaitingClass: 'waiting',
sDisabledClass: 'disabled',
sFieldRepetitionClass: 'repetition',
sAddRepetitionClass: 'add-field-repetition',
sRemoveRepetitionClass: 'remove-field-repetition',
sNetPriceClass: 'net-price',
sGrossPriceClass: 'gross-price'
},
oImages: {
sAddRepetition: 'images/icons/buttons/add.png',
sRemoveRepetition: 'images/icons/buttons/delete.png'
},
sFieldType: 'text',
sDefault: '',
aoRules: [],
sComment: ''
};
var GFormPriceEditor = GCore.ExtendClass(GFormTextField, function () {
var gThis = this;
gThis._PrepareNode = function () {
gThis.m_jNode = $('<div/>').addClass(gThis._GetClass('Field'));
var jLabel = $('<label for="' + gThis.GetId() + '"/>');
jLabel.text(gThis.m_oOptions.sLabel);
if ((gThis.m_oOptions.sComment != undefined) && (gThis.m_oOptions.sComment.length)) {
jLabel.append(' <small>' + gThis.m_oOptions.sComment + '</small>');
}
gThis.m_jNode.append(jLabel);
gThis.m_jNode.append(gThis._AddField());
$(window).bind('OnVatChange', function () {
gThis._CalculateNetPrice();
});
};
gThis.GetValue = function (sRepetition) {
if (gThis.m_jField == undefined) {
return '';
}
return gThis.m_jField.eq(1).val();
};
gThis.SetValue = function (mValue, sRepetition) {
if (gThis.m_jField == undefined) {
return;
}
gThis.m_jField.eq(1).val(mValue).change();
};
gThis._AddField = function (sId) {
var jFieldNet = $('<input type="text" id="' + gThis.GetId() + '__net"/>');
var jFieldGross = $('<input type="text" name="' + gThis.GetName() + '" id="' + gThis.GetId() + '"/>');
var jRepetitionNode = $('<span class="' + gThis._GetClass('FieldRepetition') + '"/>');
var jNetNode = $('<span class="' + gThis._GetClass('NetPrice') + '"/>');
var jGrossNode = $('<span class="' + gThis._GetClass('GrossPrice') + '"/>');
if (gThis.m_oOptions.asPrefixes[0] != undefined) {
var jPrefix = $('<span class="' + gThis._GetClass('Prefix') + '"/>');
jPrefix.html(gThis.m_oOptions.asPrefixes[0]);
jNetNode.append(jPrefix);
}
jNetNode.append($('<span class="' + gThis._GetClass('FieldSpan') + '"/>').append(jFieldNet));
if (gThis.m_oOptions.sSuffix != undefined) {
var jSuffix = $('<span class="' + gThis._GetClass('Suffix') + '"/>');
jSuffix.html(gThis.m_oOptions.sSuffix);
jNetNode.append(jSuffix);
}
if (gThis.m_oOptions.asPrefixes[1] != undefined) {
var jPrefix = $('<span class="' + gThis._GetClass('Prefix') + '"/>');
jPrefix.html(gThis.m_oOptions.asPrefixes[1]);
jGrossNode.append(jPrefix);
}
jGrossNode.append($('<span class="' + gThis._GetClass('FieldSpan') + '"/>').append(jFieldGross));
if (gThis.m_oOptions.sSuffix != undefined) {
var jSuffix = $('<span class="' + gThis._GetClass('Suffix') + '"/>');
jSuffix.html(gThis.m_oOptions.sSuffix);
jGrossNode.append(jSuffix);
}
var jError = $('<span class="' + gThis._GetClass('Required') + '"/>');
jNetNode.append(jError);
jRepetitionNode.append(jNetNode).append(jGrossNode);
gThis.m_jField = jRepetitionNode.find('input');
gThis.jRepetitionNode = jRepetitionNode;
return gThis.jRepetitionNode;
};
gThis.OnShow = function () {
gThis._CalculateNetPrice(gThis.m_jField.eq(1).val());
gThis.m_bShown = true;
if (!gThis.m_bResized) {
gThis.m_bResized = true;
gThis.m_jField.each(function () {
var iWidth = Math.floor(parseInt($(this).css('width')) / 2) - 20;
var jParent = $(this).closest('.' + gThis._GetClass('NetPrice') + ', .' + gThis._GetClass('GrossPrice'));
if (jParent.find('.' + gThis._GetClass('Prefix')).length) {
iWidth -= ($(this).offset().left - jParent.find('.' + gThis._GetClass('Prefix')).offset().left) - 1;
}
if (jParent.find('.' + gThis._GetClass('Suffix')).length) {
iWidth -= jParent.find('.' + gThis._GetClass('Suffix')).width() + 4;
}
$(this).css('width', iWidth);
});
}
};
gThis._CalculateGrossPrice = function (sPrice) {
var gVat = gThis.m_gForm.GetField(gThis.m_oOptions.sVatField);
var iVatId = parseInt(gVat.GetValue());
var fVat = 0;
if (gThis.m_oOptions.aoVatValues[iVatId] != undefined) {
fVat = parseFloat(gThis.m_oOptions.aoVatValues[iVatId]);
}
if (sPrice == undefined) {
var sPrice = gThis.m_jField.eq(0).val();
}
var fPrice = parseFloat(sPrice.replace(/,/, '.'));
fPrice = isNaN(fPrice) ? 0 : fPrice;
gThis.m_jField.eq(1).val((fPrice * (1 + fVat / 100)).toFixed(2));
};
gThis._CalculateNetPrice = function (sPrice) {
var gVat = gThis.m_gForm.GetField(gThis.m_oOptions.sVatField);
var iVatId = gVat.GetValue();
var fVat = 0;
if (gThis.m_oOptions.aoVatValues[iVatId] != undefined) {
fVat = parseFloat(gThis.m_oOptions.aoVatValues[iVatId]);
}
if (sPrice == undefined) {
var sPrice = gThis.m_jField.eq(1).val();
}
var fPrice = parseFloat(sPrice.replace(/,/, '.'));
fPrice = isNaN(fPrice) ? 0 : fPrice;
gThis.m_jField.eq(0).val((fPrice / (1 + fVat / 100)).toFixed(2));
};
gThis._Initialize = function () {
var fHandler = GEventHandler(function (eEvent) {
setTimeout(function () {
gThis._CalculateGrossPrice($(eEvent.currentTarget).val());
}, 5);
});
gThis.m_jField.eq(0).keypress(fHandler).blur(fHandler).change(gThis.ValidateField);
fHandler = GEventHandler(function (eEvent) {
setTimeout(function () {
gThis._CalculateNetPrice($(eEvent.currentTarget).val());
}, 5);
});
gThis.m_jField.eq(1).keypress(fHandler).blur(fHandler).change(gThis.ValidateField);
gThis.m_gForm.GetField(gThis.m_oOptions.sVatField).m_jField.change(GEventHandler(function (eEvent) {
gThis._CalculateNetPrice();
}));
gThis._CalculateNetPrice();
gThis.m_jField.eq(1).change();
};
gThis.ValidateField = GEventHandler(function (eEvent) {
var fPrice = parseFloat($(eEvent.currentTarget).val().replace(/,/, '.'));
fPrice = isNaN(fPrice) ? 0 : fPrice;
$(eEvent.currentTarget).val(fPrice.toFixed(2));
});
gThis.Reset = function () {
gThis.m_jField.eq(1).val(gThis.m_oOptions.sDefault).change();
gThis._CalculateNetPrice();
};
}, oDefaults); |
// All symbols in the Armenian block as per Unicode v5.1.0:
[
'\u0530',
'\u0531',
'\u0532',
'\u0533',
'\u0534',
'\u0535',
'\u0536',
'\u0537',
'\u0538',
'\u0539',
'\u053A',
'\u053B',
'\u053C',
'\u053D',
'\u053E',
'\u053F',
'\u0540',
'\u0541',
'\u0542',
'\u0543',
'\u0544',
'\u0545',
'\u0546',
'\u0547',
'\u0548',
'\u0549',
'\u054A',
'\u054B',
'\u054C',
'\u054D',
'\u054E',
'\u054F',
'\u0550',
'\u0551',
'\u0552',
'\u0553',
'\u0554',
'\u0555',
'\u0556',
'\u0557',
'\u0558',
'\u0559',
'\u055A',
'\u055B',
'\u055C',
'\u055D',
'\u055E',
'\u055F',
'\u0560',
'\u0561',
'\u0562',
'\u0563',
'\u0564',
'\u0565',
'\u0566',
'\u0567',
'\u0568',
'\u0569',
'\u056A',
'\u056B',
'\u056C',
'\u056D',
'\u056E',
'\u056F',
'\u0570',
'\u0571',
'\u0572',
'\u0573',
'\u0574',
'\u0575',
'\u0576',
'\u0577',
'\u0578',
'\u0579',
'\u057A',
'\u057B',
'\u057C',
'\u057D',
'\u057E',
'\u057F',
'\u0580',
'\u0581',
'\u0582',
'\u0583',
'\u0584',
'\u0585',
'\u0586',
'\u0587',
'\u0588',
'\u0589',
'\u058A',
'\u058B',
'\u058C',
'\u058D',
'\u058E',
'\u058F'
]; |
var a: "foo bar" |
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import PlayerContext from './PlayerContext';
import { logWarning } from './utils/console';
import getReactParentNameStack from './utils/getReactParentNameStack';
class PlayerContextConsumer extends PureComponent {
render() {
const { children, filterList } = this.props;
if (!filterList) {
if (!this.warnedAboutFilterList) {
let warning = `
Please pass the filterList prop to PlayerContextConsumer in order
to avoid unnecessarily frequent re-renders, e.g.
const filterList = ['paused', 'onTogglePause'];
// ...
<PlayerContextConsumer filterList={filterList}>
{({ paused, onTogglePause }) => {
return <div>{/* ... */}</div>;
}}
</PlayerContextConsumer>
`;
for (const parentName of getReactParentNameStack(this)) {
warning += `
Rendered by ${parentName}`;
}
logWarning(warning);
this.warnedAboutFilterList = true;
}
return <PlayerContext.Consumer>{children}</PlayerContext.Consumer>;
}
const flags = PlayerContext.__cassetteGetObservedBits(filterList);
return (
<PlayerContext.Consumer unstable_observedBits={flags}>
{playerContext => {
const usedContext = {};
for (const name of filterList) {
if (playerContext.hasOwnProperty(name)) {
usedContext[name] = playerContext[name];
}
}
return children(usedContext);
}}
</PlayerContext.Consumer>
);
}
}
PlayerContextConsumer.propTypes = {
/**
* A [render prop](https://reactjs.org/docs/render-props.html) function
* which receives as its argument an object with the latest values of the
* keys specified in the `filterList` prop (if you forget `filterList`, you
* will get all the `playerContext` values and a warning in the console)
*/
children: PropTypes.func.isRequired,
/**
* A full list of `playerContext` values which will need to be consumed.
* Similar to the prop name array passed to
* [`playerContextFilter`](#playercontextfilter), but only made up of values
* found in [`playerContext`](#playercontext).
*
*/
filterList: PropTypes.arrayOf(PropTypes.string.isRequired)
};
export default PlayerContextConsumer;
|
// Primary Navigation
// =======================================
var controller = new ScrollMagic.Controller(),
atomic_nav = document.getElementById('nav'),
atomic_links = atomic_nav.children,
atomic_scrollinks = {};
for (var i = 0, l = atomic_links.length; i < l; i++) {
if(atomic_links[i].hash !== '') {
var href = atomic_links[i].hash.replace('#', ''),
id = atomic_links[i].id,
key = href;
atomic_scrollinks[key] = id;
}
}
for (var key in atomic_scrollinks) {
new ScrollMagic.Scene({
duration: document.getElementById(key).scrollHeight,
triggerElement: '#' + key
})
.setClassToggle('#' + atomic_scrollinks[key], 'active')
.addTo(controller);
}
function scrollToTween(target) {
TweenMax.to(window, 0.675, {
scrollTo : {
y: target,
autoKill: true
},
ease : Cubic.easeInOut
});
}
function scrollToTrigger(e) {
if(e.target && e.target.nodeName == 'A') {
var id = e.target.hash;
if(id.length > 0) {
e.preventDefault();
controller.scrollTo(id);
if (window.history && window.history.pushState) {
history.pushState('', document.title, id);
}
}
}
}
controller.scrollTo(function(target) {
scrollToTween(target);
});
atomic_nav.addEventListener('click', function(e) {
scrollToTrigger(e);
});
// Back To Top Button
// =======================================
var button_id = 'scroll-top';
var button_scene = new ScrollMagic.Scene({
offset: document.getElementsByTagName('header')[0].offsetHeight,
reverse: true
}).addTo(controller);
function hideTopButton(event, id) {
var el = document.getElementById(id);
el.style.opacity = 0;
}
function makeTopButton(event, id) {
var top_hash = document.body.getAttribute('id');
if(document.getElementById(id) === null) {
var el = document.createElement('a');
el.innerHTML = 'topside';
document.body.appendChild(el);
el.setAttribute('id', id);
el.setAttribute('href', '#' + top_hash);
el.addEventListener('click', function(e) {
scrollToTrigger(e);
});
} else {
document.getElementById(id).style.opacity = 1;
}
}
button_scene.on('enter', function(event) {
makeTopButton(event, button_id);
}).on('leave', function(event) {
hideTopButton(event, button_id);
});
|
/**
* Created by williamleong on 4/20/15.
*/
Meteor.methods({
deleteAccount: function(userId) {
if (this.userId === userId) {
return Meteor.users.remove({
_id: this.userId
});
}
}
}); |
$(function () {
// start the ticker
$('#js-news').ticker();
// hide the release history when the page loads
$('#release-wrapper').css('margin-top', '-' + ($('#release-wrapper').height() + 10) + 'px');
// show/hide the release history on click
$('a[href="#release-history"]').toggle(function () {
$('#release-wrapper').animate({
marginTop: '0px'
}, 800, 'linear');
}, function () {
$('#release-wrapper').animate({
marginTop: '-' + ($('#release-wrapper').height() + 10) + 'px'
}, 800, 'linear');
});
$('#download a').mousedown(function () {
_gaq.push(['_trackEvent', 'download-button', 'clicked'])
});
});
// google analytics code
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-6132309-2']);
_gaq.push(['_setDomainName', 'www.jquerynewsticker.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); |
import Details from '../../../../ui/components/details.jsx';
import fixture from '../../../fixtures/components/passed/details.js';
import {render} from '../../helpers.js';
describe('Passed', function() {
describe('Render', function() {
let component;
beforeEach(function() {
component = render(Details, fixture);
});
it('should display the baseline image', function() {
expect(component.refs.baseline.src).to.equal(fixture.paths.baseline);
});
});
});
|
'use strict';
var createFunnelCalculator = require('./lib/create-funnel-calculator');
module.exports = createFunnelCalculator;
|
export const CELL_STATUS_CLOSED = 'CELL_STATUS_CLOSED';
export const CELL_STATUS_OPENED = 'CELL_STATUS_OPENED';
export const CELL_STATUS_QUESTION = 'CELL_STATUS_QUESTION';
export const CELL_STATUS_MARK = 'CELL_STATUS_MARK';
export const GAME_STATUS_WIN = 'GAME_STATUS_WIN';
export const GAME_STATUS_LOOSE = 'GAME_STATUS_LOOSE';
export const GAME_STATUS_GAME = 'GAME_STATUS_GAME';
|
jQuery.selectpicker.widget = {};
jQuery.selectpicker.widget.picker = {
append: function( context ) {
var config = jQuery.selectpicker.config( context );
context
.prop( "disabled", true )
.hide()
.after(
jQuery( "<div>" )
.prop( { id: config.items.selector.picker.baseId.replace( "#", "" ) } )
.css( { position: "relative" } )
.addClass( config.items.cssClass.base )
.append(
jQuery( "<div>" )
.prop( { id: config.items.selector.picker.frameId.replace( "#", "" ) } )
.css( { position: "absolute", zIndex: 100 } )
.addClass( config.items.cssClass.frame )
.append(
jQuery( "<div>" )
.prop( {
id: config.items.selector.picker.labelId.replace( "#", "" ),
tabindex: config.items.tabindex
})
.addClass( config.items.cssClass.label )
)
)
.append(
jQuery( "<input>" )
.addClass( "fakeInput" )
.prop( { type: "text", tabindex: -1 } )
.css( { width: 1, height: 1, border: 0, outline: 0 } )
)
);
}
};
jQuery.selectpicker.widget.form = {
append: function( context ) {
var config = jQuery.selectpicker.config( context );
jQuery( config.items.selector.picker.frameId )
.append(
jQuery( "<input>" )
.prop( {
type: "hidden",
name: config.items.select.name,
id: config.items.selector.form.id.replace( "#", "" )
})
);
jQuery.selectpicker.widget.form.set( context, jQuery( config.items.select.id ).val() );
},
set: function( context, value ) {
var label,
config = jQuery.selectpicker.config( context );
if ( typeof value === "undefined" ) {
value = jQuery( config.items.select.id ).children( ":first" ).val();
}
jQuery( config.items.select.id ).val( value );
label = config.items.select.labels[ config.items.select.values.indexOf( value ) ];
jQuery( config.items.selector.form.id ).val( value );
jQuery( config.items.selector.picker.labelId ).text( label );
if ( config.loaded ) {
// XXX: fake input to make enter-key-form-submitable
jQuery( config.items.selector.picker.baseId ).find( ".fakeInput" ).focus().select()
config.items.callback.onPick.apply( context, [ value, label ] );
}
else {
config.items.callback.onLoad.apply( context, [ value, label ] );
config.loaded = true;
}
},
get: function( context ) {
var config = jQuery.selectpicker.config( context );
return jQuery( config.items.selector.form.id ).val();
}
};
jQuery.selectpicker.widget.options = {
append: function( context, options ) {
var base = jQuery.selectpicker.widget.options.base( context ),
config = jQuery.selectpicker.config( context );
jQuery( options ).each( function( _, option ) {
base.find( config.items.selector.options.childId ).append( jQuery.selectpicker.widget.options.child( context, option.label, option.value ) )
});
jQuery.selectpicker.widget.options.setCurrentPick( context );
},
hide: function( context ) {
var config = jQuery.selectpicker.config( context );
if ( jQuery(jQuery.selectpicker.widget.form.id ).is( ":disabled" ) ) {
return;
}
jQuery( config.items.selector.picker.frameId ).css( { zIndex: 100 } );
jQuery( config.items.selector.options.baseId ).hide();
jQuery( config.items.selector.picker.labelId )
.removeClass( config.items.cssClass.close )
.addClass( config.items.cssClass.open );
jQuery( config.items.selector.options.inputId ).prop( { tabindex: 0 } );
jQuery( config.items.selector.picker.labelId )
.prop( { tabindex: config.items.tabindex } )
.off( "focus.selectpicker" )
.on( "focus.selectpicker", config.events.onFocusPicker );
setTimeout( function() {
jQuery( config.items.selector.picker.labelId ).off( "click.selectpicker" );
}, 300 );
},
show: function( context ) {
var config = jQuery.selectpicker.config( context );
jQuery( config.items.selector.options.baseId ).show();
jQuery( config.items.selector.picker.frameId ).css( { zIndex: 999 } );
jQuery( config.items.selector.options.inputId ).focus().select();
jQuery( config.items.selector.picker.labelId )
.removeClass( config.items.cssClass.open )
.addClass( config.items.cssClass.close );
jQuery.selectpicker.widget.options.setCurrentPick( context );
jQuery( config.items.selector.picker.labelId )
.prop( { tabindex: -1 } )
.off( "focus.selectpicker" );
setTimeout( function() {
jQuery( config.items.selector.picker.labelId ).on( "click.selectpicker", config.events.onClickPicker );
}, 300 );
jQuery( config.items.selector.options.inputId )
.prop( { tabindex: config.items.tabindex } )
.one( "blur.selectpicker", config.events.onBlurPicker );
},
toggle: function( context ) {
var config = jQuery.selectpicker.config( context );
if ( jQuery( config.items.selector.picker.labelId ).hasClass( config.items.cssClass.open ) ) {
jQuery.selectpicker.widget.options.show( context );
}
else {
jQuery.selectpicker.widget.options.hide( context );
}
},
disable: function( context ) {
var config = jQuery.selectpicker.config( context );
jQuery.selectpicker.widget.options.hide( context );
jQuery( config.items.selector.form.id ).prop( "disabled", true );
setTimeout( function() {
jQuery( config.items.selector.picker.labelId )
.css( { opacity: 0.5 } )
.prop( { tabindex: -1 } )
.off( "focus.selectpicker" );
}, 0 );
},
enable: function( context ) {
var config = jQuery.selectpicker.config( context );
jQuery( config.items.selector.form.id ).prop( "disabled", false );
jQuery( config.items.selector.picker.labelId )
.css( { opacity: 1 } )
.off( "focus.selectpicker" )
.on( "focus.selectpicker", config.events.onFocusPicker );
},
isDisabled: function( context ) {
var config = jQuery.selectpicker.config( context );
return jQuery( config.items.selector.form.id ).prop( "disabled" );
},
base: function( context ) {
var optionsBase,
config = jQuery.selectpicker.config( context );
if ( jQuery( config.items.selector.options.baseId ).length <= 0 ) {
optionsBase = jQuery( "<div>" ).prop( {
id: config.items.selector.options.baseId.replace( "#", "" )
})
.append( jQuery.selectpicker.widget.options.search( context ) );
jQuery( config.items.selector.picker.frameId ).append( optionsBase );
}
else {
optionsBase = jQuery( config.items.selector.options.baseId );
}
if ( optionsBase.find( config.items.selector.options.childId ).length <= 0 ) {
optionsBase
.append(
jQuery( "<ul>" )
.prop( { id: config.items.selector.options.childId.replace( "#", "" ) } )
.addClass( config.items.cssClass.list )
.on( "mouseover.selectpicker", config.events.onMouseoverOptions )
.on( "mouseout.selectpicker", config.events.onMouseoutOptions )
);
}
else {
optionsBase.find( config.items.selector.options.childId ).children().remove();
}
return optionsBase;
},
search: function( context ) {
var config = jQuery.selectpicker.config( context );
return jQuery( "<input>" )
.addClass( config.items.cssClass.search )
.prop( {
type: "text",
id: config.items.selector.options.inputId.replace( "#", "" ),
"autocomplete": "off"
})
.attr( "autocomplete", "off" );
// for IE bug; attr autocomplete is not work for html attributes; only autocomplete??
},
child: function( context, label, value ) {
var config = jQuery.selectpicker.config( context );
return jQuery( "<li>" )
.data( config.items.dataKey, value )
.addClass( config.items.cssClass.item )
.append(
jQuery( "<a>" )
.prop( { href: "javascript:void(0)", tabindex: -1 } )
.text( label )
.on( "click.selectpicker", config.events.onClickOptions )
)
},
find: function( context, query ) {
var config = jQuery.selectpicker.config( context );
return jQuery.map( config.items.select.searchWords, function( val, idx ) {
if ( jQuery.selectpicker.widget.options.matchAll( context, query, val ) ) {
return {
value: config.items.select.values[ idx ],
label: config.items.select.labels[ idx ]
};
}
});
},
matchAll: function( context, query, sequence ) {
var result,
regexes = [/.*/],
config = jQuery.selectpicker.config( context );
if ( query.length > 0 ) {
regexes = jQuery.map( query.split( /(?:\s| )/ ), function( val ) {
return new RegExp( val, "i" );
});
}
result = true
jQuery.each( regexes, function( _, regex ) {
if ( !regex.test( sequence ) ) {
result = false
return
}
});
return result;
},
findCurrentPick: function( context ) {
var currentPick,
config = jQuery.selectpicker.config( context );
jQuery( config.items.selector.options.childId ).find( "li" ).each( function() {
if ( jQuery( this ).hasClass( config.items.cssClass.current ) ) {
currentPick = jQuery( this );
return;
}
});
return currentPick;
},
setCurrentPick: function( context, currentPick ) {
var scrollOption = {},
config = jQuery.selectpicker.config( context );
if ( typeof currentPick === "undefined" ) {
currentPick = jQuery.selectpicker.widget.options.findCurrentPick( context ) || jQuery( config.items.selector.options.childId ).children( ":first" );
}
if ( currentPick.length != 0 ) {
currentPick.addClass( config.items.cssClass.current );
scrollOption.scrollTop = currentPick.offset().top - currentPick.parent().children( ":first" ).offset().top;
currentPick.parent().animate( scrollOption, config.items.scrollDuration );
}
return currentPick;
}
};
|
let kuaida_data = require('../data/zh-cn/kuaida-data')
let builder = require('botbuilder')
let help = require('../data/zh-cn/help')
let anwser = require('../data/zh-cn/answer')
module.exports = [
(session)=>{
let msg = new builder.Message(session)
msg.attachmentLayout(builder.AttachmentLayout.carousel)
msg.attachments([
new builder.HeroCard(session)
.title(kuaida_data.what_1)
.subtitle(kuaida_data.what_2)
.text(kuaida_data.build_1)
.images([builder.CardImage.create(session, kuaida_data.build_2),
// builder.CardImage.create(session,kuaida_data.build_3),
// builder.CardImage.create(session,kuaida_data.build_4)
])
] )
session.send(msg);
builder.Prompts.text(session,anwser.answer_q1)
},
(session,results)=>{
// session.send()
session.dialogData.anwser = results.re
console.log('results.response:'+results.response)
if(results.response.match(/没/)){
session.endDialog(anwser.answer_a1)
}
}
// (session,args,next)=>{
// let intent = args.intent;
// let guanli = builder.EntityRecognizer.findEntity(intent.entities, '快搭::管理');
// let zuijian = builder.EntityRecognizer.findEntity(intent.entities,'快搭::组件');
// let mokuai = builder.EntityRecognizer.findEntity(intent.entities,'快搭::,模块');
// console.log('我看看这是什么鬼:'+session.dialog.note)
// }
] |
import merge from 'lodash/object/merge';
const initialState = {
users: {},
games: {},
participations: {}
};
export default function reducer(state = initialState, action = {}) {
if (action.entities) {
return merge({}, state, action.entities);
}
return state;
}
|
'use strict';
import React, {Component} from "react";
import {
StyleSheet,
View,
Text,
Image,
ScrollView,
Linking,
TouchableOpacity
} from "react-native";
import Dimensions from "Dimensions";
import theme from "@store/theme";
var {height, width} = Dimensions.get("window");
var _height = 250;
/**
* Media Widget
*/
class MediaPage extends Component {
constructor() {
super();
this.state = {
medias: null
};
}
componentDidMount() {
this.setState({
medias: this.props.media
});
}
_keyExtractor = (item, index) => item.id;
calcWidth(media, height) {
var height_perc = (height / media.original_height) * 100;
var width = (height_perc / 100) * media.original_width;
return width;
}
render() {
if (!this.state.medias) {
return null;
}
let self = this;
return (
<View style={styles.container}>
<Text style={[styles.title, {color: theme.colors.MAIN_TEXT}]}>Media</Text>
<ScrollView
horizontal={true}
showsHorizontalScrollIndicator={false}
style={{height: 300}}>
{this.state.medias.map(function (media) {
var newWidth = self.calcWidth(media, 300);
if (media.media_type == "image") {
return (
<Image
key={media.id}
source={{uri: media.image_url}}
resizeMethod="auto"
style={{
borderRadius: 5,
marginRight: 15,
height: 300,
width: newWidth,
flex: 1,
alignSelf: "stretch",
resizeMode: "contain"
}}
/>
)
} else if (media.media_type == "video" && media.platform == "youtube") {
return (
<TouchableOpacity
key={media.id}
onPress={() => {
Linking.openURL("https://www.youtube.com/watch?v=" + media.video_id)
}}>
<Image
source={{uri: media.image_url}}
resizeMethod="auto"
style={{
borderRadius: 5,
marginRight: 15,
height: 300,
width: 300,
flex: 1,
alignSelf: "stretch",
resizeMode: "contain"
}}
/>
</TouchableOpacity>
)
} else {
return null;
}
})}
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
margin: 15
},
title: {
color: "#1a1a1a",
fontSize: 25,
fontFamily: "SFBold"
}
});
module.exports = MediaPage;
|
// ###########
// # imports #
// ###########
import scrollToTarget from "../helper/scrollToTarget";
import find from "../helper/find";
import toggleClass from "../helper/toggleClass";
import updateTimestamp from "../tools/updateTimestamp";
// ###########
// # program #
// ###########
function setupTimeline(response) {
// place response
document.getElementById("application-content").innerHTML = response;
// get unreadItem-element and it's count
window.unreadItemsCount = document.getElementById(
"unread-items"
).dataset.unreaditems;
window.unreadItemsElementCount = document.getElementById(
"unread-items__count"
);
// now get amount of feeditems and calculate latest item to se it as scroll-anchor
let allFeedItems = find(".timeline__item");
let latestItem = allFeedItems[unreadItemsCount - 1];
// toggle ui-elements
if (window.unreadItemsCount > 0) {
toggleClass(find("#unread-items"), "js-hidden");
}
toggleClass(find("#application-loading"), "js-hidden");
// scroll to target
scrollToTarget(latestItem, 0, window.headerHeight, () => {
updateTimestamp(allFeedItems);
});
}
export default setupTimeline;
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var roles = require('./routes/roles');
var app = express();
//configure passport
require('./config/passport')(passport);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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(session({
genId:function(req){
return genuuid()
},
secret:'SUPERDUPERSECRETSTUFF'
}));
app.use(passport.initialize()); //initialize passport
app.use(passport.session()); //initialize passport sessions
app.use('/api/', routes);
app.use('/api/users', users);
app.use('/api/roles', roles);
// 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: {}
});
});
module.exports = app;
|
class compatcontextmenu_compatcontextmenu_1 {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = compatcontextmenu_compatcontextmenu_1;
|
/**
* This cloudflare worker performs the following functions:
* - rejects banned clients
* - enforce presence of API Key
* - responds to read queries using mirror api hosts (if available, tracking unavailable hosts)
* - sends writes to master API
* - logs request summary to logs.openchargemap.org for debug purposes (rejections, API abuse etc)
* */
const enableAPIKeyRules = true;
const enableMirrorChecks = false;
const enableDebug = false;
const enableLogging = true; // if true, API requests are logged to central log API
const enablePrimaryForReads = true; // if true, primary API server is skipped for reads
const requireAPIKeyForAllRequests = true;
const logTimeoutMS = 2000;
const corsHeaders = {
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
}
function handleOptions(request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
let headers = request.headers
if (
headers.get("Origin") !== null &&
headers.get("Access-Control-Request-Method") !== null &&
headers.get("Access-Control-Request-Headers") !== null
) {
// Handle CORS pre-flight request.
// If you want to check or reject the requested method + headers
// you can do that here.
let respHeaders = {
...corsHeaders,
"Access-Control-Allow-Origin": headers.get("Origin") ?? "*",
"Access-Control-Allow-Credentials": "true",
// Allow all future content Request headers to go back to browser
// such as Authorization (Bearer) or X-Client-Name-Version
"Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers"),
}
return new Response(null, {
headers: respHeaders,
})
}
else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
})
}
}
addEventListener('fetch', async event => {
// handle basic OPTION queries
if (event.request.method == "OPTIONS") {
// Handle CORS preflight requests
return event.respondWith(handleOptions(event.request))
}
// disallow robots
if (event.request.url.toString().indexOf("/robots.txt") > -1) {
return event.respondWith(
new Response("user-agent: * \r\ndisallow: /", {
headers: {
"content-type": "text/plain"
}
})
)
}
// pass through .well-known for acme http validation on main server
if (event.request.url.toString().indexOf("/.well-known/") > -1) {
let url = new URL(event.request.url);
url.hostname = "api-01.openchargemap.io";
console.log("Redirected to well known " + url);
let modifiedRequest = new Request(url, {
method: event.request.method,
headers: event.request.headers
});
return event.respondWith(fetch(modifiedRequest));
}
// check for banned IPs or banned User Agents
const clientIP = event.request.headers.get('cf-connecting-ip');
const userAgent = event.request.headers.get('user-agent');
if (userAgent && userAgent.indexOf("FME/2020") > -1) {
event.respondWith(rejectRequest(event, "Blocked for API Abuse. Callers spamming API with repeated duplicate calls may be auto banned."));
return;
}
// check API key
const apiKey = getAPIKey(event.request);
let status = "OK";
if (apiKey == null
&& userAgent
&& (userAgent.indexOf("python-requests") > -1 ||
userAgent.indexOf("Java/1.8.0_271") > -1)) {
return event.respondWith(rejectRequest(event, "Generic user agents must use an API Key. API Keys are mandatory and this rule will be enforced soon. https://openchargemap.org/site/develop/api"));
}
if (enableAPIKeyRules) {
let maxresults = getParameterByName(event.request.url, "maxresults");
if (apiKey == null && requireAPIKeyForAllRequests == true && event.request.method != "OPTIONS") {
status = "REJECTED_APIKEY_MISSING";
event.respondWith(rejectRequest(event));
}
else if (apiKey == null && maxresults != null && parseInt(maxresults) > 250) {
status = "REJECTED_APIKEY_MISSING";
event.respondWith(rejectRequest(event));
} else {
if (enableDebug) console.log("Passing request with API Key or key not required:" + apiKey);
//respond
event.respondWith(fetchAndApply(event, apiKey, status));
}
} else {
//respond
event.respondWith(fetchAndApply(event, apiKey, status));
}
//log
if (enableLogging) {
event.waitUntil(attemptLog(event, apiKey, status));
}
});
async function attemptLog(event, apiKey, status) {
// attempt to log but timeout after 1000 ms if no response from log
// Initiate the fetch but don't await it yet, just keep the promise.
let logPromise = logRequest(event.request, apiKey, status)
// Create a promise that resolves to `undefined` after 10 seconds.
let timeoutPromise = new Promise(resolve => setTimeout(resolve, logTimeoutMS))
// Wait for whichever promise completes first.
return Promise.race([logPromise, timeoutPromise])
}
async function rejectRequest(event, reason) {
if (!reason || reason == null) {
reason = "You must specify an API Key, either in an X-API-Key header or key= query string parameter.";
}
console.log(reason);
return new Response(reason, {
status: 403,
});
}
async function fetchAndApply(event, apiKey, status) {
let banned_ua = []; //await OCM_CONFIG_KV.get("API_BANNED_UA", "json");
let banned_ip = []; //await OCM_CONFIG_KV.get("API_BANNED_IP", "json");
let banned_keys = []; //await OCM_CONFIG_KV.get("API_BANNED_KEYS", "json");
const clientIP = event.request.headers.get('cf-connecting-ip');
const userAgent = event.request.headers.get('user-agent');
let abuseMsg = "Blocked for API Abuse. Callers spamming API with repeated duplicate calls may be auto banned.";
if (banned_ua.includes(userAgent)) {
status = "BANNED_UA";
return rejectRequest(event, abuseMsg)
}
if (banned_ip.includes(clientIP)) {
status = "BANNED_IP";
return rejectRequest(event, abuseMsg)
}
if (banned_keys.includes(apiKey)) {
status = "BANNED_KEY";
return rejectRequest(event, abuseMsg)
}
let mirrorHosts = [
"api-01.openchargemap.io"
];
// check if we think this user is currently an editor (has posted)
let ip_key = clientIP != null ? "API_EDITOR_" + clientIP.replace(".", "_") : null;
let isEditor = false;
if (ip_key != null) {
if (await OCM_CONFIG_KV.get(ip_key) != null) {
isEditor = true;
}
}
// get list of mirrors from KV store and append to our working list
if (enableMirrorChecks) {
let kv_mirrors = await OCM_CONFIG_KV.get("API_MIRRORS", "json");
mirrorHosts.push(...kv_mirrors);
let kv_skipped_mirrors = await OCM_CONFIG_KV.get("API_SKIPPED_MIRRORS", "json");
// remove any mirrors temporarily not in use.
if (kv_skipped_mirrors != null && kv_mirrors.length > 1) {
if (enableDebug) console.log("Skipped Mirrors:");
if (enableDebug) console.log(kv_skipped_mirrors);
mirrorHosts = mirrorHosts.filter(k => !kv_skipped_mirrors.includes(k))
}
}
if (enableDebug) console.log("Viable mirrors:");
if (enableDebug) console.log(mirrorHosts);
////////////////
let enableCache = false;
// redirect request to backend api
let url = new URL(event.request.url);
if (
event.request.method != "POST" &&
!url.href.includes("/geocode") &&
!url.href.includes("/map") &&
!url.href.includes("/openapi") &&
!url.href.includes("/.well-known")
) {
let mirrorIndex = getRandomInt(0, mirrorHosts.length);
// force query to first mirror if there is one available;
if (!enablePrimaryForReads && mirrorIndex == 0 && mirrorHosts.length > 1) {
mirrorIndex = 1;
}
if (mirrorIndex > 0) {
console.log("Using mirror API " + mirrorIndex + " for request. " + mirrorHosts[mirrorIndex]);
}
// if not doing a POST request reads can be served randomly from mirrors or from cache
url.hostname = mirrorHosts[mirrorIndex];
if (url.hostname != mirrorHosts[0]) {
url.protocol = "http";
url.port = "80";
}
// get cached response if available, otherwise fetch new response and cache it
let cache = caches.default;
let response = null;
if (enableCache) response = await cache.match(event.request);
if (!response) {
let modifiedRequest = new Request(url, {
method: event.request.method,
headers: event.request.headers
});
try {
response = await fetch(modifiedRequest);
// Make the headers mutable by re-constructing the Response.
response = new Response(response.body, response);
if (!response.ok && response.status >= 500) {
console.log("Forwarded request failed. " + response.status);
throw "Mirror response status failed:" + response.status;
}
response.headers.set('x-forwarded-host', url.hostname);
if (response.headers.get('Access-Control-Allow-Origin') === null) {
response.headers.append("Access-Control-Allow-Origin", "*");
}
if (response.headers.get('Access-Control-Allow-Credentials') === null) {
response.headers.append("Access-Control-Allow-Credentials", "true");
}
if (enableCache) event.waitUntil(cache.put(event.request, response.clone()));
return response;
} catch {
// failed to fetch from mirror, try primary
console.log("Forwarded request failed. Retrying to primary API");
// add failed mirror to skipped mirrors
if (mirrorIndex != 0) {
await OCM_CONFIG_KV.put("API_SKIPPED_MIRRORS", JSON.stringify([mirrorHosts[mirrorIndex]]), { expirationTtl: 60 * 15 });
}
response = await fetch(event.request);
if (enableCache) event.waitUntil(cache.put(event.request, response.clone()));
return response;
}
} else {
console.log("Using cached response");
return response;
}
} else {
// POSTs (and certain GETs) only go to primary API
if (enableDebug) console.log("Using primary API for request. " + url.origin);
if (event.request.method == "POST") {
if (ip_key != null) {
await OCM_CONFIG_KV.put(ip_key, "true", { expirationTtl: 60 * 60 * 12 });
if (enableDebug) console.log("Logged user as an editor:" + ip_key);
}
}
response = await fetch(event.request);
return response
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
function getParameterByName(url, name) {
name = name.replace(/[\[\]]/g, '\\$&')
name = name.replace(/\//g, '')
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url)
if (!results) return null
else if (!results[2]) return ''
else if (results[2]) {
results[2] = results[2].replace(/\//g, '')
}
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function getAPIKey(request) {
let apiKey = getParameterByName(request.url, "key");
//console.log("API Key From URL:" + apiKey);
if (apiKey == null || apiKey == '') {
apiKey = request.headers.get('X-API-Key');
if (enableDebug) console.log("API Key From Uppercase header:" + apiKey);
}
if (apiKey == null || apiKey == '') {
apiKey = request.headers.get('x-api-key');
if (enableDebug) console.log("API Key From Lowercase header:" + apiKey);
}
if (apiKey == '' || apiKey == 'test' || apiKey == 'null') apiKey = null;
return apiKey;
}
async function logRequest(request, apiKey, status) {
// log the url of the request and the API key used
var ray = request.headers.get('cf-ray') || '';
var id = ray.slice(0, -4);
var data = {
'timestamp': Date.now(),
'url': request.url,
'referer': request.referrer,
'method': request.method,
'ray': ray,
'ip': request.headers.get('cf-connecting-ip') || '',
'host': request.headers.get('host') || '',
'ua': request.headers.get('user-agent') || '',
'cc': request.headers.get('Cf-Ipcountry') || '',
'ocm_key': apiKey,
'status': status
};
var url = `http://log.openchargemap.org/?status=${data.status}&key=${data.ocm_key}&ua=${data.ua}&ip=${data.ip}&url=${encodeURI(request.url)}`;
//console.log("Logging Request "+url+" ::"+JSON.stringify(data));
try {
await fetch(url, {
method: 'PUT',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json',
})
});
} catch (exp) {
console.log("Failed to log request");
}
} |
// includes
var express = require('express');
var mysql = require('mysql');
var app = express();
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
var bodyParser = require('body-parser');
// set the app variables
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', 9009);
// body parser stuff
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
// static folder
app.use(express.static('public'));
// connect to the database
var pool = mysql.createPool({
connectionLimit : 10,
host : 'classmysql.engr.oregonstate.edu',
user : 'cs290_morrissz',
password : '4443',
database : 'cs290_morrissz'
});
// get route for home
app.get(['/', '/home'], function(req, res) {
var context = {};
// console.log("Getting workout list...");
queryText = "SELECT " +
"id, " +
"name, " +
"reps, " +
"weight, " +
"DATE_FORMAT(ex_date, \"%Y-%m-%d\") as ex_date, " +
"units " +
"FROM exercises";
// console.log("Firing query: " + queryText);
pool.query(queryText, function(err, result, fields) {
context.exercises = result;
// console.log(context);
res.render('home', context);
});
});
// api call for sending new data to the database
app.post('/', function(req, res) {
console.log("POST received.");
// console.log(req.body);
queryText = "INSERT INTO exercises (name, reps, weight, ex_date, units)\n" +
"VALUES (\n" +
"\'" + req.body.name + "\',\n" +
"\'" + req.body.reps + "\',\n" +
"\'" + req.body.weight + "\',\n" +
"\'" + req.body.date + "\',\n" +
"\'" + req.body.units + "\'\n" +
")";
pool.query(queryText, function(err, result, fields) {
if (err) {
res.send({'status': 'error'})
} else {
// console.log(result);
res.send({'status': 'success', 'id': result.insertId});
}
});
});
// api call for removing entries in the database
app.delete('/', function(req, res) {
console.log("DELETE received.");
queryText = "DELETE FROM exercises WHERE id = " + req.body.id;
console.log(queryText);
pool.query(queryText, function(err, result, fields) {
if (err) {
res.send({'status': 'error'})
} else {
// console.log(result);
res.send({'status': 'success'});
}
});
});
// 404 page
app.use(function(req,res){
res.status(404);
res.render('404');
});
// 500 page for internal errors
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500);
res.render('500');
});
// turn the web server on
app.listen(app.get('port'), function() {
console.log('Express started on http://localhost:' + app.get('port'));
});
|
'use strict';
chrome.browserAction.onClicked.addListener(() => {
chrome.tabs.create({
active: true,
url: 'options/options.html'
}, null);
});
|
var utils = require("../lib/utils"),
assert = require("assert");
var now = new Date().getTime().toString();
describe('utils', function() {
it('should generate unique identifiers', function() {
var generatedIds = [];
for (var i = 0; i < 1000; i++) {
var id = utils.uniqueId();
assert(id);
assert(id.length >= 6);
assert.equal(-1, generatedIds.indexOf(id));
generatedIds.push(id);
}
});
it('should format the current date', function() {
var date = utils.getFormattedDate(now);
assert(date);
assert(date.length == 8);
});
it('should format the current time', function() {
var time = utils.getFormattedTime(now);
assert(time);
assert(time.length == 9);
});
});
|
import styled from 'styled-components';
const List = styled.ul`
font-family: Georgia, Times, 'Times New Roman', serif;
padding-left: 1.75em;
list-style:none;
`;
export default List;
|
const gulp = require('gulp')
const source = require('vinyl-source-stream')
const browserify = require('browserify')
const watchify = require('watchify')
const reactify = require('reactify')
const gulpif = require('gulp-if')
const uglify = require('gulp-uglify')
const streamify = require('gulp-streamify')
const notify = require('gulp-notify')
const concat = require('gulp-concat')
const cssmin = require('gulp-cssmin')
const gutil = require('gulp-util')
const shell = require('gulp-shell')
const glob = require('glob')
const livereload = require('gulp-livereload')
const jasminePhantomJs = require('gulp-jasmine2-phantomjs')
const fetcher = require('./fetcher')
const fs = require('fs')
// External dependencies you do not want to rebundle while developing,
// but include in your application deployment
var dependencies = [
'react',
'react-addons'
];
var browserifyTask = function (options) {
// Our app bundler
var appBundler = browserify({
entries: [options.src], // Only need initial file, browserify finds the rest
transform: [reactify], // We want to convert JSX to normal javascript
debug: options.development, // Gives us sourcemapping
cache: {},
packageCache: {},
fullPaths: options.development // Requirement of watchify
});
// We set our dependencies as externals on our app bundler when developing
(options.development ? dependencies : []).forEach(function(dep){
appBundler.external(dep);
});
// The rebundle process
var rebundle = function(){
var start = Date.now()
console.log('Building APP bundle')
appBundler.bundle()
.on('error', gutil.log)
.pipe(source('main.js'))
.pipe(gulpif(!options.development, streamify(uglify())))
.pipe(gulp.dest(options.dest))
.pipe(gulpif(options.development, livereload()))
.pipe(notify(function(){
console.log('APP bundle built in ' + (Date.now() - start) + 'ms');
}))
} // end rebundle definition
// Fire up Watchify when developing
if (options.development) {
appBundler = watchify(appBundler);
appBundler.on('update', rebundle);
}
// Run it at least once...
rebundle()
// We create a separate bundle for our dependencies as they
// should not rebundle on file changes. This only happens when
// we develop. When deploying, the dependencies will be included
// in the application bundle
if (options.development) {
var testFiles = glob.sync('./specs/**/*-spec.js')
var testBundler = browserify({
entries: testFiles,
debug: true, // Gives us sourcemapping
transform: [reactify],
cache: {},
packageCache: {},
fullPaths: true // Requirement of watchify
})
dependencies.forEach(function(dep){
testBundler.external(dep)
})
var rebundleTests = function () {
var start = Date.now()
console.log('Building TEST bundle')
testBundler.bundle()
.on('error', gutil.log)
.pipe(source('specs.js'))
.pipe(gulp.dest(options.dest))
.pipe(livereload())
.pipe(notify(function () {
console.log('TEST bundle built in ' + (Date.now() - start) + 'ms');
}))
}
testBundler = watchify(testBundler)
testBundler.on('update', rebundleTests)
rebundleTests()
// Remove react-addons when deploying, as it is only for
// testing
if (!options.development) {
dependencies.splice(dependencies.indexOf('react-addons'), 1);
}
var vendorsBundler = browserify({
debug: true,
require: dependencies
});
// Run the vendor bundle
var start = new Date();
console.log('Building VENDORS bundle')
vendorsBundler.bundle()
.on('error', gutil.log)
.pipe(source('vendors.js'))
.pipe(gulpif(!options.development, streamify(uglify())))
.pipe(gulp.dest(options.dest))
.pipe(notify(function () {
console.log('VENDORS bundle built in ' + (Date.now() - start) + 'ms')
}))
}
}
var cssTask = function (options) {
if (options.development) {
var run = function () {
var start = new Date();
console.log('Building CSS bundle');
gulp.src(options.src)
.pipe(concat('main.css'))
.pipe(gulp.dest(options.dest))
.pipe(notify(function () {
console.log('CSS bundle built in ' + (Date.now() - start) + 'ms');
}))
};
run();
gulp.watch(options.src, run);
} else {
gulp.src(options.src)
.pipe(concat('main.css'))
.pipe(cssmin())
.pipe(gulp.dest(options.dest));
}
}
var fetchTask = function(options){
console.log('Running Fetcher...')
// Using request under the hood...
fetcher(function fetcherCallback(err,data){
if(err) return console.error(err)
writeFile(JSON.stringify(data), options.path)
// console.dir(data)
})
}
// Helper to write github output file...
function writeFile(data, path){
var wstream = fs.createWriteStream(path)
wstream.write(data)
wstream.end()
}
// Starts our development workflow
gulp.task('default', function () {
fetchTask({
path: './build/github_output.json'
})
browserifyTask({
development: true,
src: './app/main.js',
dest: './build'
});
cssTask({
development: true,
src: ['./styles/variables.css','./styles/reset.css','./styles/main.css'],
dest: './build'
});
});
gulp.task('deploy', function () {
browserifyTask({
development: false,
src: './app/main.js',
dest: './dist'
});
cssTask({
development: false,
src: ['./styles/variables.css','./styles/reset.css','./styles/main.css'],
dest: './dist'
});
fetchTask({
path: './dist/github_output.json'
})
})
gulp.task('test', function(){
return gulp.src('./build/testrunner-phantomjs.html').pipe(jasminePhantomJs())
})
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M22 3.41L16.71 8.7 20 12h-8V4l3.29 3.29L20.59 2 22 3.41zM3.41 22l5.29-5.29L12 20v-8H4l3.29 3.29L2 20.59 3.41 22z" />
, 'CloseFullscreenOutlined');
|
export default class MapView {
on() {}
}
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'morganizer',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
module.exports = {
"key": "raichu",
"moves": [
{
"learn_type": "tutor",
"name": "covet"
},
{
"learn_type": "machine",
"name": "wild-charge"
},
{
"learn_type": "machine",
"name": "volt-switch"
},
{
"learn_type": "machine",
"name": "echoed-voice"
},
{
"learn_type": "machine",
"name": "round"
},
{
"learn_type": "tutor",
"name": "magnet-rise"
},
{
"learn_type": "tutor",
"name": "signal-beam"
},
{
"learn_type": "tutor",
"name": "knock-off"
},
{
"learn_type": "tutor",
"name": "helping-hand"
},
{
"learn_type": "machine",
"name": "charge-beam"
},
{
"learn_type": "machine",
"name": "grass-knot"
},
{
"learn_type": "machine",
"name": "captivate"
},
{
"learn_type": "machine",
"name": "giga-impact"
},
{
"learn_type": "machine",
"name": "focus-blast"
},
{
"learn_type": "machine",
"name": "fling"
},
{
"learn_type": "machine",
"name": "natural-gift"
},
{
"learn_type": "tutor",
"name": "counter"
},
{
"learn_type": "machine",
"name": "shock-wave"
},
{
"learn_type": "machine",
"name": "secret-power"
},
{
"learn_type": "machine",
"name": "brick-break"
},
{
"learn_type": "machine",
"name": "focus-punch"
},
{
"learn_type": "machine",
"name": "facade"
},
{
"learn_type": "machine",
"name": "rock-smash"
},
{
"learn_type": "machine",
"name": "light-screen"
},
{
"learn_type": "machine",
"name": "dig"
},
{
"learn_type": "machine",
"name": "rain-dance"
},
{
"learn_type": "machine",
"name": "hidden-power"
},
{
"learn_type": "machine",
"name": "iron-tail"
},
{
"learn_type": "machine",
"name": "dynamicpunch"
},
{
"learn_type": "machine",
"name": "frustration"
},
{
"learn_type": "machine",
"name": "return"
},
{
"learn_type": "machine",
"name": "sleep-talk"
},
{
"learn_type": "machine",
"name": "attract"
},
{
"learn_type": "machine",
"name": "swagger"
},
{
"learn_type": "machine",
"name": "rollout"
},
{
"learn_type": "machine",
"name": "endure"
},
{
"learn_type": "machine",
"name": "detect"
},
{
"learn_type": "machine",
"name": "zap-cannon"
},
{
"learn_type": "machine",
"name": "mud-slap"
},
{
"learn_type": "machine",
"name": "protect"
},
{
"learn_type": "machine",
"name": "curse"
},
{
"learn_type": "machine",
"name": "snore"
},
{
"learn_type": "machine",
"name": "thief"
},
{
"learn_type": "machine",
"name": "defense-curl"
},
{
"learn_type": "level up",
"level": 1,
"name": "quick-attack"
},
{
"learn_type": "machine",
"name": "strength"
},
{
"learn_type": "level up",
"level": 1,
"name": "tail-whip"
},
{
"learn_type": "machine",
"name": "headbutt"
},
{
"learn_type": "machine",
"name": "thunderpunch"
},
{
"learn_type": "machine",
"name": "substitute"
},
{
"learn_type": "machine",
"name": "rest"
},
{
"learn_type": "machine",
"name": "flash"
},
{
"learn_type": "machine",
"name": "skull-bash"
},
{
"learn_type": "machine",
"name": "swift"
},
{
"learn_type": "machine",
"name": "bide"
},
{
"learn_type": "machine",
"name": "reflect"
},
{
"learn_type": "machine",
"name": "double-team"
},
{
"learn_type": "machine",
"name": "mimic"
},
{
"learn_type": "machine",
"name": "rage"
},
{
"learn_type": "machine",
"name": "toxic"
},
{
"learn_type": "machine",
"name": "thunder"
},
{
"learn_type": "level up",
"level": 1,
"name": "thunder-wave"
},
{
"learn_type": "machine",
"name": "thunderbolt"
},
{
"learn_type": "level up",
"level": 1,
"name": "thundershock"
},
{
"learn_type": "machine",
"name": "seismic-toss"
},
{
"learn_type": "machine",
"name": "submission"
},
{
"learn_type": "machine",
"name": "hyper-beam"
},
{
"learn_type": "level up",
"level": 1,
"name": "growl"
},
{
"learn_type": "machine",
"name": "double-edge"
},
{
"learn_type": "machine",
"name": "take-down"
},
{
"learn_type": "machine",
"name": "body-slam"
},
{
"learn_type": "machine",
"name": "mega-kick"
},
{
"learn_type": "machine",
"name": "pay-day"
},
{
"learn_type": "machine",
"name": "mega-punch"
}
]
}; |
let stringValue = "hello ";
let result = stringValue.concat("world");
console.log(result); // "hello world"
console.log(stringValue); // "hello"
|
/**
* Asciify
*
* ---------------------------------------------------------------
*
* Create a fancy banner
*
* For usage docs see:
* https://github.com/olizilla/grunt-asciify
*/
module.exports = function(grunt) {
grunt.config.set('asciify', {
pkg: grunt.file.readJSON('package.json'),
options: {
font: 'cyberlarge',
log: false
},
title: {
text: '<%= asciify.pkg.name %>'
}
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.