code stringlengths 2 1.05M |
|---|
const { Infrastructure, Machine, Range } = require('kelda');
const Mongo = require('./mongo.js');
const nWorker = 3;
const baseMachine = new Machine({
provider: 'Amazon',
cpu: new Range(2),
ram: new Range(2),
});
const mongo = new Mongo(nWorker);
const infra = new Infrastructure({
masters: baseMachine,
workers: baseMachine.replicate(nWorker),
});
mongo.deploy(infra);
|
const router = require('express').Router();
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const User = require('../../db').models.user;
passport.use(
new GoogleStrategy({
clientID: '392045154125-00051vrqokg6k262rip63h549qr71mfs.apps.googleusercontent.com',
clientSecret: '-1w_cZuL1oZUhi30iAHx3Tvb',
callbackURL: '/api/auth/verify'
}, (token, refreshToken, profile, done) => {
User.findOne({
where: {googleID: profile.id}
})
.then(foundUser => {
if (!foundUser) {
return User.create({googleID: profile.id, email: profile.emails[0].value});
} else {
return foundUser;
}
})
.then(user => {
done(null, user);
})
.catch(done);
})
);
router.get('/logout', (req, res, next) => {
req.logout();
res.sendStatus(204);
});
router.get('/', passport.authenticate('google', { scope: 'email' }));
router.get('/verify', passport.authenticate('google', {
successRedirect: '/business',
failureRedirect: '/'
}));
// router.get('/', passport.authenticate('google', { scope: 'email' }));
// router.get('/verify', passport.authenticate('google', {
// successRedirect: `/${req.route.path}`,
// failureRedirect: '/failure'
// }));
module.exports = router;
|
// To end the end have the option go to an id of 0. This text will be displayed;
pGameOverMessage = 'Sorry but you have lost the game. Please rewind to try again';
pData = [
{
id: 0,
text:[
"Wow, this is funny",
"Are you there?",
"This is a test",
"I'll be back soon",
3,
"^assets/image.jpg",
"Who are you?",
],
options:[
{
text: "My name is Robert",
id:1,
},
{
text: "My name is Tessa",
id:1,
},
{
text: "My name is Eso",
id:1,
},
]
},
{
id: 1,
text:[
"Let me check...",
3,
"You win",
],
options:[
{
text: "Restart",
id:0,
},
{
text: "Quit",
id:0,
},
]
},
];
|
'use strict';
const path = require('path'),koa = require('koa'),mount=require('koa-mount');
const Pug = require('koa-pug'),staticServe = require('koa-static'),favicon=require('koa-favi'),session=require('koa-generic-session'),redisStore=require('koa-redis');
const bodyParser = require('koa-bodyparser'),log = require('./common/logger');
const config = require('./config'),errorCode=require('./errorCode'),routerScan=require('./common/routerScan'),
jutil=require('./common/jutil'),cRouter = require('./common/cRouter')();
const app = koa();
app.use(bodyParser());
// app.use(staticServe(path.join(__dirname,'assets')));
function renderErrorCode(errorObj){
if(errorObj && errorObj.errorCode && errorCode[errorObj.errorCode]){
var _tmRs = errorCode[errorObj.errorCode];
if(typeof errorCode[errorObj_rs.errorCode] === 'string' ){
errorObj.errorMessage = errorCode[errorObj.errorCode] ;
}else if(typeof errorCode[errorObj.errorCode] === 'object' ){
errorObj.errorMessage = errorCode[errorObj.errorCode].zn ;
}
return errorObj;
}else{
return errorObj;
}
}
app.use(function *(next) {
try {
yield next;
var _rs = this.body;
this.body = renderErrorCode(_rs);
} catch (e) {
this.body = renderErrorCode(e);
}
});
app.keys = [`${config.prefix}-session`];
const sessionOpt = {
key : `${config.prefix}-session`,
};
if(config.redis){
if(config.redis.ttl){
sessionOpt.ttl = config.redis.ttl;
}
sessionOpt.store = redisStore({
host : config.redis.host,
port : config.redis.port,
socket : config.redis.socket,
ttl : config.redis.ttl,
db : config.redis.db
});
}
app.use(session(sessionOpt));
//token 认证
app.use(function *(next){
if(!this.session.token){
throw {errorCode : 'sys.token.001'}
}else{
yield next;
}
});
// import pug plugin
const pug = new Pug({
viewPath: path.join(__dirname, "views"),
debug: true,
noCache: true,
pretty: false,
compileDebug: false,
basedir: path.join(__dirname, "views")
});
app.use(pug.middleware);
/**
* 添加kRender 及校验请求路径
*/
app.use(function *(next) {
try{
let orginUrl = this.originalUrl;
let mountPath = this.mountPath;
let index = orginUrl.lastIndexOf(mountPath);
var slice = orginUrl.substring(index+mountPath.length,orginUrl.length);
if(slice.length<=0){
this.pathLength = 0;
}else{
this.pathLength = slice.split('/').length - 1 ;
}
if(this.pathLength == 0){
this.pathBasic = config.prefix+'/';
}else if(this.pathLength == 1){
this.pathBasic = './'
}else if(this.pathLength >= 2){
this.pathBasic = '';
for(var i=0;i<this.pathLength-1;i++){
this.pathBasic += '../';
}
}
var _this = this;
this.kRender = function (path,obj) {
obj = obj ? obj : {};
obj['pathBasic'] = _this.pathBasic;
obj['pathLength'] = _this.pathLength;
_this.render(path,obj);
};
}catch(e){
console.error(e);
}
yield next;
});
/**
* 遍历路由 router
*/
routerScan(app);
app.use(function *(next){
this.throw(404);
});
var mountApp = koa();
mountApp.use(mount("/"+config.prefix, app));
mountApp.keys = [config.prefix];
module.exports = mountApp; |
/* eslint-disable */
// https://github.com/karma-runner/karma/issues/1597
'use strict';
const conf = require('./base.karma.conf');
conf.plugins.push(require('karma-browserstack-launcher'));
if (process.env.BROWSERSTACK_USERNAME && process.env.BROWSERSTACK_ACCESS_KEY) {
conf.browserStack = {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY,
}
} else {
try {
conf.browserStack = require('../browserstack-keys.json');
} catch (e) {
console.error('No browserstack keys found. Please set env variables BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY or set them in "browserstack-keys.json" at the root of your project.');
console.error('Alternatively, use `npm run test` to test locally.');
process.exit(1);
}
}
conf.customLaunchers = {
bsMacFirefox14: {
base: 'BrowserStack',
browser: 'firefox',
browser_version: '33.0',
os: 'OS X',
os_version: 'El Capitan',
},
bsMacChrome38: {
base: 'BrowserStack',
browser: 'chrome',
browser_version: '38.0',
os: 'OS X',
os_version: 'El Capitan',
},
bsMacSafari6: {
base: 'BrowserStack',
browser: 'safari',
browser_version: '6.2',
os: 'OS X',
os_version: 'Mountain Lion',
},
bsMacOpera20: {
base: 'BrowserStack',
browser: 'opera',
browser_version: '20.0',
os: 'OS X',
os_version: 'El Capitan',
},
bsWinEdge13: {
base: 'BrowserStack',
browser: 'edge',
browser_version: '13',
os: 'WINDOWS',
os_version: '10',
},
bsWinIe11: {
base: 'BrowserStack',
browser: 'ie',
browser_version: '11',
os: 'WINDOWS',
os_version: '7',
},
};
conf.browsers = ['bsMacFirefox14', 'bsMacChrome38', 'bsMacSafari6', 'bsMacOpera20', 'bsWinEdge13', 'bsWinIe11'];
module.exports = function configureKarma(config) {
config.set(conf);
};
|
/* eslint-disable */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import Queue from 'promise-queue';
import ReactDOM from 'react-dom';
import { marked } from 'marked';
import { loadYamlFile, saveYamlFile } from '../reducers/index';
import { SplitButton, MenuItem, Button, ButtonToolbar, Glyphicon, DropdownButton, Collapse} from 'react-bootstrap';
import { sendAsFile, sendAsImage, getAsImage } from '../lib/helpers'
import slug from 'slug';
import jsPDF from 'jspdf';
import '../assets/fonts/din-cond/style.css';
import { resolve } from 'path';
import sortBy from 'sort-by'
import { range } from 'rxjs';
const PAGE_WIDTH=10.55;
const PAGE_HEIGHT=7.55;
const MARGIN_X=0.3;
const MARGIN_Y=0.3;
const CARD_WIDTH=5;
const CARD_HEIGHT=3.5;
const CARD_OFFSETX=0;
const CARD_OFFSETY=-0.03
export class FileField extends React.Component {
constructor(props) {
super(props);
this._domclick = function (ce) {
ce.preventDefault();
let modifiers = { ctrl: ce.ctrlKey, shift: ce.shiftKey, meta: ce.metaKey };
if (this.input.__changeHandler) this.input.removeEventListener('change', this.input.__changeHandler)
this.input.value = "";
this.input.__changeHandler = (e) => {
e.preventDefault();
this.props.onChange(e, modifiers)
}
this.input.addEventListener('change', this.input.__changeHandler)
this.input.click();
}.bind(this)
}
componentDidMount() {
this.clicker.addEventListener('click', this._domclick)
}
componentWillUnMount() {
this.clicker.removeEventListener('click', this._domclick)
}
render() {
return <span style={this.props.style} >
<span ref={(input) => this.clicker = input}>{this.props.children}</span><input type="file" ref={(input) => { this.input = input }} multiple style={{ display: "none" }} accept={this.props.accept} />
</span>
}
}
export const loadCharacter = (e, action) => {
let self = this
let files = e.target.files;
if (!window.characterLoader)
window.characterLoader = new Queue(1, Infinity)
for (let file of files) {
window.characterLoader.add(loadYamlFile(file)).then((data) => {
data.forEach((obj, i) => {
action(obj, i)
}, this);
}).catch(console.error)
}
}
export const downloadCharacters=(characters)=>{
sendAsFile("7TV_cast.yaml",saveYamlFile(characters,true),'application/x-yaml')
}
export const downloadSingleCharacter=(character)=>{
sendAsFile("7TV_cast-"+slug(character.name||character.id)+".yaml",saveYamlFile(character,false),'application/x-yaml');
}
export const downloadCharactersAsImages=(cast)=>{
cast.forEach(item=>{
sendAsImage(item.id,"7TV_cast-"+slug(item.name||item.id)+".png");
})
}
const dottedLine=function(doc, xFrom, yFrom, xTo, yTo, segmentLength)
{
// Calculate line length (c)
var a = Math.abs(xTo - xFrom);
var b = Math.abs(yTo - yFrom);
var c = Math.sqrt(Math.pow(a,2) + Math.pow(b,2));
// Make sure we have an odd number of line segments (drawn or blank)
// to fit it nicely
var fractions = c / segmentLength;
var adjustedSegmentLength = (Math.floor(fractions) % 2 === 0) ? (c / Math.ceil(fractions)) : (c / Math.floor(fractions));
// Calculate x, y deltas per segment
var deltaX = adjustedSegmentLength * (a / c);
var deltaY = adjustedSegmentLength * (b / c);
var curX = xFrom, curY = yFrom;
while (curX <= xTo && curY <= yTo)
{
doc.line(curX, curY, curX + deltaX, curY + deltaY);
curX += 2*deltaX;
curY += 2*deltaY;
}
}
const getImageDimensions= (file) => {
return new Promise (function (resolved, rejected) {
var i = new Image()
i.onload = function(){
resolved({w: i.width, h: i.height})
};
i.src = file
})
}
export const downloadCharactersAsPDF=(cast,fileName='7TVcast',status=console.warn)=>{
let doc = new jsPDF({orientation: 'landscape',format:[PAGE_WIDTH,PAGE_HEIGHT],unit:'in'});
var i=0;
let promises=cast.sort(sortBy('__card')).map((item)=>{
return new Promise((rs,rj)=>{
getAsImage(document.getElementById(item.id)).then((img)=>{
status("Processing image "+(++i)+"/"+cast.length);
rs({dataURL: img,type:item.__card.replace(/.*_(.*)$/,'$1')})
}).catch(console.log);
})});
Promise.all(promises).then((items)=>{
chunk(items,0,(i,p)=>{return i.type!==p.type;}).forEach((c,cn)=>{
let positions = cardGrid(c[0].type);
chunk(c,positions.length).forEach((itemsperpage,page)=>{
status("Generating page "+(page+1))
if (cn||page) doc.addPage();
itemsperpage.forEach((item,j)=>{
let {dataURL,type} = item;
let [fw,fh] = cardFactor(type);
doc.addImage(dataURL,'JPEG',positions[j].x,positions[j].y,CARD_WIDTH*fw,CARD_HEIGHT*fh)
})
cardCuts(c[0].type,doc)
});
});
doc.save(fileName+'.pdf')
status(null)
})
}
const chunk = (r,j,fn=(i)=>{return false;}) => r.reduce((a,b,i,g) => {
if (!i || j&&(!(a[a.length-1].length % j)) || (fn(b,g[!i?i:i-1]))) a.push([])
a[a.length-1].push(g[i])
return a;
}, []);
const cardGrid=function(type){
let [fw,fh] = cardFactor(type);
switch(type){
case 'small':
return Array.from(Array(8).keys()).map((v)=>({x:(v%2)*CARD_WIDTH*fw+MARGIN_X, y: Math.floor(v/2)*CARD_HEIGHT*fh+MARGIN_Y}));
break;
case 'large':
return Array.from(Array(2).keys()).map((v)=>({x:(v%2)*CARD_WIDTH*fw+MARGIN_X, y: Math.floor(v/2)*CARD_HEIGHT*fh+MARGIN_Y}));
break;
default:
return Array.from(Array(4).keys()).map((v)=>({x:(v%2)*CARD_WIDTH*fw+MARGIN_X, y: Math.floor(v/2)*CARD_HEIGHT*fh+MARGIN_Y}));
break;
}
}
const cardCuts=function(type,doc){
doc.setLineWidth(0.01)
doc.setDrawColor(255,255,255);
switch(type){
case 'large':
dottedLine(doc,0,MARGIN_Y+CARD_HEIGHT+CARD_OFFSETY,PAGE_WIDTH,MARGIN_Y+CARD_HEIGHT+CARD_OFFSETY,0.01)
break;
default:
dottedLine(doc,MARGIN_X+CARD_WIDTH/2,0,MARGIN_X+CARD_WIDTH/2,PAGE_HEIGHT,0.05)
dottedLine(doc,MARGIN_X+CARD_WIDTH,0,MARGIN_X+CARD_WIDTH,PAGE_HEIGHT,0.01)
dottedLine(doc,MARGIN_X+CARD_WIDTH/2*3,0,MARGIN_X+CARD_WIDTH/2*3,PAGE_HEIGHT,0.05)
dottedLine(doc,0,MARGIN_Y+CARD_HEIGHT+CARD_OFFSETY,PAGE_WIDTH,MARGIN_Y+CARD_HEIGHT+CARD_OFFSETY,0.01)
break;
}
}
const cardFactor=function(type){
switch(type){
case 'small': return [1,0.5]; break;
case 'large': return [1,2]; break;
default: return [1,1];
}
}
export const Marked = ({md="", Component="span", Options={},...rest})=>{
let __html=marked(md,Options);
if (Options.inline) __html=__html.replace(/^<p>/gi,'').replace(/<\/p>[\r\n]*$/gi,'').replace(/[\r\n]/gi,'')
return <Component {...{...rest}} dangerouslySetInnerHTML={{__html}}/>
}
export class Toolbar extends React.Component {
constructor(...args) {
super(...args);
this.state = {
status: null,
};
}
status(status){
this.setState({status: status? "("+status+")":''});
this.forceUpdate();
}
render(){
return <div className="ui paper editorToolBar">
<h2 className="din" style={{textAlign:"center", marginBottom:0}}>7TV Studios</h2>
<h5 className="din" style={{textAlign:"center", marginTop:0}}> casting agency</h5>
<div style={{margin:5}}>
<DropdownButton bsStyle="primary" bsSize="small" title="New" id="new_model" >
<MenuItem eventKey="1" onClick={e=>this.props.dispatch({ type: 'CHARACTER_NEW' })}>Character</MenuItem>
<MenuItem eventKey="2" onClick={e=>this.props.dispatch({ type: 'CHARACTER_NEW', payload:{ __card:'vehicle'} })}>Vehicle</MenuItem>
<MenuItem eventKey="3" onClick={e=>this.props.dispatch({ type: 'CHARACTER_NEW', payload:{ __card:'vehicle_large'} })}>Extended Vehicle</MenuItem>
<MenuItem eventKey="4" onClick={e=>this.props.dispatch({ type: 'CHARACTER_NEW', payload:{ __card:'unit'} })}>Unit</MenuItem>
<hr/>
<MenuItem eventKey="5" onClick={e=>this.props.dispatch({ type: 'CHARACTER_NEW', payload:{ __card:'gadget_small'} })}>Gadget</MenuItem>
</DropdownButton>
<FileField style={{display:"block",margin: "5px 0 5px 0"}} accept=".yaml" onChange={e => loadCharacter(e, (file) => this.props.dispatch({ type: 'CHARACTER_LOAD', payload: file }))}><Button block bsSize="small" bsStyle="success"><Glyphicon glyph="upload" /> Load .Yaml</Button></FileField>
<Button block bsSize="small" onClick={e=>downloadCharacters(this.props.cast)} bsStyle="warning"><Glyphicon glyph="download" /> Download as .Yaml</Button>
<Button block bsSize="small" onClick={e=>downloadCharactersAsImages(this.props.cast)} bsStyle="danger"><Glyphicon glyph="download" /> Download as Single Images</Button>
<Button block bsSize="small" onClick={e=>downloadCharactersAsPDF(this.props.cast, null,this.status.bind(this))} bsStyle="danger"><Glyphicon glyph="download" /> Download as PDF {this.state.status}</Button>
<Button block bsSize="small" onClick={e=> {if (confirm('Are you sure? This will wipe all the current cards! It is a bloody nuke!')) this.props.dispatch({type: 'CAST_CLEAR'});}} bsStyle="info"><Glyphicon glyph="trash" /> Reset all</Button>
</div>
</div>
}
}
Toolbar = connect(
(state)=>{return {cast: state.cast}}
)(Toolbar);
export class Help extends React.Component {
constructor(...args) {
super(...args);
this.state = {
open: false,
};
}
render(){
return <div className="ui paper" style={{margin:5}} >
<Button block bsSize="small" onClick={() => this.setState({ open: !this.state.open })} bsStyle="default">Help</Button>
<Collapse in={this.state.open}><div className="help" dangerouslySetInnerHTML={{__html:marked(require("!raw-loader!../HELP.md"))}} ></div></Collapse>
</div>
}
}
const downloadSnapshot=function(state)
{
let d=new Date();
sendAsFile("7TV-debug-"+d+".json",JSON.stringify(state),'application/json');
}
export class Rescue extends React.Component {
render(){
return <div className="ui paper"> <DropdownButton bsStyle="primary" bsSize="xsmall" title="Debug" id="new_model" dropup >
<MenuItem eventKey="1" onClick={e=>downloadSnapshot(this.props.state)}>Download data snapshot</MenuItem>
</DropdownButton></div>
}
}
Rescue = connect((state)=>({state}))(Rescue); |
/**
* Scope abstraction is a colletor when compiler child template with scope
*/
'use strict';
var util = require('./util')
function Scope (data, parent) {
this.$data = data
this.$directives = []
this.$components = []
this.$watchers = []
this.$parent = parent || null
}
Scope.prototype.$update = function () {
var args = arguments
util.forEach(this.$watchers, function (w) {
w.$update.apply(w, args)
})
util.forEach(this.$directives, function (d) {
d.$update.apply(d, args)
})
util.forEach(this.$components, function (child) {
child.$update.apply(child, args)
})
}
Scope.prototype.$removeChild = function (scope) {
var i = util.indexOf(this.$components, scope)
if (~i) {
scope.$parent = null
this.$components.splice(i, 1)
}
return this
}
Scope.prototype.$addChild = function (scope) {
if (!~util.indexOf(this.$components, scope)) this.$components.push(scope)
return this
}
Scope.prototype.$destroy = function () {
/**
* Release ref from parent scope
*/
this.$parent && this.$parent.$removeChild(this)
/**
* destroy binded watchers
*/
scope.$watchers.forEach(function (w) {
w.$destroy()
})
/**
* destroy binded directives
*/
scope.$directives.forEach(function (d) {
d.$destroy()
})
/**
* destroy children scopes
*/
scope.$components.forEach(function (c) {
c.$destroy()
})
return this
}
module.exports = Scope |
"use strict";
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
var shader_compiler_1 = require("./shader_compiler");
var ReverseProgram = /** @class */ (function () {
function ReverseProgram(xShape, axis) {
this.variableNames = ['x'];
var rank = xShape.length;
if (rank > 4) {
throw new Error("WebGL backend: Reverse of rank-" + rank + " tensor is not yet supported");
}
this.outputShape = xShape;
if (rank === 1) {
this.userCode = "\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(" + xShape[0] + " - coord - 1));\n }\n ";
return;
}
var getInCoord = function (i) {
if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
return xShape[i] + " - coords[" + i + "] - 1";
}
return "coords[" + i + "]";
};
var inCoords = xShape.map(function (_, i) { return getInCoord(i); }).join(',');
var type = shader_compiler_1.getCoordsDataType(rank);
this.userCode = "\n void main() {\n " + type + " coords = getOutputCoords();\n setOutput(getX(" + inCoords + "));\n }\n ";
}
return ReverseProgram;
}());
exports.ReverseProgram = ReverseProgram;
//# sourceMappingURL=reverse_gpu.js.map |
var app = null;
var skillSet = [];
Ext.define('TaskEstimates', {
extend: 'Rally.app.TimeboxScopedApp',
scopeType: 'iteration',
componentCls: 'app',
onScopeChange: function(scope) {
console.log("IN scope change");
app = this;
skillSet = [{name:'.net', sum: 0}, {name: 'test', sum: 0}, {name:'ontwerp', sum:0}, {name: 'meetingpoint', sum: 0}];
var qFilter = app.buildTagFilter(skillSet);
console.log("Final filter: ", qFilter.toString());
var iterationStore = Ext.create('Rally.data.wsapi.Store', {
model: 'Task',
fetch: ['Name', 'Tags', 'Estimate'],
filters: qFilter,
autoLoad: true,
listeners: {
load: function(store, records) {
_.each(records, function(record){
var tagName = record.data.Tags._tagsNameArray[0].Name;
var estimate = record.data.Estimate;
estimate = estimate === null ? 0 : estimate;
_.each(skillSet, function(skill){
console.log(tagName, ":", skill.name);
if (skill.name == tagName) {
skill.sum = skill.sum + estimate;
}
});
});
app.addCustomGrid();
}
}
});
},
buildTagFilter: function(skillSet) {
var iterationFilter = app.getContext().getTimeboxScope().getQueryFilter();
var tagFilter = Ext.create('Rally.data.wsapi.Filter', {
property: 'Name',
operator: '=',
value: 'Name'
});
console.log("Skills: ", skillSet);
_.each(skillSet, function (skill){
console.log("skill", skill);
tagFilter = tagFilter.or(Ext.create('Rally.data.wsapi.Filter', {
property: 'tags.Name',
operator: '=',
value: skill['name']
}));
});
console.log("filter: ", tagFilter.toString());
return iterationFilter.and(tagFilter);
},
addCustomGrid: function() {
var grid = this.down("rallygrid");
if (grid) {
grid.destroy();
}
app.add({
xtype: 'rallygrid',
showPagingToolbar: false,
showRowActionsColumn: false,
editable: false,
store: Ext.create('Rally.data.custom.Store', {
data: skillSet
}),
columnCfgs: [
{
text: 'Name',
dataIndex: 'name',
flex: 1
},
{
text: 'Total Estimate',
dataIndex: 'sum'
}
]
});
}
});
|
'use strict'
var inherits = require('inherits')
var EventEmitter = require('node-event-emitter')
var sax = require('sax')
var SaxSaxjs = module.exports = function SaxSaxjs () {
EventEmitter.call(this)
this.parser = sax.parser(true)
var that = this
this.parser.onopentag = function (a) {
that.emit('startElement', a.name, a.attributes)
}
this.parser.onclosetag = function (name) {
that.emit('endElement', name)
}
this.parser.ontext = function (str) {
that.emit('text', str)
}
this.parser.onend = function () {
that.emit('end')
}
this.parser.onerror = function (e) {
that.emit('error', e)
}
}
inherits(SaxSaxjs, EventEmitter)
SaxSaxjs.prototype.write = function (data) {
if (typeof data !== 'string') {
data = data.toString()
}
this.parser.write(data)
}
SaxSaxjs.prototype.end = function (data) {
if (data) {
this.parser.write(data)
}
this.parser.close()
}
|
'use strict';
var Events = require('../../events/Events');
var State = require('../../state/State');
var THREE = require('three');
var initialized = false;
function SeparationAndSeek (obj, dimensions, godToFollow, separation, vehicles) {
this.godToFollow = godToFollow;
this.obj = obj;
this.dimensions = dimensions;
this.vehicles = vehicles;
this.secureDistanceToGod = 0.2;
this.status = 'asleep';
this.maxSpeed = 0.007;
this.maxForce = 0.0004;
this.acceleration = new THREE.Vector3();
this.velocity = new THREE.Vector3();
this.separateFactor = 8;
this.seekFactor = 6;
this.desiredSeparation = separation;
Events.on('raceStatusChanged', this.raceStatusChanged.bind(this));
Events.on('updateScene', this.update.bind(this));
}
SeparationAndSeek.prototype.raceStatusChanged = function (race, status) {
if (this.godToFollow.race === race) {
this.status = status;
}
};
// INIT CODE BASED ON: natureofcode.com/book/chapter-6-autonomous-agents/
SeparationAndSeek.prototype.applyBehaviours = function (vehicles) {
var separateForce = this.separate(vehicles);
var absPos = new THREE.Vector3().setFromMatrixPosition(this.godToFollow.matrixWorld);
var posY = 0;
if (this.dimensions === 3) {
posY = absPos.y;
}
var godPosition = new THREE.Vector3(absPos.x, posY, absPos.z);
var seekForce = this.seek(godPosition);
separateForce.multiplyScalar(this.separateFactor);
seekForce.multiplyScalar(this.seekFactor);
this.applyForce(separateForce);
this.applyForce(seekForce);
};
SeparationAndSeek.prototype.applyForce = function (force) {
this.acceleration.add(force);
};
SeparationAndSeek.prototype.separate = function (vehicles) {
var sum = new THREE.Vector3();
var count = 0;
// For every boid in the system, check if it's too close
for ( var i = 0; i < vehicles.length; i++) {
var posY = 0;
// TODO fix this because is custom for MiniFlyers
var absPos = this.obj.position;
if (this.dimensions === 3) {
posY = absPos.y;
}
var myPos3D = new THREE.Vector3(absPos.x, posY, absPos.z);
var posVehicleY = 0;
if (this.dimensions === 3) {
posVehicleY = vehicles[ i ].position.y;
}
var vehiclePos3D = new THREE.Vector3(vehicles[ i ].position.x, posVehicleY, vehicles[ i ].position.z);
var d = myPos3D.distanceTo(vehiclePos3D);
// If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
// console.log(this.obj, vehicles[ i ]);
if ((d > 0) && (d < this.desiredSeparation)) {
// Calculate vector pointing away from neighbor
var diff = new THREE.Vector3();
diff = diff.subVectors(myPos3D, vehiclePos3D);
diff.normalize();
diff.divideScalar(d); // Weight by distance
sum.add(diff);
count++; // Keep track of how many
}
}
// Average -- divide by how many
if (count > 0) {
sum.divideScalar(count);
// Our desired vector is the average scaled to maximum speed
sum.normalize();
sum.multiplyScalar(this.maxSpeed);
// Implement Reynolds: Steering = Desired - Velocity
sum.sub(this.velocity);
sum.setLength(this.maxForce);
}
return sum;
};
SeparationAndSeek.prototype.seek = function (godPosition) {
var desired = new THREE.Vector3();
var posY = 0;
var absPos = new THREE.Vector3().setFromMatrixPosition(this.obj.matrixWorld);
if (this.dimensions === 3) {
posY = absPos.y;
}
var myPos3D = new THREE.Vector3(absPos.x, posY, absPos.z);
desired = desired.subVectors(godPosition, myPos3D); // A vector pointing from the location to the target
if (desired.length() < this.secureDistanceToGod) {
desired.setLength(- 1);
} else {
// Normalize desired and scale to maximum speed
desired.setLength(this.maxSpeed);
}
// desired.setLength(this.maxSpeed);
// Steering = Desired minus velocity
var steer = new THREE.Vector3();
steer = steer.subVectors(desired, this.velocity);
steer.setLength(this.maxForce); // Limit to maximum steering force
return steer;
};
// Method to update location
SeparationAndSeek.prototype.update = function (timestamp) {
if (this.status === 'asleep') {
return;
}
if (!this.godToFollow) {
return;
}
this.applyBehaviours(this.vehicles);
// Update velocity
this.velocity.add(this.acceleration);
// Limit speed
this.velocity.setLength(this.maxSpeed);
var velY = 0;
if (this.dimensions === 3) {
velY = this.velocity.y;
}
var vel3D = new THREE.Vector3(this.velocity.x, velY, this.velocity.z);
this.obj.position.add(vel3D);
// Reset acceleration to 0 each cycle
this.acceleration.multiplyScalar(0);
// this.moodManager.update( timestamp );
};
// END CODE BASED ON: natureofcode.com/book/chapter-6-autonomous-agents/
module.exports = SeparationAndSeek;
|
module.exports = function(app){
var dummy = require("../../controllers/dummy");
app.get('/dummy', dummy.dummyValue);
} |
(function() {
angular
.module("bookmapEvent")
.directive("eventFilter", EventFilterDirective);
function EventFilterDirective() {
controller.$inject = ["$scope"];
function controller($scope) {
var self = this;
self.isVisible = false;
self.toggle = toggle;
self.filter = filter;
self.needle = "";
/*
* @todo Wait for three letters at least.
*/
function filter($event) {
if ($event.keyCode === 27) { // hide with escape
self.toggle();
return;
}
for (var e in self.events._layers) {
self.events._layers[e].filter(self.needle, self.map); // hack
}
}
function toggle() {
self.isVisible = !self.isVisible;
}
}
return {
restrict: "E",
templateUrl: "client/app/components/event/map/event.filter.directive.html",
controller: controller,
controllerAs: "vm",
bindToController: {
events: "=",
map: "="
},
scope: {}
};
}
})();
|
const logostyle = document.getElementById('logoscript')
let debuff = false
const mouseMove = (e) => {
if (!debuff) {
requestAnimationFrame( () => {
const x = (e.clientX / window.innerWidth * 2 - 1) / 15
const y = (e.clientY / window.innerHeight * 2 - 1) / 15
logoparallax(x, y)
})
debuff = true
}
}
const handleOrientation = (e) => {
if (!debuff) {
requestAnimationFrame( () => {
const y = e.beta / 1200
const x = e.gamma / 1200
logoparallax(x, y)
})
debuff = true
}
}
const logoparallax = (x, y) => {
logostyle.innerHTML = '#logo span{transform:translate('+ x + 'rem,' + y + 'rem)}'
debuff = false
}
window.addEventListener('mousemove', mouseMove, true)
window.addEventListener('deviceorientation', handleOrientation, true) |
Admin.Modules.register('display.table', () => {
//use LazyLoad
lazyload()
//nit: Daan
// Все что ниже было отключено, но для работы ленивой загрузке нужно вызвать этот модуль
// $('.display-filters[data-display="DisplayTable"]').each((i, el) => {
// let $self = $(el),
// $filtersRow = $self.find('tr').first(),
// tag = $self[0].tagName,
// $filters = $filtersRow.find('td'),
// $button = $('<button class="btn btn-default">' + trans('lang.table.filters.control') + '</button>')
//
// $filtersRow.after(
// $(`<tr><td colspan="${$filters.length}" class="text-right"></td></tr>`).append($button)
// )
//
// $button.on('click', () => {
// let query = {columns: []}
//
// $filters.each((i, td) => {
// let $filter = $(td).find('.column-filter'),
// val = null
//
// switch ($filter.data('type')) {
// case 'range':
//
// break
//
// case 'text':
// case 'select':
// val = $filter.val()
//
// break
// }
//
// if (!_.isNull(val) && val.length > 0) {
// query['columns'][i] = {
// search: {
// value: val
// }
// }
// }
// })
//
// Admin.Url.query(query)
// })
// })
})
|
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const sliderDB = require('../../model/slider');
router.post('/delete', function (req, res) {
let id = req.body._id;
sliderDB.deleteById(id).then((img) => {
if (img === -1) return res.json({ errno: -1 });
let pathName = path.join(__dirname, '../../../', '/store/images/', img);
fs.unlink(pathName, (err) => {
if (err) return res.json({ errno: -1 });
res.json({ errno: 0 });
});
}); 22
});
router.post('/post', function (req, res) {
let data = req.body;
if (data._id === -1) {
sliderDB.insert(data).then((id) => {
if (id === -1) {
res.json({ errno: 1 });
} else {
res.json({ errno: 0, data: { _id: id } });
}
});
} else {
sliderDB.update(data).then((oldImg) => {
if (oldImg === -1) return res.json({ errno: -1 });
if (oldImg === '') {
return res.json({ errno: 0 });
}
let pathName = path.join(__dirname, '../../../', '/store/images/', oldImg);
fs.unlink(pathName, (err) => {
if (err) return res.json({ errno: -1 });
res.json({ errno: 0 });
});
});
}
});
module.exports = router; |
function Structure() {}
//------------------------------------------------------------------------------------------------------
// AES S-BOX
//------------------------------------------------------------------------------------------------------
Structure.sbox =
[
[ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76 ],
[ 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0 ],
[ 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15 ],
[ 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75 ],
[ 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84 ],
[ 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF ],
[ 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8 ],
[ 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2 ],
[ 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73 ],
[ 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB ],
[ 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79 ],
[ 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08 ],
[ 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A ],
[ 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E ],
[ 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF ],
[ 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 ]
];
//------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
// AES INVERSE S-BOX
//------------------------------------------------------------------------------------------------------
Structure.inverseSbox =
[
[ 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB ],
[ 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB ],
[ 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E ],
[ 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25 ],
[ 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92 ],
[ 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84 ],
[ 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06 ],
[ 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B ],
[ 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73 ],
[ 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E ],
[ 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B ],
[ 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4 ],
[ 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F ],
[ 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF ],
[ 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61 ],
[ 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D ]
];
//-----------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// ROUND COEFFICIENTS
//-------------------------------------------------------------------------------------------------
Structure.rcon =
[
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d
];
//-------------------------------------------------------------------------------------------------
//Mix column matrix used in MixColumns layer
Structure.mixColMatrix =
[
[ 0x02, 0x03, 0x01, 0x01 ],
[ 0x01, 0x02, 0x03, 0x01 ],
[ 0x01, 0x01, 0x02, 0x03 ],
[ 0x03, 0x01, 0x01, 0x02 ]
];
//Inverse mix columns matrix used in InverseMixColumns layer
//Values are the inverse in GF(2^8) of those in mixColMatrix
Structure.inverseMixColMatrix =
[
[ 0x0e, 0x0b, 0x0d, 0x09 ],
[ 0x09, 0x0e, 0x0b, 0x0d ],
[ 0x0d, 0x09, 0x0e, 0x0b ],
[ 0x0b, 0x0d, 0x09, 0x0e ]
];
//Returns the round coefficient at index
Structure.getRconEntry = function(index)
{
var rc = Structure.convert(this.rcon[index].toString(16), 16, 2);
return rc;
};
//Returns the mix column entry a[row][column]
//returns the inverse value if Mode::DECRYPT
Structure.getMixColEntry = function(row, col, encrypt_mode)
{
var value;
if(encrypt_mode)
value = Structure.mixColMatrix[row][col].toString(16);
else
value = Structure.inverseMixColMatrix[row][col].toString(16);
return Structure.convert(value, 16, 2);
};
//Returns the s-box entry a[row][column]
//returns the inverse value if Mode::DECRYPT
Structure.getSboxEntry = function(row, column, encrypt_mode)
{
var value;
if(encrypt_mode)
value = Structure.sbox[row][column].toString(16);
else
value = Structure.inverseSbox[row][column].toString(16);
return Structure.convert(value, 16, 2);
};
//Returns the sbox entry for the bin
//row and column of s-box table are derived from bin
//left-most bits = row, right-most bits = column
Structure.getSboxEntryFromBin = function(bin, encrypt_mode)
{
bin = Structure.padBin(bin);
var row = Structure.convert(bin.substring(0, 4), 2, 10);
var col = Structure.convert(bin.substring(4, 8), 2, 10);
return Structure.getSboxEntry(row, col, encrypt_mode);
};
//pads a binary string up to 8bits
Structure.padBin = function(bin)
{
if(bin.length >= 8) return bin;
var b = '00000000';
return b.substring(0, b.length - bin.length) + bin;
};
//pads a hex string up 00
Structure.padHex = function(hex)
{
if(hex.length >= 2) return hex;
var h = '00';
return h.substring(0, h.length - hex.length) + hex;
};
//Converts the value from base 'from' to base 'to'
Structure.convert = function(value, from, to)
{
if(from == 2) value = Structure.padBin(value);
var parsed = parseInt(value, from).toString(to);
if(to == 2)
return Structure.padBin(parsed);
else
return parsed;
};
//Prints out the 4 bytes in row
Structure.printStateRow = function(state, rowNumber)
{
var colStr = '';
for(var col = 0; col < 4; col++)
colStr += state[rowNumber][col] + ' ';
console.log(colStr + '\n');
};
//Prints out the state 4x4 matrix
Structure.printState = function(state)
{
for(var row = 0; row < 4; row++)
{
var colStr = '';
for(var col = 0; col < 4; col++)
colStr += state[row][col] + ' ';
console.log(colStr + '\n');
}
};
//Returns the string contained in the state(s)
Structure.statesToString = function(states)
{
var numStates = states.length;
var message = "";
for(var i = 0; i < numStates; i++)
message += Structure.stateToString(states[i]);
return message;
};
//Prints out the string represented by the states
//numStates: size(states)
Structure.printDecryptedMessage = function(states)
{
var numStates = states.length;
var message = "";
for(var i = 0; i < numStates; i++)
message += Structure.stateToString(states[i]);
return message;
};
//Creates the skeleton for the state
Structure.createState = function()
{
var state = [];
for(var i = 0; i < 4; i++)
state.push([]);
return state;
};
//Adds the bytes in str into the passed state
Structure.makeState = function(str)
{
var state = Structure.createState();
var index = 0;
for(var row = 0; row < 4; row++)
for(var col = 0; col < 4; col++)
state[col][row] = str[index++];
return state;
};
//Creates and returns a randomly generated state
//Useful for generation of keys/IV's
Structure.generateState = function()
{
var state = Structure.createState();
var dec, next;
for(var row = 0; row < 4; row++)
{
for(var col = 0; col < 4; col++)
{
dec = Math.floor(Math.random() * 256);
next = String.fromCharCode(dec).toString(2);
state[col][row] = next;
}
}
return state;
};
//Copies the state b into a
Structure.copyState = function(stateA, stateB)
{
for(var row = 0; row < 4; row++)
for(var col = 0; col < 4; col++)
stateA[row][col] = stateB[row][col];
};
//puts the character bytes in the str into a state
//values are converted into binary
Structure.strToState = function(str)
{
var bytes = [];
for(var i = 0; i < 16; i++)
{
if(str.length <= i)
bytes.push(Structure.padBin(""));
else
bytes.push(Structure.padBin(str.charCodeAt(i).toString(2)));
}
return Structure.makeState(bytes);
};
//Returns a hex representation of the state
Structure.stateToHex = function(state)
{
Structure.printState(state);
var str = "";
for(var row = 0; row < 4; row++)
{
for(var col = 0; col < 4; col++)
{
var hex = Structure.padHex(Structure.convert(state[col][row], 2, 16));
if(hex != '00')
str += hex;
}
}
return str;
};
//puts the hex into a state
//values sare converted into binary
Structure.hexToState = function(hex)
{
if(hex.length != 32) return;
var bytes = [];
var index = 0;
var hIndex = 0;
while(index < 16)
{
bytes.push(Structure.convert(hex.substring(hIndex, hIndex + 2), 16, 2));
hIndex += 2;
index++;
}
return Structure.makeState(bytes);
};
//Returns the string value of the state
Structure.stateToString = function(state)
{
var str = "";
for(var row = 0; row < 4; row++)
{
for(var col = 0; col < 4; col++)
{
var hex = Structure.padHex(Structure.convert(state[col][row], 2, 16));
if(hex != '00')
str += String.fromCharCode(parseInt(hex, 16));
}
}
return str;
};
//returns the number of states (blocks) needed for the text
Structure.getNumStates = function(str)
{
return Math.ceil(str.length / 16);
};
//performs a bitwise XOR: a XOR b
Structure.xor = function(a, b)
{
a = parseInt(a, 2);
b = parseInt(b, 2);
return Structure.padBin((a ^ b).toString(2));
};
//Performs matrix/state addition in GF(2^8)
//Each entry is xor'd with the corresponding entry
Structure.addStates = function(stateA, stateB)
{
for(var row = 0; row < 4; row++)
for(var col = 0; col < 4; col++)
stateA[col][row] = Structure.xor(stateA[col][row], stateB[col][row]);
};
//bitwise left shifts a by b
Structure.shiftLeft = function(a, b)
{
a = parseInt(a, 2);
return Structure.padBin((a << b).toString(2)).slice(-8);
};
//bitwise right shifts a by b
Structure.shiftRight = function(a, b)
{
a = parseInt(a, 2);
return Structure.padBin((a >> b).toString(2)).slice(-8);
};
//returns the column at colNum in the matrix
Structure.getColumn = function(state, column)
{
var col = [];
col.push(state[0][column]);
col.push(state[1][column]);
col.push(state[2][column]);
col.push(state[3][column]);
return col;
};
//Creates states from the string
Structure.makeStates = function(str)
{
var len = str.length;
var strIndex = 0;
var numStates = Structure.getNumStates(str);
var states = [[[]]];
for(var sIndex = 0; sIndex < numStates; sIndex++)
{
var nextState;
var nextStr;
if(strIndex + 16 > len)
nextStr = str.substring(strIndex, len);
else
nextStr = str.substring(strIndex, strIndex + 16);
strIndex += 16;
nextState = Structure.strToState(nextStr);
states[sIndex] = nextState;
}
return states;
};
|
// retorna um id único
function generateId() {
generateId._lastId = generateId._lastId || new Date() * 1;
generateId._lastId += 1;
return generateId._lastId;
}
(function() {
$.fn.uniacLoadSelect = function(options) {
var $this = $(this);
var url = options.url,
valueField = options.valueField,
textField = options.textField,
groupField = options.groupField,
dataAjax = options.data,
ajaxDone = options.done,
selected = options.selected,
placeholder = options.placeholder || '';
var done = function(data) {
$this.html('<option value="">' + placeholder + '</option>');
var groups = {};
$.each(data, function(index, item) {
var $option = $('<option />').val(item[valueField]).text(item[textField]);
if (groupField) {
var $group = groups[item[groupField]];
if (!$group) {
$group = $('<optgroup />').attr('label', item[groupField])
groups[item[groupField]] = $group;
$this.append($group);
}
$group.append($option);
}
else
$this.append($option);
});
if (selected)
$this.val(selected);
if ($.isFunction(ajaxDone))
ajaxDone(data);
}
var fail = function() {
$this.html('');
}
$.ajax({
url: url,
method: 'GET',
cache: false,
dataType: 'json',
data: dataAjax
})
.done(done)
.fail(fail);
}
var uniac_fileupload_default_options = {};
// Adiciona ao jquery a inicialização do componente de
// upload de arquivos com a configuração padrão do UNIAC
// de tamanho, tipo e quantidade de arquivos aceitos
$.fn.uniacFileupload = function(options) {
var upload = this;
var fileuploadOptions = $.extend({}, uniac_fileupload_default_options, options);
upload.fileupload(fileuploadOptions);
// Load existing files:
upload.addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: upload.fileupload('option', 'url'),
dataType: 'json',
context: upload[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
};
// Define a configuração padrão de tamanho, tipo
// e quantidade de arquivos aceitos para upload
$.uniacFileuploadDefaultOptions = function(maxFileSize, acceptFileTypes, maxNumberOfFiles) {
var acceptFileTypesRegEx = acceptFileTypes.join('|'),
acceptFileTypesMessage = acceptFileTypes.join(', '),
maxFileSizeBytes = maxFileSize * 1024;
uniac_fileupload_default_options = {
autoUpload : true,
maxFileSize: maxFileSizeBytes,
acceptFileTypes: new RegExp('(\\.|\\/)(' + acceptFileTypesRegEx + ')$'),
maxNumberOfFiles: maxNumberOfFiles,
sequentialUploads: true, // Evitar conflitos de upload: alguns arquivos eram perdidos
messages: {
maxNumberOfFiles: 'Número máximo de anexos excedido.',
acceptFileTypes: 'O anexo deve ser um arquivo dos tipos: ' + acceptFileTypesMessage + '.',
maxFileSize: 'O anexo deve possuir menos que ' + maxFileSize + ' kb.'
},
/*formData: {
_token: $('[name=_token]').val()
}*/
};
};
})();
function inicializarGridPrincipal(gridSelector, gridSource, gridConfig, urlVisualizar)
{
var grid = $(gridSelector);
// source da grid
var defaultGridSource =
{
datatype: "json",
root: 'data',
cache: false,
filter: function()
{
// update the grid and send a request to the server.
grid.jqxGrid('updatebounddata', 'filter');
},
sort: function()
{
// update the grid and send a request to the server.
grid.jqxGrid('updatebounddata', 'sort');
},
beforeprocessing: function(data)
{
if (data != null)
_gridSource.totalrecords = data.total;
}
};
// opcoes da grid
var defaultGridConfig =
{
width: "100%",
source: dataAdapter,
rowsheight: 37,
showfilterrow: true,
filterable: true,
sortable: true,
columnsresize: true,
//autoheight: true,
height: 480,
pageable: true,
virtualmode: true,
localization: getGridLocalization(),
rendergridrows: function(obj)
{
return obj.data;
}
};
var _gridSource = $.extend({}, defaultGridSource, gridSource);
var dataAdapter = new $.jqx.dataAdapter(_gridSource, _gridSource);
var _gridConfig = $.extend({}, defaultGridConfig, gridConfig);
_gridConfig.source = dataAdapter;
// initialize jqxGrid
grid.jqxGrid(_gridConfig);
grid.on('click', '.btn-excluir', function(e){
e.preventDefault();
var $this = $(this);
if (confirm('Deseja realmente excluir?'))
{
grid.jqxGrid('showloadelement');
var url = $this.attr('href');
$.ajax(url, {
type: 'POST',
data: {
_token: $('input[name=_token]').val()
}
})
.always(function(){
dataAdapter.dataBind();
})
.fail(function(){
alert('Falha ao excluir! Verifique se o registro não está em uso.');
});
}
return false;
});
if (urlVisualizar)
{
if (urlVisualizar[urlVisualizar.length - 1] != "/")
urlVisualizar += "/";
grid.on('rowdoubleclick', function (event)
{
var $this = $(this);
var id = grid.jqxGrid('source')._options.id || 'codigo';
var data = $this.jqxGrid('getrowdata', event.args.rowindex);
window.location.href = urlVisualizar + data[id];
});
}
}
function isRightClick(event) {
// Indica se o evento foi disparado pelo botão direito do mouse
var rightclick;
if (!event) var event = window.event;
if (event.which) rightclick = (event.which == 3);
else if (event.button) rightclick = (event.button == 2);
return rightclick;
}
|
// Generated on 2014-10-22 using generator-angular 0.9.5
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function(grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist',
hostname: 'localhost',
defaultLang: 'en',
ports: {
server: grunt.option('serverPort') || 9000,
test: grunt.option('testPort') || 9001,
liveReload: grunt.option('liveReloadPort') || 35729
}
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/{,**/}*.js'],
tasks: ['newer:jshint:all', 'includeSource:server'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/**/*.js'],
tasks: ['newer:jshint:test', 'karma:ci']
},
config: {
files: ['<%= yeoman.app %>/json/config.json'],
tasks: ['ngconstant']
},
compass: {
files: [
'<%= yeoman.app %>/styles/**/*.{scss,sass}',
'<%= yeoman.app %>/modules/*/styles/**/*.{scss,sass}'
],
tasks: ['compass:server', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
html: {
files: ['<%= yeoman.app %>/*.html'],
tasks: ['includeSource:server']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'.tmp/*.html',
'<%= yeoman.app %>/**/*.html',
'<%= yeoman.app %>/**/*.json',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: appConfig.ports.server,
// Change this to '0.0.0.0' to access the server from outside.
hostname: appConfig.hostname,
livereload: appConfig.ports.liveReload
},
livereload: {
options: {
open: true,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
server: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: appConfig.ports.test,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('dist')
];
}
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/{,**/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.sass-cache',
'.tmp',
'coverage',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git*'
]
}]
},
server: '.tmp',
test: ['.tmp', 'coverage']
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '**/*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
options: {
//cwd: '<%= yeoman.app %>'
},
app: {
src: [
'<%= yeoman.app %>/index.html',
'<%= yeoman.app %>/statics/*.html'
],
ignorePath: /\.\.\//
},
sass: {
src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /(\.\.\/){1,2}bower_components\//
}
},
includeSource: {
options: {
basePath: '<%= yeoman.app %>',
baseUrl: '',
},
server: {
files: {
'.tmp/index.html': '<%= yeoman.app %>/index.html'
}
},
dist: {
files: {
'<%= yeoman.dist %>/index.html': '<%= yeoman.app %>/index.html'
}
}
},
// Compiles Sass to CSS and generates necessary files if requested
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '.tmp/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: './bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false,
assetCacheBuster: false,
raw: 'Sass::Script::Number.precision = 10\n'
},
dist: {
options: {
generatedImagesDir: '<%= yeoman.dist %>/images/generated'
}
},
server: {
options: {
debugInfo: true
}
}
},
ngconstant: {
options: {
name: 'app.const',
dest: '.tmp/app.const.js',
constants: {
CONFIG: grunt.file.readJSON('app/json/config.json')
}
},
build: {}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/{,**/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.dist %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,**/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: ['<%= yeoman.dist %>', '<%= yeoman.dist %>/images']
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
concat: {
// Only one 'use strict'
useStrict: {
options: {
banner: '\'use strict\';\n',
process: function(src, filepath) {
return '// Source: ' +
filepath + '\n' +
src.replace(/(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1');
}
},
src: ['.tmp/concat/scripts/scripts.js'],
dest: '.tmp/concat/scripts/scripts.js'
}
},
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html', 'modules/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'statics/{,*/}*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'img/{,*/}*',
'fonts/*',
'json/lang/*',
'modules/**',
'!modules/*/*.js'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: '.',
src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
dest: '<%= yeoman.dist %>'
}, {
expand: true,
cwd: '.',
src: 'bower.json',
dest: '<%= yeoman.dist %>'
}, {
expand: true,
cwd: 'bower_components/fontawesome/fonts',
src: '*',
dest: '<%= yeoman.dist %>/fonts'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'compass:server'
],
test: [
'compass'
],
dist: [
'compass:dist',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
options: {
configFile: 'test/karma.conf.js'
},
ci: {
singleRun: true
},
coverage: {
singleRun: true,
reporters: ['spec', 'coverage'],
preprocessors: {
'app/**/*.js': 'coverage'
}
},
serve: {
browsers: [
'Chrome'
]
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function(target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'ngconstant',
'includeSource:server',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('_test', [
'clean:test',
'ngconstant',
'concurrent:test',
'autoprefixer',
'connect:test'
]);
grunt.registerTask('serve:test', [
'clean:server',
'_test',
'karma:serve'
]);
grunt.registerTask('test', [
'clean:server',
'_test',
'karma:ci'
]);
grunt.registerTask('test:coverage', [
'clean:server',
'_test',
'karma:coverage'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'ngconstant',
'includeSource:dist',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat:generated',
'concat:useStrict',
'ngAnnotate',
'copy:dist',
// 'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
// Based on: https://github.com/elasticsearch/kibana (licenced under: http://www.apache.org/licenses/LICENSE-2.0)
// https://github.com/elasticsearch/kibana/blob/5c2419072b3644802310a8a65b19419df429af1b/src/kibana/utils/datemath.js
// Futher modifications by Panoptix
(function() {
'use strict';
var module = angular.module('datemath', []);
module.factory('datemath', function(_, moment) {
/* This is a simplified version of elasticsearch's date parser */
var parse = function (text, roundUp) {
if (!text) return undefined;
if (moment.isMoment(text)) return text;
if (_.isDate(text)) return moment(text);
var time,
mathString = '',
index,
parseString;
if (text.substring(0, 3) === 'now') {
time = moment();
mathString = text.substring('now'.length);
} else {
index = text.indexOf('||');
if (index === -1) {
parseString = text;
mathString = ''; // nothing else
} else {
parseString = text.substring(0, index);
mathString = text.substring(index + 2);
}
// We're going to just require ISO8601 timestamps, k?
time = moment(parseString);
}
if (!mathString.length) {
return time;
}
return parseDateMath(mathString, time, roundUp);
};
var parseDateMath = function (mathString, time, roundUp) {
var dateTime = time,
spans = ['s', 'm', 'h', 'd', 'w', 'M', 'y'];
for (var i = 0; i < mathString.length;) {
var c = mathString.charAt(i++),
type,
num,
unit;
if (c === '/') {
type = 0;
} else if (c === '+') {
type = 1;
} else if (c === '-') {
type = 2;
} else {
return undefined;
}
if (isNaN(mathString.charAt(i))) {
num = 1;
} else {
var numFrom = i;
while (!isNaN(mathString.charAt(i))) {
i++;
}
num = parseInt(mathString.substring(numFrom, i), 10);
}
if (type === 0) {
// rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M)
if (num !== 1) {
return undefined;
}
}
unit = mathString.charAt(i++);
if (!_.contains(spans, unit)) {
return undefined;
} else {
if (type === 0) {
if (roundUp) {
dateTime.endOf(unit);
} else {
dateTime.startOf(unit);
}
} else if (type === 1) {
dateTime.add(unit, num);
} else if (type === 2) {
dateTime.subtract(unit, num);
}
}
}
return dateTime;
};
return {
parse: parse
};
});
}());
|
version https://git-lfs.github.com/spec/v1
oid sha256:2f159cd6e5ee410124b378646d4d64296febb0bce3331817f76159f2009cc695
size 6340
|
var webpack = require('webpack');
var path = require('path');
var webpackMerge = require('webpack-merge');
// Webpack Config
var webpackConfig = {
entry: {
'main': './main.browser.ts',
},
output: {
publicPath: '',
path: path.resolve(__dirname, './dist'),
filename : "main.bundle.js"
},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
path.resolve(__dirname, './src'),
{
// your Angular Async Route paths relative to this root directory
}
),
],
module: {
loaders: [
// .ts files for TypeScript
{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader',
'angular2-template-loader',
'angular2-router-loader'
]
},
{ test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] },
{ test: /\.html$/, loader: 'raw-loader' }
]
}
};
// Our Webpack Defaults
var defaultConfig = {
devtool: 'source-map',
output: {
filename: '[name].bundle.js',
sourceMapFilename: '[name].map',
chunkFilename: '[id].chunk.js'
},
resolve: {
extensions: [ '.ts', '.js' ],
modules: [ path.resolve(__dirname, 'node_modules') ]
},
node: {
global: true,
crypto: 'empty',
__dirname: true,
__filename: true,
process: true,
Buffer: false,
clearImmediate: false,
setImmediate: false
}
};
module.exports = webpackMerge(defaultConfig, webpackConfig);
|
/* NOTE, this simon game is made by a lot of efforts as It is written only by pure/ vanila javascript.
as far as I know about javascript, i know that I don't know it at all. My respect and special thanks to Wojciech Kałużny
who has written a very well basic pattern design to solve simon game problem, you can view his artical here
https://medium.com/front-end-hacking/create-simon-game-in-javascript-d53b474a7416
I have tried some version before with nest setTimeOut funct but none of them works perfectly, actually at first i tried put setInterval inside the
loop and I hardly learn many things to this 'dangerous' async problem with setInerval
Hope you enjoy the game
*/
"use strict"
/* Global variable */
var display = document.getElementById("digital-display");
var count = document.getElementById("digital-display").getAttribute("value");
var nodes = document.getElementsByClassName("quarter");
var els = [].slice.call(nodes); //each color parts that player may click
var gameStatus = "off"; // use to track game is on/off
var strictMode = document.getElementById("strictMode"); //this variable tracks the strict mode on/off
const whichPart = ['green', 'red', 'yellow', 'blue'];
const tones = {
green: new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3'),
red: new Audio('https://s3.amazonaws.com/freecodecamp/simonSound2.mp3'),
yellow: new Audio('https://s3.amazonaws.com/freecodecamp/simonSound3.mp3'),
blue: new Audio('https://s3.amazonaws.com/freecodecamp/simonSound4.mp3'),
playerTurn: new Audio('http://soundjax.com/reddo/40725%5EDING1.mp3'),
fail: new Audio('http://soundjax.com/reddo/76527%5Eerror.mp3')
};
var colors = []; // colors generated by computer
var player = [];
/* this function turn on / off the game */
function toggle() {
var slider = document.getElementById("slider");
var status = slider.getAttribute("value"); // on or off
var turn = status === "off" ? "on" : "off";
gameStatus = turn; // this varible pass the game status: on/off to the start button
slider.style.cssFloat = turn === "on" ? "right" : "left"; //slide the toggle
slider.setAttribute("value", turn);
console.log("status now is: " + gameStatus);
if (turn === "off") {
reset();
lockClick();
}
}
/* this funct enable/disable strict mode */
function setStrict() {
strictMode.setAttribute("value", strictMode.getAttribute("value") === "off" ? "on" : "off");
strictMode.classList.toggle("lighten");
console.log("strictmode is: " + strictMode.getAttribute("value"));
}
function startGame() {
if (gameStatus === "on") {
//this funct helps blinking the - - in the display panel
count = "- -";
display.innerHTML = "<span class='blink'>" + count + "</span";
setTimeout(function() {
clearGame();
}, 2000);
} else {
alert("please turn on the game");
}
}
function reset() {
count = "";
updateCount();
colors = [];
player = [];
}
function clearGame() {
count = 0;
colors = [];
player = [];
nextMove();
}
function updateCount() {
display.innerHTML = count;
}
function lighten(colors) {
var i = 0;
var lightening = setInterval(function() { //after each 600ms, lighten continues lighten the next colors set
lightenColor(colors[i]);
i++;
if (i >= colors.length) {
clearInterval(lightening); //lighten and darken a set of colors has finished
//now is player turn,
}
}, 600);
player = [];
setTimeout(function() {
unLockClick();
}, 1000);
}
function lightenColor(color) {
var el = document.getElementById(color);
el.classList.add("lighten");
tones[color].play();
console.log("color: " + color + " brighten");
var lightOneColor = setTimeout(function() {
el.classList.remove("lighten");
console.log("color: " + color + " darken");
}, 300);
}
function playerInput(colorPlayerInput) {
player.push(colorPlayerInput);
checkAudio(colorPlayerInput);
console.log(colorPlayerInput + " color is clicked");
match(colors);
}
function match(colors) { //check if player enter the right pattern
if (colors[player.length - 1] !== player[player.length - 1]) {
checkAudio("fail");
if (strictMode.getAttribute("value") === "on") {
startGame();
} else {
lighten(colors);
}
} else {
if (player.length === colors.length) {
if (count === 20) {
alert("Congrats! you won");
} else {
nextMove();
console.log("create next level");
}
}
}
}
function lockClick() {
els.forEach(function(element) {
element.classList.add("non-click");
//element.classList.toggle("non-hover");
}, this);
}
function unLockClick() {
els.forEach(function(element) {
element.classList.remove("non-click");
//element.classList.toggle("non-hover");
}, this);
}
function nextMove() {
var colour = whichPart[(Math.floor(Math.random() * 4))];
colors.push(colour);
console.log("add extra step / color");
console.log(colors);
lighten(colors);
count++;
updateCount();
}
//Credit to JohnnyCoder,
//https://stackoverflow.com/questions/36803176/how-to-prevent-the-play-request-was-interrupted-by-a-call-to-pause-error
function checkAudio(au) {
var audio = tones[au];
var isPlaying = audio.currentTime > 0 && !audio.paused && !audio.ended &&
audio.readyState > 2;
if (!isPlaying) {
audio.play();
} else {
console.log("audio error");
}
}
lockClick(); |
import React, { Component } from 'react';
import { Input, Button, ProgressBar } from 'react-bootstrap';
export default class Timer extends Component {
state = {
secondsRemaining: 60,
selectedSeconds: 60,
timerRunning: false
}
setInitialTime = (event) => {
this.setState({
selectedSeconds: event.target.options[event.target.selectedIndex].value,
secondsRemaining: event.target.options[event.target.selectedIndex].value
});
}
startCountdown = () => {
this.setState({timerRunning: true});
this.interval = setInterval(this.tick, 1000);
}
resetCountdown = () => {
clearInterval(this.interval);
this.setState({timerRunning: false, secondsRemaining: this.state.selectedSeconds});
}
tick = () => {
this.setState({secondsRemaining: this.state.secondsRemaining - 1});
if (this.state.secondsRemaining <= 0) {
this.resetCountdown();
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
<p>Stop slacking! Time your breaks!</p>
{this.state.timerRunning
?
<ProgressBar max={this.state.selectedSeconds} now={this.state.secondsRemaining} label={this.state.secondsRemaining} />
:
<Input type="select" value={this.state.selectedSeconds} onChange={this.setInitialTime}>
<option value="60">60 seconds</option>
<option value="120">120 seconds</option>
<option value="180">180 seconds</option>
</Input>
}
<Button block onClick={this.state.timerRunning ? this.resetCountdown : this.startCountdown}>
{this.state.timerRunning ? 'Stop' : 'Start'} Timer
</Button>
</div>
);
}
}
|
/**
* Sinon.JS 1.6.0, 2013/02/18
*
* @author Christian Johansen (christian@cjohansen.no)
* @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
*
* (The BSD License)
*
* Copyright (c) 2010-2013, Christian Johansen, christian@cjohansen.no
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Christian Johansen nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var sinon = (function () {
"use strict";
var buster = (function (setTimeout, B) {
var isNode = typeof require == "function" && typeof module == "object";
var div = typeof document != "undefined" && document.createElement("div");
var F = function () {};
var buster = {
bind: function bind(obj, methOrProp) {
var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
var args = Array.prototype.slice.call(arguments, 2);
return function () {
var allArgs = args.concat(Array.prototype.slice.call(arguments));
return method.apply(obj, allArgs);
};
},
partial: function partial(fn) {
var args = [].slice.call(arguments, 1);
return function () {
return fn.apply(this, args.concat([].slice.call(arguments)));
};
},
create: function create(object) {
F.prototype = object;
return new F();
},
extend: function extend(target) {
if (!target) { return; }
for (var i = 1, l = arguments.length, prop; i < l; ++i) {
for (prop in arguments[i]) {
target[prop] = arguments[i][prop];
}
}
return target;
},
nextTick: function nextTick(callback) {
if (typeof process != "undefined" && process.nextTick) {
return process.nextTick(callback);
}
setTimeout(callback, 0);
},
functionName: function functionName(func) {
if (!func) return "";
if (func.displayName) return func.displayName;
if (func.name) return func.name;
var matches = func.toString().match(/function\s+([^\(]+)/m);
return matches && matches[1] || "";
},
isNode: function isNode(obj) {
if (!div) return false;
try {
obj.appendChild(div);
obj.removeChild(div);
} catch (e) {
return false;
}
return true;
},
isElement: function isElement(obj) {
return obj && obj.nodeType === 1 && buster.isNode(obj);
},
isArray: function isArray(arr) {
return Object.prototype.toString.call(arr) == "[object Array]";
},
flatten: function flatten(arr) {
var result = [], arr = arr || [];
for (var i = 0, l = arr.length; i < l; ++i) {
result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
}
return result;
},
each: function each(arr, callback) {
for (var i = 0, l = arr.length; i < l; ++i) {
callback(arr[i]);
}
},
map: function map(arr, callback) {
var results = [];
for (var i = 0, l = arr.length; i < l; ++i) {
results.push(callback(arr[i]));
}
return results;
},
parallel: function parallel(fns, callback) {
function cb(err, res) {
if (typeof callback == "function") {
callback(err, res);
callback = null;
}
}
if (fns.length == 0) { return cb(null, []); }
var remaining = fns.length, results = [];
function makeDone(num) {
return function done(err, result) {
if (err) { return cb(err); }
results[num] = result;
if (--remaining == 0) { cb(null, results); }
};
}
for (var i = 0, l = fns.length; i < l; ++i) {
fns[i](makeDone(i));
}
},
series: function series(fns, callback) {
function cb(err, res) {
if (typeof callback == "function") {
callback(err, res);
}
}
var remaining = fns.slice();
var results = [];
function callNext() {
if (remaining.length == 0) return cb(null, results);
var promise = remaining.shift()(next);
if (promise && typeof promise.then == "function") {
promise.then(buster.partial(next, null), next);
}
}
function next(err, result) {
if (err) return cb(err);
results.push(result);
callNext();
}
callNext();
},
countdown: function countdown(num, done) {
return function () {
if (--num == 0) done();
};
}
};
if (typeof process === "object" &&
typeof require === "function" && typeof module === "object") {
var crypto = require("crypto");
var path = require("path");
buster.tmpFile = function (fileName) {
var hashed = crypto.createHash("sha1");
hashed.update(fileName);
var tmpfileName = hashed.digest("hex");
if (process.platform == "win32") {
return path.join(process.env["TEMP"], tmpfileName);
} else {
return path.join("/tmp", tmpfileName);
}
};
}
if (Array.prototype.some) {
buster.some = function (arr, fn, thisp) {
return arr.some(fn, thisp);
};
} else {
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
buster.some = function (arr, fun, thisp) {
if (arr == null) { throw new TypeError(); }
arr = Object(arr);
var len = arr.length >>> 0;
if (typeof fun !== "function") { throw new TypeError(); }
for (var i = 0; i < len; i++) {
if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) {
return true;
}
}
return false;
};
}
if (Array.prototype.filter) {
buster.filter = function (arr, fn, thisp) {
return arr.filter(fn, thisp);
};
} else {
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
buster.filter = function (fn, thisp) {
if (this == null) { throw new TypeError(); }
var t = Object(this);
var len = t.length >>> 0;
if (typeof fn != "function") { throw new TypeError(); }
var res = [];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fun mutates this
if (fn.call(thisp, val, i, t)) { res.push(val); }
}
}
return res;
};
}
if (isNode) {
module.exports = buster;
buster.eventEmitter = require("./buster-event-emitter");
Object.defineProperty(buster, "defineVersionGetter", {
get: function () {
return require("./define-version-getter");
}
});
}
return buster.extend(B || {}, buster);
}(setTimeout, buster));
if (typeof buster === "undefined") {
var buster = {};
}
if (typeof module === "object" && typeof require === "function") {
buster = require("buster-core");
}
buster.format = buster.format || {};
buster.format.excludeConstructors = ["Object", /^.$/];
buster.format.quoteStrings = true;
buster.format.ascii = (function () {
var hasOwn = Object.prototype.hasOwnProperty;
var specialObjects = [];
if (typeof global != "undefined") {
specialObjects.push({ obj: global, value: "[object global]" });
}
if (typeof document != "undefined") {
specialObjects.push({ obj: document, value: "[object HTMLDocument]" });
}
if (typeof window != "undefined") {
specialObjects.push({ obj: window, value: "[object Window]" });
}
function keys(object) {
var k = Object.keys && Object.keys(object) || [];
if (k.length == 0) {
for (var prop in object) {
if (hasOwn.call(object, prop)) {
k.push(prop);
}
}
}
return k.sort();
}
function isCircular(object, objects) {
if (typeof object != "object") {
return false;
}
for (var i = 0, l = objects.length; i < l; ++i) {
if (objects[i] === object) {
return true;
}
}
return false;
}
function ascii(object, processed, indent) {
if (typeof object == "string") {
var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings;
return processed || quote ? '"' + object + '"' : object;
}
if (typeof object == "function" && !(object instanceof RegExp)) {
return ascii.func(object);
}
processed = processed || [];
if (isCircular(object, processed)) {
return "[Circular]";
}
if (Object.prototype.toString.call(object) == "[object Array]") {
return ascii.array.call(this, object, processed);
}
if (!object) {
return "" + object;
}
if (buster.isElement(object)) {
return ascii.element(object);
}
if (typeof object.toString == "function" &&
object.toString !== Object.prototype.toString) {
return object.toString();
}
for (var i = 0, l = specialObjects.length; i < l; i++) {
if (object === specialObjects[i].obj) {
return specialObjects[i].value;
}
}
return ascii.object.call(this, object, processed, indent);
}
ascii.func = function (func) {
return "function " + buster.functionName(func) + "() {}";
};
ascii.array = function (array, processed) {
processed = processed || [];
processed.push(array);
var pieces = [];
for (var i = 0, l = array.length; i < l; ++i) {
pieces.push(ascii.call(this, array[i], processed));
}
return "[" + pieces.join(", ") + "]";
};
ascii.object = function (object, processed, indent) {
processed = processed || [];
processed.push(object);
indent = indent || 0;
var pieces = [], properties = keys(object), prop, str, obj;
var is = "";
var length = 3;
for (var i = 0, l = indent; i < l; ++i) {
is += " ";
}
for (i = 0, l = properties.length; i < l; ++i) {
prop = properties[i];
obj = object[prop];
if (isCircular(obj, processed)) {
str = "[Circular]";
} else {
str = ascii.call(this, obj, processed, indent + 2);
}
str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
length += str.length;
pieces.push(str);
}
var cons = ascii.constructorName.call(this, object);
var prefix = cons ? "[" + cons + "] " : ""
return (length + indent) > 80 ?
prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}" :
prefix + "{ " + pieces.join(", ") + " }";
};
ascii.element = function (element) {
var tagName = element.tagName.toLowerCase();
var attrs = element.attributes, attribute, pairs = [], attrName;
for (var i = 0, l = attrs.length; i < l; ++i) {
attribute = attrs.item(i);
attrName = attribute.nodeName.toLowerCase().replace("html:", "");
if (attrName == "contenteditable" && attribute.nodeValue == "inherit") {
continue;
}
if (!!attribute.nodeValue) {
pairs.push(attrName + "=\"" + attribute.nodeValue + "\"");
}
}
var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
var content = element.innerHTML;
if (content.length > 20) {
content = content.substr(0, 20) + "[...]";
}
var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">";
return res.replace(/ contentEditable="inherit"/, "");
};
ascii.constructorName = function (object) {
var name = buster.functionName(object && object.constructor);
var excludes = this.excludeConstructors || buster.format.excludeConstructors || [];
for (var i = 0, l = excludes.length; i < l; ++i) {
if (typeof excludes[i] == "string" && excludes[i] == name) {
return "";
} else if (excludes[i].test && excludes[i].test(name)) {
return "";
}
}
return name;
};
return ascii;
}());
if (typeof module != "undefined") {
module.exports = buster.format;
}
/*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
/*global module, require, __dirname, document*/
/**
* Sinon core utilities. For internal use only.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
var sinon = (function (buster) {
var div = typeof document != "undefined" && document.createElement("div");
var hasOwn = Object.prototype.hasOwnProperty;
function isDOMNode(obj) {
var success = false;
try {
obj.appendChild(div);
success = div.parentNode == obj;
} catch (e) {
return false;
} finally {
try {
obj.removeChild(div);
} catch (e) {
// Remove failed, not much we can do about that
}
}
return success;
}
function isElement(obj) {
return div && obj && obj.nodeType === 1 && isDOMNode(obj);
}
function isFunction(obj) {
return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
}
function mirrorProperties(target, source) {
for (var prop in source) {
if (!hasOwn.call(target, prop)) {
target[prop] = source[prop];
}
}
}
var sinon = {
wrapMethod: function wrapMethod(object, property, method) {
if (!object) {
throw new TypeError("Should wrap property of object");
}
if (typeof method != "function") {
throw new TypeError("Method wrapper should be function");
}
var wrappedMethod = object[property];
if (!isFunction(wrappedMethod)) {
throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
property + " as function");
}
if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
throw new TypeError("Attempted to wrap " + property + " which is already wrapped");
}
if (wrappedMethod.calledBefore) {
var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
throw new TypeError("Attempted to wrap " + property + " which is already " + verb);
}
// IE 8 does not support hasOwnProperty on the window object.
var owned = hasOwn.call(object, property);
object[property] = method;
method.displayName = property;
method.restore = function () {
// For prototype properties try to reset by delete first.
// If this fails (ex: localStorage on mobile safari) then force a reset
// via direct assignment.
if (!owned) {
delete object[property];
}
if (object[property] === method) {
object[property] = wrappedMethod;
}
};
method.restore.sinon = true;
mirrorProperties(method, wrappedMethod);
return method;
},
extend: function extend(target) {
for (var i = 1, l = arguments.length; i < l; i += 1) {
for (var prop in arguments[i]) {
if (arguments[i].hasOwnProperty(prop)) {
target[prop] = arguments[i][prop];
}
// DONT ENUM bug, only care about toString
if (arguments[i].hasOwnProperty("toString") &&
arguments[i].toString != target.toString) {
target.toString = arguments[i].toString;
}
}
}
return target;
},
create: function create(proto) {
var F = function () {};
F.prototype = proto;
return new F();
},
deepEqual: function deepEqual(a, b) {
if (sinon.match && sinon.match.isMatcher(a)) {
return a.test(b);
}
if (typeof a != "object" || typeof b != "object") {
return a === b;
}
if (isElement(a) || isElement(b)) {
return a === b;
}
if (a === b) {
return true;
}
if ((a === null && b !== null) || (a !== null && b === null)) {
return false;
}
var aString = Object.prototype.toString.call(a);
if (aString != Object.prototype.toString.call(b)) {
return false;
}
if (aString == "[object Array]") {
if (a.length !== b.length) {
return false;
}
for (var i = 0, l = a.length; i < l; i += 1) {
if (!deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
var prop, aLength = 0, bLength = 0;
for (prop in a) {
aLength += 1;
if (!deepEqual(a[prop], b[prop])) {
return false;
}
}
for (prop in b) {
bLength += 1;
}
if (aLength != bLength) {
return false;
}
return true;
},
functionName: function functionName(func) {
var name = func.displayName || func.name;
// Use function decomposition as a last resort to get function
// name. Does not rely on function decomposition to work - if it
// doesn't debugging will be slightly less informative
// (i.e. toString will say 'spy' rather than 'myFunc').
if (!name) {
var matches = func.toString().match(/function ([^\s\(]+)/);
name = matches && matches[1];
}
return name;
},
functionToString: function toString() {
if (this.getCall && this.callCount) {
var thisValue, prop, i = this.callCount;
while (i--) {
thisValue = this.getCall(i).thisValue;
for (prop in thisValue) {
if (thisValue[prop] === this) {
return prop;
}
}
}
}
return this.displayName || "sinon fake";
},
getConfig: function (custom) {
var config = {};
custom = custom || {};
var defaults = sinon.defaultConfig;
for (var prop in defaults) {
if (defaults.hasOwnProperty(prop)) {
config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
}
}
return config;
},
format: function (val) {
return "" + val;
},
defaultConfig: {
injectIntoThis: true,
injectInto: null,
properties: ["spy", "stub", "mock", "clock", "server", "requests"],
useFakeTimers: true,
useFakeServer: true
},
timesInWords: function timesInWords(count) {
return count == 1 && "once" ||
count == 2 && "twice" ||
count == 3 && "thrice" ||
(count || 0) + " times";
},
calledInOrder: function (spies) {
for (var i = 1, l = spies.length; i < l; i++) {
if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) {
return false;
}
}
return true;
},
orderByFirstCall: function (spies) {
return spies.sort(function (a, b) {
// uuid, won't ever be equal
var aCall = a.getCall(0);
var bCall = b.getCall(0);
var aId = aCall && aCall.callId || -1;
var bId = bCall && bCall.callId || -1;
return aId < bId ? -1 : 1;
});
},
log: function () {},
logError: function (label, err) {
var msg = label + " threw exception: "
sinon.log(msg + "[" + err.name + "] " + err.message);
if (err.stack) { sinon.log(err.stack); }
setTimeout(function () {
err.message = msg + err.message;
throw err;
}, 0);
},
typeOf: function (value) {
if (value === null) {
return "null";
}
else if (value === undefined) {
return "undefined";
}
var string = Object.prototype.toString.call(value);
return string.substring(8, string.length - 1).toLowerCase();
},
createStubInstance: function (constructor) {
if (typeof constructor !== "function") {
throw new TypeError("The constructor should be a function.");
}
return sinon.stub(sinon.create(constructor.prototype));
}
};
var isNode = typeof module == "object" && typeof require == "function";
if (isNode) {
try {
buster = { format: require("buster-format") };
} catch (e) {}
module.exports = sinon;
module.exports.spy = require("./sinon/spy");
module.exports.stub = require("./sinon/stub");
module.exports.mock = require("./sinon/mock");
module.exports.collection = require("./sinon/collection");
module.exports.assert = require("./sinon/assert");
module.exports.sandbox = require("./sinon/sandbox");
module.exports.test = require("./sinon/test");
module.exports.testCase = require("./sinon/test_case");
module.exports.assert = require("./sinon/assert");
module.exports.match = require("./sinon/match");
}
if (buster) {
var formatter = sinon.create(buster.format);
formatter.quoteStrings = false;
sinon.format = function () {
return formatter.ascii.apply(formatter, arguments);
};
} else if (isNode) {
try {
var util = require("util");
sinon.format = function (value) {
return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
};
} catch (e) {
/* Node, but no util module - would be very old, but better safe than
sorry */
}
}
return sinon;
}(typeof buster == "object" && buster));
/* @depend ../sinon.js */
/*jslint eqeqeq: false, onevar: false, plusplus: false*/
/*global module, require, sinon*/
/**
* Match functions
*
* @author Maximilian Antoni (mail@maxantoni.de)
* @license BSD
*
* Copyright (c) 2012 Maximilian Antoni
*/
(function (sinon) {
var commonJSModule = typeof module == "object" && typeof require == "function";
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon) {
return;
}
function assertType(value, type, name) {
var actual = sinon.typeOf(value);
if (actual !== type) {
throw new TypeError("Expected type of " + name + " to be " +
type + ", but was " + actual);
}
}
var matcher = {
toString: function () {
return this.message;
}
};
function isMatcher(object) {
return matcher.isPrototypeOf(object);
}
function matchObject(expectation, actual) {
if (actual === null || actual === undefined) {
return false;
}
for (var key in expectation) {
if (expectation.hasOwnProperty(key)) {
var exp = expectation[key];
var act = actual[key];
if (match.isMatcher(exp)) {
if (!exp.test(act)) {
return false;
}
} else if (sinon.typeOf(exp) === "object") {
if (!matchObject(exp, act)) {
return false;
}
} else if (!sinon.deepEqual(exp, act)) {
return false;
}
}
}
return true;
}
matcher.or = function (m2) {
if (!isMatcher(m2)) {
throw new TypeError("Matcher expected");
}
var m1 = this;
var or = sinon.create(matcher);
or.test = function (actual) {
return m1.test(actual) || m2.test(actual);
};
or.message = m1.message + ".or(" + m2.message + ")";
return or;
};
matcher.and = function (m2) {
if (!isMatcher(m2)) {
throw new TypeError("Matcher expected");
}
var m1 = this;
var and = sinon.create(matcher);
and.test = function (actual) {
return m1.test(actual) && m2.test(actual);
};
and.message = m1.message + ".and(" + m2.message + ")";
return and;
};
var match = function (expectation, message) {
var m = sinon.create(matcher);
var type = sinon.typeOf(expectation);
switch (type) {
case "object":
if (typeof expectation.test === "function") {
m.test = function (actual) {
return expectation.test(actual) === true;
};
m.message = "match(" + sinon.functionName(expectation.test) + ")";
return m;
}
var str = [];
for (var key in expectation) {
if (expectation.hasOwnProperty(key)) {
str.push(key + ": " + expectation[key]);
}
}
m.test = function (actual) {
return matchObject(expectation, actual);
};
m.message = "match(" + str.join(", ") + ")";
break;
case "number":
m.test = function (actual) {
return expectation == actual;
};
break;
case "string":
m.test = function (actual) {
if (typeof actual !== "string") {
return false;
}
return actual.indexOf(expectation) !== -1;
};
m.message = "match(\"" + expectation + "\")";
break;
case "regexp":
m.test = function (actual) {
if (typeof actual !== "string") {
return false;
}
return expectation.test(actual);
};
break;
case "function":
m.test = expectation;
if (message) {
m.message = message;
} else {
m.message = "match(" + sinon.functionName(expectation) + ")";
}
break;
default:
m.test = function (actual) {
return sinon.deepEqual(expectation, actual);
};
}
if (!m.message) {
m.message = "match(" + expectation + ")";
}
return m;
};
match.isMatcher = isMatcher;
match.any = match(function () {
return true;
}, "any");
match.defined = match(function (actual) {
return actual !== null && actual !== undefined;
}, "defined");
match.truthy = match(function (actual) {
return !!actual;
}, "truthy");
match.falsy = match(function (actual) {
return !actual;
}, "falsy");
match.same = function (expectation) {
return match(function (actual) {
return expectation === actual;
}, "same(" + expectation + ")");
};
match.typeOf = function (type) {
assertType(type, "string", "type");
return match(function (actual) {
return sinon.typeOf(actual) === type;
}, "typeOf(\"" + type + "\")");
};
match.instanceOf = function (type) {
assertType(type, "function", "type");
return match(function (actual) {
return actual instanceof type;
}, "instanceOf(" + sinon.functionName(type) + ")");
};
function createPropertyMatcher(propertyTest, messagePrefix) {
return function (property, value) {
assertType(property, "string", "property");
var onlyProperty = arguments.length === 1;
var message = messagePrefix + "(\"" + property + "\"";
if (!onlyProperty) {
message += ", " + value;
}
message += ")";
return match(function (actual) {
if (actual === undefined || actual === null ||
!propertyTest(actual, property)) {
return false;
}
return onlyProperty || sinon.deepEqual(value, actual[property]);
}, message);
};
}
match.has = createPropertyMatcher(function (actual, property) {
if (typeof actual === "object") {
return property in actual;
}
return actual[property] !== undefined;
}, "has");
match.hasOwn = createPropertyMatcher(function (actual, property) {
return actual.hasOwnProperty(property);
}, "hasOwn");
match.bool = match.typeOf("boolean");
match.number = match.typeOf("number");
match.string = match.typeOf("string");
match.object = match.typeOf("object");
match.func = match.typeOf("function");
match.array = match.typeOf("array");
match.regexp = match.typeOf("regexp");
match.date = match.typeOf("date");
if (commonJSModule) {
module.exports = match;
} else {
sinon.match = match;
}
}(typeof sinon == "object" && sinon || null));
/**
* @depend ../sinon.js
* @depend match.js
*/
/*jslint eqeqeq: false, onevar: false, plusplus: false*/
/*global module, require, sinon*/
/**
* Spy functions
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function (sinon) {
var commonJSModule = typeof module == "object" && typeof require == "function";
var spyCall;
var callId = 0;
var push = [].push;
var slice = Array.prototype.slice;
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon) {
return;
}
function spy(object, property) {
if (!property && typeof object == "function") {
return spy.create(object);
}
if (!object && !property) {
return spy.create(function () { });
}
var method = object[property];
return sinon.wrapMethod(object, property, spy.create(method));
}
sinon.extend(spy, (function () {
function delegateToCalls(api, method, matchAny, actual, notCalled) {
api[method] = function () {
if (!this.called) {
if (notCalled) {
return notCalled.apply(this, arguments);
}
return false;
}
var currentCall;
var matches = 0;
for (var i = 0, l = this.callCount; i < l; i += 1) {
currentCall = this.getCall(i);
if (currentCall[actual || method].apply(currentCall, arguments)) {
matches += 1;
if (matchAny) {
return true;
}
}
}
return matches === this.callCount;
};
}
function matchingFake(fakes, args, strict) {
if (!fakes) {
return;
}
var alen = args.length;
for (var i = 0, l = fakes.length; i < l; i++) {
if (fakes[i].matches(args, strict)) {
return fakes[i];
}
}
}
function incrementCallCount() {
this.called = true;
this.callCount += 1;
this.notCalled = false;
this.calledOnce = this.callCount == 1;
this.calledTwice = this.callCount == 2;
this.calledThrice = this.callCount == 3;
}
function createCallProperties() {
this.firstCall = this.getCall(0);
this.secondCall = this.getCall(1);
this.thirdCall = this.getCall(2);
this.lastCall = this.getCall(this.callCount - 1);
}
var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
function createProxy(func) {
// Retain the function length:
var p;
if (func.length) {
eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) +
") { return p.invoke(func, this, slice.call(arguments)); });");
}
else {
p = function proxy() {
return p.invoke(func, this, slice.call(arguments));
};
}
return p;
}
var uuid = 0;
// Public API
var spyApi = {
reset: function () {
this.called = false;
this.notCalled = true;
this.calledOnce = false;
this.calledTwice = false;
this.calledThrice = false;
this.callCount = 0;
this.firstCall = null;
this.secondCall = null;
this.thirdCall = null;
this.lastCall = null;
this.args = [];
this.returnValues = [];
this.thisValues = [];
this.exceptions = [];
this.callIds = [];
if (this.fakes) {
for (var i = 0; i < this.fakes.length; i++) {
this.fakes[i].reset();
}
}
},
create: function create(func) {
var name;
if (typeof func != "function") {
func = function () { };
} else {
name = sinon.functionName(func);
}
var proxy = createProxy(func);
sinon.extend(proxy, spy);
delete proxy.create;
sinon.extend(proxy, func);
proxy.reset();
proxy.prototype = func.prototype;
proxy.displayName = name || "spy";
proxy.toString = sinon.functionToString;
proxy._create = sinon.spy.create;
proxy.id = "spy#" + uuid++;
return proxy;
},
invoke: function invoke(func, thisValue, args) {
var matching = matchingFake(this.fakes, args);
var exception, returnValue;
incrementCallCount.call(this);
push.call(this.thisValues, thisValue);
push.call(this.args, args);
push.call(this.callIds, callId++);
try {
if (matching) {
returnValue = matching.invoke(func, thisValue, args);
} else {
returnValue = (this.func || func).apply(thisValue, args);
}
} catch (e) {
push.call(this.returnValues, undefined);
exception = e;
throw e;
} finally {
push.call(this.exceptions, exception);
}
push.call(this.returnValues, returnValue);
createCallProperties.call(this);
return returnValue;
},
getCall: function getCall(i) {
if (i < 0 || i >= this.callCount) {
return null;
}
return spyCall.create(this, this.thisValues[i], this.args[i],
this.returnValues[i], this.exceptions[i],
this.callIds[i]);
},
calledBefore: function calledBefore(spyFn) {
if (!this.called) {
return false;
}
if (!spyFn.called) {
return true;
}
return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
},
calledAfter: function calledAfter(spyFn) {
if (!this.called || !spyFn.called) {
return false;
}
return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
},
withArgs: function () {
var args = slice.call(arguments);
if (this.fakes) {
var match = matchingFake(this.fakes, args, true);
if (match) {
return match;
}
} else {
this.fakes = [];
}
var original = this;
var fake = this._create();
fake.matchingAguments = args;
push.call(this.fakes, fake);
fake.withArgs = function () {
return original.withArgs.apply(original, arguments);
};
for (var i = 0; i < this.args.length; i++) {
if (fake.matches(this.args[i])) {
incrementCallCount.call(fake);
push.call(fake.thisValues, this.thisValues[i]);
push.call(fake.args, this.args[i]);
push.call(fake.returnValues, this.returnValues[i]);
push.call(fake.exceptions, this.exceptions[i]);
push.call(fake.callIds, this.callIds[i]);
}
}
createCallProperties.call(fake);
return fake;
},
matches: function (args, strict) {
var margs = this.matchingAguments;
if (margs.length <= args.length &&
sinon.deepEqual(margs, args.slice(0, margs.length))) {
return !strict || margs.length == args.length;
}
},
printf: function (format) {
var spy = this;
var args = slice.call(arguments, 1);
var formatter;
return (format || "").replace(/%(.)/g, function (match, specifyer) {
formatter = spyApi.formatters[specifyer];
if (typeof formatter == "function") {
return formatter.call(null, spy, args);
} else if (!isNaN(parseInt(specifyer), 10)) {
return sinon.format(args[specifyer - 1]);
}
return "%" + specifyer;
});
}
};
delegateToCalls(spyApi, "calledOn", true);
delegateToCalls(spyApi, "alwaysCalledOn", false, "calledOn");
delegateToCalls(spyApi, "calledWith", true);
delegateToCalls(spyApi, "calledWithMatch", true);
delegateToCalls(spyApi, "alwaysCalledWith", false, "calledWith");
delegateToCalls(spyApi, "alwaysCalledWithMatch", false, "calledWithMatch");
delegateToCalls(spyApi, "calledWithExactly", true);
delegateToCalls(spyApi, "alwaysCalledWithExactly", false, "calledWithExactly");
delegateToCalls(spyApi, "neverCalledWith", false, "notCalledWith",
function () { return true; });
delegateToCalls(spyApi, "neverCalledWithMatch", false, "notCalledWithMatch",
function () { return true; });
delegateToCalls(spyApi, "threw", true);
delegateToCalls(spyApi, "alwaysThrew", false, "threw");
delegateToCalls(spyApi, "returned", true);
delegateToCalls(spyApi, "alwaysReturned", false, "returned");
delegateToCalls(spyApi, "calledWithNew", true);
delegateToCalls(spyApi, "alwaysCalledWithNew", false, "calledWithNew");
delegateToCalls(spyApi, "callArg", false, "callArgWith", function () {
throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
});
spyApi.callArgWith = spyApi.callArg;
delegateToCalls(spyApi, "callArgOn", false, "callArgOnWith", function () {
throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
});
spyApi.callArgOnWith = spyApi.callArgOn;
delegateToCalls(spyApi, "yield", false, "yield", function () {
throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
});
// "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
spyApi.invokeCallback = spyApi.yield;
delegateToCalls(spyApi, "yieldOn", false, "yieldOn", function () {
throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
});
delegateToCalls(spyApi, "yieldTo", false, "yieldTo", function (property) {
throw new Error(this.toString() + " cannot yield to '" + property +
"' since it was not yet invoked.");
});
delegateToCalls(spyApi, "yieldToOn", false, "yieldToOn", function (property) {
throw new Error(this.toString() + " cannot yield to '" + property +
"' since it was not yet invoked.");
});
spyApi.formatters = {
"c": function (spy) {
return sinon.timesInWords(spy.callCount);
},
"n": function (spy) {
return spy.toString();
},
"C": function (spy) {
var calls = [];
for (var i = 0, l = spy.callCount; i < l; ++i) {
var stringifiedCall = " " + spy.getCall(i).toString();
if (/\n/.test(calls[i - 1])) {
stringifiedCall = "\n" + stringifiedCall;
}
push.call(calls, stringifiedCall);
}
return calls.length > 0 ? "\n" + calls.join("\n") : "";
},
"t": function (spy) {
var objects = [];
for (var i = 0, l = spy.callCount; i < l; ++i) {
push.call(objects, sinon.format(spy.thisValues[i]));
}
return objects.join(", ");
},
"*": function (spy, args) {
var formatted = [];
for (var i = 0, l = args.length; i < l; ++i) {
push.call(formatted, sinon.format(args[i]));
}
return formatted.join(", ");
}
};
return spyApi;
}()));
spyCall = (function () {
function throwYieldError(proxy, text, args) {
var msg = sinon.functionName(proxy) + text;
if (args.length) {
msg += " Received [" + slice.call(args).join(", ") + "]";
}
throw new Error(msg);
}
var callApi = {
create: function create(spy, thisValue, args, returnValue, exception, id) {
var proxyCall = sinon.create(spyCall);
delete proxyCall.create;
proxyCall.proxy = spy;
proxyCall.thisValue = thisValue;
proxyCall.args = args;
proxyCall.returnValue = returnValue;
proxyCall.exception = exception;
proxyCall.callId = typeof id == "number" && id || callId++;
return proxyCall;
},
calledOn: function calledOn(thisValue) {
if (sinon.match && sinon.match.isMatcher(thisValue)) {
return thisValue.test(this.thisValue);
}
return this.thisValue === thisValue;
},
calledWith: function calledWith() {
for (var i = 0, l = arguments.length; i < l; i += 1) {
if (!sinon.deepEqual(arguments[i], this.args[i])) {
return false;
}
}
return true;
},
calledWithMatch: function calledWithMatch() {
for (var i = 0, l = arguments.length; i < l; i += 1) {
var actual = this.args[i];
var expectation = arguments[i];
if (!sinon.match || !sinon.match(expectation).test(actual)) {
return false;
}
}
return true;
},
calledWithExactly: function calledWithExactly() {
return arguments.length == this.args.length &&
this.calledWith.apply(this, arguments);
},
notCalledWith: function notCalledWith() {
return !this.calledWith.apply(this, arguments);
},
notCalledWithMatch: function notCalledWithMatch() {
return !this.calledWithMatch.apply(this, arguments);
},
returned: function returned(value) {
return sinon.deepEqual(value, this.returnValue);
},
threw: function threw(error) {
if (typeof error == "undefined" || !this.exception) {
return !!this.exception;
}
if (typeof error == "string") {
return this.exception.name == error;
}
return this.exception === error;
},
calledWithNew: function calledWithNew(thisValue) {
return this.thisValue instanceof this.proxy;
},
calledBefore: function (other) {
return this.callId < other.callId;
},
calledAfter: function (other) {
return this.callId > other.callId;
},
callArg: function (pos) {
this.args[pos]();
},
callArgOn: function (pos, thisValue) {
this.args[pos].apply(thisValue);
},
callArgWith: function (pos) {
this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1)));
},
callArgOnWith: function (pos, thisValue) {
var args = slice.call(arguments, 2);
this.args[pos].apply(thisValue, args);
},
"yield": function () {
this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0)));
},
yieldOn: function (thisValue) {
var args = this.args;
for (var i = 0, l = args.length; i < l; ++i) {
if (typeof args[i] === "function") {
args[i].apply(thisValue, slice.call(arguments, 1));
return;
}
}
throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
},
yieldTo: function (prop) {
this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1)));
},
yieldToOn: function (prop, thisValue) {
var args = this.args;
for (var i = 0, l = args.length; i < l; ++i) {
if (args[i] && typeof args[i][prop] === "function") {
args[i][prop].apply(thisValue, slice.call(arguments, 2));
return;
}
}
throwYieldError(this.proxy, " cannot yield to '" + prop +
"' since no callback was passed.", args);
},
toString: function () {
var callStr = this.proxy.toString() + "(";
var args = [];
for (var i = 0, l = this.args.length; i < l; ++i) {
push.call(args, sinon.format(this.args[i]));
}
callStr = callStr + args.join(", ") + ")";
if (typeof this.returnValue != "undefined") {
callStr += " => " + sinon.format(this.returnValue);
}
if (this.exception) {
callStr += " !" + this.exception.name;
if (this.exception.message) {
callStr += "(" + this.exception.message + ")";
}
}
return callStr;
}
};
callApi.invokeCallback = callApi.yield;
return callApi;
}());
spy.spyCall = spyCall;
// This steps outside the module sandbox and will be removed
sinon.spyCall = spyCall;
if (commonJSModule) {
module.exports = spy;
} else {
sinon.spy = spy;
}
}(typeof sinon == "object" && sinon || null));
/**
* @depend ../sinon.js
* @depend spy.js
*/
/*jslint eqeqeq: false, onevar: false*/
/*global module, require, sinon*/
/**
* Stub functions
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function (sinon) {
var commonJSModule = typeof module == "object" && typeof require == "function";
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon) {
return;
}
function stub(object, property, func) {
if (!!func && typeof func != "function") {
throw new TypeError("Custom stub should be function");
}
var wrapper;
if (func) {
wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
} else {
wrapper = stub.create();
}
if (!object && !property) {
return sinon.stub.create();
}
if (!property && !!object && typeof object == "object") {
for (var prop in object) {
if (typeof object[prop] === "function") {
stub(object, prop);
}
}
return object;
}
return sinon.wrapMethod(object, property, wrapper);
}
function getChangingValue(stub, property) {
var index = stub.callCount - 1;
var values = stub[property];
var prop = index in values ? values[index] : values[values.length - 1];
stub[property + "Last"] = prop;
return prop;
}
function getCallback(stub, args) {
var callArgAt = getChangingValue(stub, "callArgAts");
if (callArgAt < 0) {
var callArgProp = getChangingValue(stub, "callArgProps");
for (var i = 0, l = args.length; i < l; ++i) {
if (!callArgProp && typeof args[i] == "function") {
return args[i];
}
if (callArgProp && args[i] &&
typeof args[i][callArgProp] == "function") {
return args[i][callArgProp];
}
}
return null;
}
return args[callArgAt];
}
var join = Array.prototype.join;
function getCallbackError(stub, func, args) {
if (stub.callArgAtsLast < 0) {
var msg;
if (stub.callArgPropsLast) {
msg = sinon.functionName(stub) +
" expected to yield to '" + stub.callArgPropsLast +
"', but no object with such a property was passed."
} else {
msg = sinon.functionName(stub) +
" expected to yield, but no callback was passed."
}
if (args.length > 0) {
msg += " Received [" + join.call(args, ", ") + "]";
}
return msg;
}
return "argument at index " + stub.callArgAtsLast + " is not a function: " + func;
}
var nextTick = (function () {
if (typeof process === "object" && typeof process.nextTick === "function") {
return process.nextTick;
} else if (typeof setImmediate === "function") {
return setImmediate;
} else {
return function (callback) {
setTimeout(callback, 0);
};
}
})();
function callCallback(stub, args) {
if (stub.callArgAts.length > 0) {
var func = getCallback(stub, args);
if (typeof func != "function") {
throw new TypeError(getCallbackError(stub, func, args));
}
var callbackArguments = getChangingValue(stub, "callbackArguments");
var callbackContext = getChangingValue(stub, "callbackContexts");
if (stub.callbackAsync) {
nextTick(function() {
func.apply(callbackContext, callbackArguments);
});
} else {
func.apply(callbackContext, callbackArguments);
}
}
}
var uuid = 0;
sinon.extend(stub, (function () {
var slice = Array.prototype.slice, proto;
function throwsException(error, message) {
if (typeof error == "string") {
this.exception = new Error(message || "");
this.exception.name = error;
} else if (!error) {
this.exception = new Error("Error");
} else {
this.exception = error;
}
return this;
}
proto = {
create: function create() {
var functionStub = function () {
callCallback(functionStub, arguments);
if (functionStub.exception) {
throw functionStub.exception;
} else if (typeof functionStub.returnArgAt == 'number') {
return arguments[functionStub.returnArgAt];
} else if (functionStub.returnThis) {
return this;
}
return functionStub.returnValue;
};
functionStub.id = "stub#" + uuid++;
var orig = functionStub;
functionStub = sinon.spy.create(functionStub);
functionStub.func = orig;
functionStub.callArgAts = [];
functionStub.callbackArguments = [];
functionStub.callbackContexts = [];
functionStub.callArgProps = [];
sinon.extend(functionStub, stub);
functionStub._create = sinon.stub.create;
functionStub.displayName = "stub";
functionStub.toString = sinon.functionToString;
return functionStub;
},
resetBehavior: function () {
var i;
this.callArgAts = [];
this.callbackArguments = [];
this.callbackContexts = [];
this.callArgProps = [];
delete this.returnValue;
delete this.returnArgAt;
this.returnThis = false;
if (this.fakes) {
for (i = 0; i < this.fakes.length; i++) {
this.fakes[i].resetBehavior();
}
}
},
returns: function returns(value) {
this.returnValue = value;
return this;
},
returnsArg: function returnsArg(pos) {
if (typeof pos != "number") {
throw new TypeError("argument index is not number");
}
this.returnArgAt = pos;
return this;
},
returnsThis: function returnsThis() {
this.returnThis = true;
return this;
},
"throws": throwsException,
throwsException: throwsException,
callsArg: function callsArg(pos) {
if (typeof pos != "number") {
throw new TypeError("argument index is not number");
}
this.callArgAts.push(pos);
this.callbackArguments.push([]);
this.callbackContexts.push(undefined);
this.callArgProps.push(undefined);
return this;
},
callsArgOn: function callsArgOn(pos, context) {
if (typeof pos != "number") {
throw new TypeError("argument index is not number");
}
if (typeof context != "object") {
throw new TypeError("argument context is not an object");
}
this.callArgAts.push(pos);
this.callbackArguments.push([]);
this.callbackContexts.push(context);
this.callArgProps.push(undefined);
return this;
},
callsArgWith: function callsArgWith(pos) {
if (typeof pos != "number") {
throw new TypeError("argument index is not number");
}
this.callArgAts.push(pos);
this.callbackArguments.push(slice.call(arguments, 1));
this.callbackContexts.push(undefined);
this.callArgProps.push(undefined);
return this;
},
callsArgOnWith: function callsArgWith(pos, context) {
if (typeof pos != "number") {
throw new TypeError("argument index is not number");
}
if (typeof context != "object") {
throw new TypeError("argument context is not an object");
}
this.callArgAts.push(pos);
this.callbackArguments.push(slice.call(arguments, 2));
this.callbackContexts.push(context);
this.callArgProps.push(undefined);
return this;
},
yields: function () {
this.callArgAts.push(-1);
this.callbackArguments.push(slice.call(arguments, 0));
this.callbackContexts.push(undefined);
this.callArgProps.push(undefined);
return this;
},
yieldsOn: function (context) {
if (typeof context != "object") {
throw new TypeError("argument context is not an object");
}
this.callArgAts.push(-1);
this.callbackArguments.push(slice.call(arguments, 1));
this.callbackContexts.push(context);
this.callArgProps.push(undefined);
return this;
},
yieldsTo: function (prop) {
this.callArgAts.push(-1);
this.callbackArguments.push(slice.call(arguments, 1));
this.callbackContexts.push(undefined);
this.callArgProps.push(prop);
return this;
},
yieldsToOn: function (prop, context) {
if (typeof context != "object") {
throw new TypeError("argument context is not an object");
}
this.callArgAts.push(-1);
this.callbackArguments.push(slice.call(arguments, 2));
this.callbackContexts.push(context);
this.callArgProps.push(prop);
return this;
}
};
// create asynchronous versions of callsArg* and yields* methods
for (var method in proto) {
// need to avoid creating anotherasync versions of the newly added async methods
if (proto.hasOwnProperty(method) &&
method.match(/^(callsArg|yields|thenYields$)/) &&
!method.match(/Async/)) {
proto[method + 'Async'] = (function (syncFnName) {
return function () {
this.callbackAsync = true;
return this[syncFnName].apply(this, arguments);
};
})(method);
}
}
return proto;
}()));
if (commonJSModule) {
module.exports = stub;
} else {
sinon.stub = stub;
}
}(typeof sinon == "object" && sinon || null));
/**
* @depend ../sinon.js
* @depend stub.js
*/
/*jslint eqeqeq: false, onevar: false, nomen: false*/
/*global module, require, sinon*/
/**
* Mock functions.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function (sinon) {
var commonJSModule = typeof module == "object" && typeof require == "function";
var push = [].push;
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon) {
return;
}
function mock(object) {
if (!object) {
return sinon.expectation.create("Anonymous mock");
}
return mock.create(object);
}
sinon.mock = mock;
sinon.extend(mock, (function () {
function each(collection, callback) {
if (!collection) {
return;
}
for (var i = 0, l = collection.length; i < l; i += 1) {
callback(collection[i]);
}
}
return {
create: function create(object) {
if (!object) {
throw new TypeError("object is null");
}
var mockObject = sinon.extend({}, mock);
mockObject.object = object;
delete mockObject.create;
return mockObject;
},
expects: function expects(method) {
if (!method) {
throw new TypeError("method is falsy");
}
if (!this.expectations) {
this.expectations = {};
this.proxies = [];
}
if (!this.expectations[method]) {
this.expectations[method] = [];
var mockObject = this;
sinon.wrapMethod(this.object, method, function () {
return mockObject.invokeMethod(method, this, arguments);
});
push.call(this.proxies, method);
}
var expectation = sinon.expectation.create(method);
push.call(this.expectations[method], expectation);
return expectation;
},
restore: function restore() {
var object = this.object;
each(this.proxies, function (proxy) {
if (typeof object[proxy].restore == "function") {
object[proxy].restore();
}
});
},
verify: function verify() {
var expectations = this.expectations || {};
var messages = [], met = [];
each(this.proxies, function (proxy) {
each(expectations[proxy], function (expectation) {
if (!expectation.met()) {
push.call(messages, expectation.toString());
} else {
push.call(met, expectation.toString());
}
});
});
this.restore();
if (messages.length > 0) {
sinon.expectation.fail(messages.concat(met).join("\n"));
} else {
sinon.expectation.pass(messages.concat(met).join("\n"));
}
return true;
},
invokeMethod: function invokeMethod(method, thisValue, args) {
var expectations = this.expectations && this.expectations[method];
var length = expectations && expectations.length || 0, i;
for (i = 0; i < length; i += 1) {
if (!expectations[i].met() &&
expectations[i].allowsCall(thisValue, args)) {
return expectations[i].apply(thisValue, args);
}
}
var messages = [], available, exhausted = 0;
for (i = 0; i < length; i += 1) {
if (expectations[i].allowsCall(thisValue, args)) {
available = available || expectations[i];
} else {
exhausted += 1;
}
push.call(messages, " " + expectations[i].toString());
}
if (exhausted === 0) {
return available.apply(thisValue, args);
}
messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
proxy: method,
args: args
}));
sinon.expectation.fail(messages.join("\n"));
}
};
}()));
var times = sinon.timesInWords;
sinon.expectation = (function () {
var slice = Array.prototype.slice;
var _invoke = sinon.spy.invoke;
function callCountInWords(callCount) {
if (callCount == 0) {
return "never called";
} else {
return "called " + times(callCount);
}
}
function expectedCallCountInWords(expectation) {
var min = expectation.minCalls;
var max = expectation.maxCalls;
if (typeof min == "number" && typeof max == "number") {
var str = times(min);
if (min != max) {
str = "at least " + str + " and at most " + times(max);
}
return str;
}
if (typeof min == "number") {
return "at least " + times(min);
}
return "at most " + times(max);
}
function receivedMinCalls(expectation) {
var hasMinLimit = typeof expectation.minCalls == "number";
return !hasMinLimit || expectation.callCount >= expectation.minCalls;
}
function receivedMaxCalls(expectation) {
if (typeof expectation.maxCalls != "number") {
return false;
}
return expectation.callCount == expectation.maxCalls;
}
return {
minCalls: 1,
maxCalls: 1,
create: function create(methodName) {
var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
delete expectation.create;
expectation.method = methodName;
return expectation;
},
invoke: function invoke(func, thisValue, args) {
this.verifyCallAllowed(thisValue, args);
return _invoke.apply(this, arguments);
},
atLeast: function atLeast(num) {
if (typeof num != "number") {
throw new TypeError("'" + num + "' is not number");
}
if (!this.limitsSet) {
this.maxCalls = null;
this.limitsSet = true;
}
this.minCalls = num;
return this;
},
atMost: function atMost(num) {
if (typeof num != "number") {
throw new TypeError("'" + num + "' is not number");
}
if (!this.limitsSet) {
this.minCalls = null;
this.limitsSet = true;
}
this.maxCalls = num;
return this;
},
never: function never() {
return this.exactly(0);
},
once: function once() {
return this.exactly(1);
},
twice: function twice() {
return this.exactly(2);
},
thrice: function thrice() {
return this.exactly(3);
},
exactly: function exactly(num) {
if (typeof num != "number") {
throw new TypeError("'" + num + "' is not a number");
}
this.atLeast(num);
return this.atMost(num);
},
met: function met() {
return !this.failed && receivedMinCalls(this);
},
verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
if (receivedMaxCalls(this)) {
this.failed = true;
sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
}
if ("expectedThis" in this && this.expectedThis !== thisValue) {
sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
this.expectedThis);
}
if (!("expectedArguments" in this)) {
return;
}
if (!args) {
sinon.expectation.fail(this.method + " received no arguments, expected " +
sinon.format(this.expectedArguments));
}
if (args.length < this.expectedArguments.length) {
sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) +
"), expected " + sinon.format(this.expectedArguments));
}
if (this.expectsExactArgCount &&
args.length != this.expectedArguments.length) {
sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) +
"), expected " + sinon.format(this.expectedArguments));
}
for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
", expected " + sinon.format(this.expectedArguments));
}
}
},
allowsCall: function allowsCall(thisValue, args) {
if (this.met() && receivedMaxCalls(this)) {
return false;
}
if ("expectedThis" in this && this.expectedThis !== thisValue) {
return false;
}
if (!("expectedArguments" in this)) {
return true;
}
args = args || [];
if (args.length < this.expectedArguments.length) {
return false;
}
if (this.expectsExactArgCount &&
args.length != this.expectedArguments.length) {
return false;
}
for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
return false;
}
}
return true;
},
withArgs: function withArgs() {
this.expectedArguments = slice.call(arguments);
return this;
},
withExactArgs: function withExactArgs() {
this.withArgs.apply(this, arguments);
this.expectsExactArgCount = true;
return this;
},
on: function on(thisValue) {
this.expectedThis = thisValue;
return this;
},
toString: function () {
var args = (this.expectedArguments || []).slice();
if (!this.expectsExactArgCount) {
push.call(args, "[...]");
}
var callStr = sinon.spyCall.toString.call({
proxy: this.method || "anonymous mock expectation",
args: args
});
var message = callStr.replace(", [...", "[, ...") + " " +
expectedCallCountInWords(this);
if (this.met()) {
return "Expectation met: " + message;
}
return "Expected " + message + " (" +
callCountInWords(this.callCount) + ")";
},
verify: function verify() {
if (!this.met()) {
sinon.expectation.fail(this.toString());
} else {
sinon.expectation.pass(this.toString());
}
return true;
},
pass: function(message) {
sinon.assert.pass(message);
},
fail: function (message) {
var exception = new Error(message);
exception.name = "ExpectationError";
throw exception;
}
};
}());
if (commonJSModule) {
module.exports = mock;
} else {
sinon.mock = mock;
}
}(typeof sinon == "object" && sinon || null));
/**
* @depend ../sinon.js
* @depend stub.js
* @depend mock.js
*/
/*jslint eqeqeq: false, onevar: false, forin: true*/
/*global module, require, sinon*/
/**
* Collections of stubs, spies and mocks.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function (sinon) {
var commonJSModule = typeof module == "object" && typeof require == "function";
var push = [].push;
var hasOwnProperty = Object.prototype.hasOwnProperty;
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon) {
return;
}
function getFakes(fakeCollection) {
if (!fakeCollection.fakes) {
fakeCollection.fakes = [];
}
return fakeCollection.fakes;
}
function each(fakeCollection, method) {
var fakes = getFakes(fakeCollection);
for (var i = 0, l = fakes.length; i < l; i += 1) {
if (typeof fakes[i][method] == "function") {
fakes[i][method]();
}
}
}
function compact(fakeCollection) {
var fakes = getFakes(fakeCollection);
var i = 0;
while (i < fakes.length) {
fakes.splice(i, 1);
}
}
var collection = {
verify: function resolve() {
each(this, "verify");
},
restore: function restore() {
each(this, "restore");
compact(this);
},
verifyAndRestore: function verifyAndRestore() {
var exception;
try {
this.verify();
} catch (e) {
exception = e;
}
this.restore();
if (exception) {
throw exception;
}
},
add: function add(fake) {
push.call(getFakes(this), fake);
return fake;
},
spy: function spy() {
return this.add(sinon.spy.apply(sinon, arguments));
},
stub: function stub(object, property, value) {
if (property) {
var original = object[property];
if (typeof original != "function") {
if (!hasOwnProperty.call(object, property)) {
throw new TypeError("Cannot stub non-existent own property " + property);
}
object[property] = value;
return this.add({
restore: function () {
object[property] = original;
}
});
}
}
if (!property && !!object && typeof object == "object") {
var stubbedObj = sinon.stub.apply(sinon, arguments);
for (var prop in stubbedObj) {
if (typeof stubbedObj[prop] === "function") {
this.add(stubbedObj[prop]);
}
}
return stubbedObj;
}
return this.add(sinon.stub.apply(sinon, arguments));
},
mock: function mock() {
return this.add(sinon.mock.apply(sinon, arguments));
},
inject: function inject(obj) {
var col = this;
obj.spy = function () {
return col.spy.apply(col, arguments);
};
obj.stub = function () {
return col.stub.apply(col, arguments);
};
obj.mock = function () {
return col.mock.apply(col, arguments);
};
return obj;
}
};
if (commonJSModule) {
module.exports = collection;
} else {
sinon.collection = collection;
}
}(typeof sinon == "object" && sinon || null));
/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
/*global module, require, window*/
/**
* Fake timer API
* setTimeout
* setInterval
* clearTimeout
* clearInterval
* tick
* reset
* Date
*
* Inspired by jsUnitMockTimeOut from JsUnit
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
if (typeof sinon == "undefined") {
var sinon = {};
}
(function (global) {
var id = 1;
function addTimer(args, recurring) {
if (args.length === 0) {
throw new Error("Function requires at least 1 parameter");
}
var toId = id++;
var delay = args[1] || 0;
if (!this.timeouts) {
this.timeouts = {};
}
this.timeouts[toId] = {
id: toId,
func: args[0],
callAt: this.now + delay,
invokeArgs: Array.prototype.slice.call(args, 2)
};
if (recurring === true) {
this.timeouts[toId].interval = delay;
}
return toId;
}
function parseTime(str) {
if (!str) {
return 0;
}
var strings = str.split(":");
var l = strings.length, i = l;
var ms = 0, parsed;
if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
throw new Error("tick only understands numbers and 'h:m:s'");
}
while (i--) {
parsed = parseInt(strings[i], 10);
if (parsed >= 60) {
throw new Error("Invalid time " + str);
}
ms += parsed * Math.pow(60, (l - i - 1));
}
return ms * 1000;
}
function createObject(object) {
var newObject;
if (Object.create) {
newObject = Object.create(object);
} else {
var F = function () {};
F.prototype = object;
newObject = new F();
}
newObject.Date.clock = newObject;
return newObject;
}
sinon.clock = {
now: 0,
create: function create(now) {
var clock = createObject(this);
if (typeof now == "number") {
clock.now = now;
}
if (!!now && typeof now == "object") {
throw new TypeError("now should be milliseconds since UNIX epoch");
}
return clock;
},
setTimeout: function setTimeout(callback, timeout) {
return addTimer.call(this, arguments, false);
},
clearTimeout: function clearTimeout(timerId) {
if (!this.timeouts) {
this.timeouts = [];
}
if (timerId in this.timeouts) {
delete this.timeouts[timerId];
}
},
setInterval: function setInterval(callback, timeout) {
return addTimer.call(this, arguments, true);
},
clearInterval: function clearInterval(timerId) {
this.clearTimeout(timerId);
},
tick: function tick(ms) {
ms = typeof ms == "number" ? ms : parseTime(ms);
var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
var timer = this.firstTimerInRange(tickFrom, tickTo);
var firstException;
while (timer && tickFrom <= tickTo) {
if (this.timeouts[timer.id]) {
tickFrom = this.now = timer.callAt;
try {
this.callTimer(timer);
} catch (e) {
firstException = firstException || e;
}
}
timer = this.firstTimerInRange(previous, tickTo);
previous = tickFrom;
}
this.now = tickTo;
if (firstException) {
throw firstException;
}
return this.now;
},
firstTimerInRange: function (from, to) {
var timer, smallest, originalTimer;
for (var id in this.timeouts) {
if (this.timeouts.hasOwnProperty(id)) {
if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
continue;
}
if (!smallest || this.timeouts[id].callAt < smallest) {
originalTimer = this.timeouts[id];
smallest = this.timeouts[id].callAt;
timer = {
func: this.timeouts[id].func,
callAt: this.timeouts[id].callAt,
interval: this.timeouts[id].interval,
id: this.timeouts[id].id,
invokeArgs: this.timeouts[id].invokeArgs
};
}
}
}
return timer || null;
},
callTimer: function (timer) {
if (typeof timer.interval == "number") {
this.timeouts[timer.id].callAt += timer.interval;
} else {
delete this.timeouts[timer.id];
}
try {
if (typeof timer.func == "function") {
timer.func.apply(null, timer.invokeArgs);
} else {
eval(timer.func);
}
} catch (e) {
var exception = e;
}
if (!this.timeouts[timer.id]) {
if (exception) {
throw exception;
}
return;
}
if (exception) {
throw exception;
}
},
reset: function reset() {
this.timeouts = {};
},
Date: (function () {
var NativeDate = Date;
function ClockDate(year, month, date, hour, minute, second, ms) {
// Defensive and verbose to avoid potential harm in passing
// explicit undefined when user does not pass argument
switch (arguments.length) {
case 0:
return new NativeDate(ClockDate.clock.now);
case 1:
return new NativeDate(year);
case 2:
return new NativeDate(year, month);
case 3:
return new NativeDate(year, month, date);
case 4:
return new NativeDate(year, month, date, hour);
case 5:
return new NativeDate(year, month, date, hour, minute);
case 6:
return new NativeDate(year, month, date, hour, minute, second);
default:
return new NativeDate(year, month, date, hour, minute, second, ms);
}
}
return mirrorDateProperties(ClockDate, NativeDate);
}())
};
function mirrorDateProperties(target, source) {
if (source.now) {
target.now = function now() {
return target.clock.now;
};
} else {
delete target.now;
}
if (source.toSource) {
target.toSource = function toSource() {
return source.toSource();
};
} else {
delete target.toSource;
}
target.toString = function toString() {
return source.toString();
};
target.prototype = source.prototype;
target.parse = source.parse;
target.UTC = source.UTC;
target.prototype.toUTCString = source.prototype.toUTCString;
return target;
}
var methods = ["Date", "setTimeout", "setInterval",
"clearTimeout", "clearInterval"];
function restore() {
var method;
for (var i = 0, l = this.methods.length; i < l; i++) {
method = this.methods[i];
if (global[method].hadOwnProperty) {
global[method] = this["_" + method];
} else {
delete global[method];
}
}
// Prevent multiple executions which will completely remove these props
this.methods = [];
}
function stubGlobal(method, clock) {
clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
clock["_" + method] = global[method];
if (method == "Date") {
var date = mirrorDateProperties(clock[method], global[method]);
global[method] = date;
} else {
global[method] = function () {
return clock[method].apply(clock, arguments);
};
for (var prop in clock[method]) {
if (clock[method].hasOwnProperty(prop)) {
global[method][prop] = clock[method][prop];
}
}
}
global[method].clock = clock;
}
sinon.useFakeTimers = function useFakeTimers(now) {
var clock = sinon.clock.create(now);
clock.restore = restore;
clock.methods = Array.prototype.slice.call(arguments,
typeof now == "number" ? 1 : 0);
if (clock.methods.length === 0) {
clock.methods = methods;
}
for (var i = 0, l = clock.methods.length; i < l; i++) {
stubGlobal(clock.methods[i], clock);
}
return clock;
};
}(typeof global != "undefined" && typeof global !== "function" ? global : this));
sinon.timers = {
setTimeout: setTimeout,
clearTimeout: clearTimeout,
setInterval: setInterval,
clearInterval: clearInterval,
Date: Date
};
if (typeof module == "object" && typeof require == "function") {
module.exports = sinon;
}
/*jslint eqeqeq: false, onevar: false*/
/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
/**
* Minimal Event interface implementation
*
* Original implementation by Sven Fuchs: https://gist.github.com/995028
* Modifications and tests by Christian Johansen.
*
* @author Sven Fuchs (svenfuchs@artweb-design.de)
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2011 Sven Fuchs, Christian Johansen
*/
if (typeof sinon == "undefined") {
this.sinon = {};
}
(function () {
var push = [].push;
sinon.Event = function Event(type, bubbles, cancelable) {
this.initEvent(type, bubbles, cancelable);
};
sinon.Event.prototype = {
initEvent: function(type, bubbles, cancelable) {
this.type = type;
this.bubbles = bubbles;
this.cancelable = cancelable;
},
stopPropagation: function () {},
preventDefault: function () {
this.defaultPrevented = true;
}
};
sinon.EventTarget = {
addEventListener: function addEventListener(event, listener, useCapture) {
this.eventListeners = this.eventListeners || {};
this.eventListeners[event] = this.eventListeners[event] || [];
push.call(this.eventListeners[event], listener);
},
removeEventListener: function removeEventListener(event, listener, useCapture) {
var listeners = this.eventListeners && this.eventListeners[event] || [];
for (var i = 0, l = listeners.length; i < l; ++i) {
if (listeners[i] == listener) {
return listeners.splice(i, 1);
}
}
},
dispatchEvent: function dispatchEvent(event) {
var type = event.type;
var listeners = this.eventListeners && this.eventListeners[type] || [];
for (var i = 0; i < listeners.length; i++) {
if (typeof listeners[i] == "function") {
listeners[i].call(this, event);
} else {
listeners[i].handleEvent(event);
}
}
return !!event.defaultPrevented;
}
};
}());
/**
* @depend ../../sinon.js
* @depend event.js
*/
/*jslint eqeqeq: false, onevar: false*/
/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
/**
* Fake XMLHttpRequest object
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
if (typeof sinon == "undefined") {
this.sinon = {};
}
sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest };
// wrapper for global
(function(global) {
var xhr = sinon.xhr;
xhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
xhr.GlobalActiveXObject = global.ActiveXObject;
xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined";
xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined";
xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX
? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
/*jsl:ignore*/
var unsafeHeaders = {
"Accept-Charset": true,
"Accept-Encoding": true,
"Connection": true,
"Content-Length": true,
"Cookie": true,
"Cookie2": true,
"Content-Transfer-Encoding": true,
"Date": true,
"Expect": true,
"Host": true,
"Keep-Alive": true,
"Referer": true,
"TE": true,
"Trailer": true,
"Transfer-Encoding": true,
"Upgrade": true,
"User-Agent": true,
"Via": true
};
/*jsl:end*/
function FakeXMLHttpRequest() {
this.readyState = FakeXMLHttpRequest.UNSENT;
this.requestHeaders = {};
this.requestBody = null;
this.status = 0;
this.statusText = "";
if (typeof FakeXMLHttpRequest.onCreate == "function") {
FakeXMLHttpRequest.onCreate(this);
}
}
function verifyState(xhr) {
if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
throw new Error("INVALID_STATE_ERR");
}
if (xhr.sendFlag) {
throw new Error("INVALID_STATE_ERR");
}
}
// filtering to enable a white-list version of Sinon FakeXhr,
// where whitelisted requests are passed through to real XHR
function each(collection, callback) {
if (!collection) return;
for (var i = 0, l = collection.length; i < l; i += 1) {
callback(collection[i]);
}
}
function some(collection, callback) {
for (var index = 0; index < collection.length; index++) {
if(callback(collection[index]) === true) return true;
};
return false;
}
// largest arity in XHR is 5 - XHR#open
var apply = function(obj,method,args) {
switch(args.length) {
case 0: return obj[method]();
case 1: return obj[method](args[0]);
case 2: return obj[method](args[0],args[1]);
case 3: return obj[method](args[0],args[1],args[2]);
case 4: return obj[method](args[0],args[1],args[2],args[3]);
case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]);
};
};
FakeXMLHttpRequest.filters = [];
FakeXMLHttpRequest.addFilter = function(fn) {
this.filters.push(fn)
};
var IE6Re = /MSIE 6/;
FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) {
var xhr = new sinon.xhr.workingXHR();
each(["open","setRequestHeader","send","abort","getResponseHeader",
"getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"],
function(method) {
fakeXhr[method] = function() {
return apply(xhr,method,arguments);
};
});
var copyAttrs = function(args) {
each(args, function(attr) {
try {
fakeXhr[attr] = xhr[attr]
} catch(e) {
if(!IE6Re.test(navigator.userAgent)) throw e;
}
});
};
var stateChange = function() {
fakeXhr.readyState = xhr.readyState;
if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
copyAttrs(["status","statusText"]);
}
if(xhr.readyState >= FakeXMLHttpRequest.LOADING) {
copyAttrs(["responseText"]);
}
if(xhr.readyState === FakeXMLHttpRequest.DONE) {
copyAttrs(["responseXML"]);
}
if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr);
};
if(xhr.addEventListener) {
for(var event in fakeXhr.eventListeners) {
if(fakeXhr.eventListeners.hasOwnProperty(event)) {
each(fakeXhr.eventListeners[event],function(handler) {
xhr.addEventListener(event, handler);
});
}
}
xhr.addEventListener("readystatechange",stateChange);
} else {
xhr.onreadystatechange = stateChange;
}
apply(xhr,"open",xhrArgs);
};
FakeXMLHttpRequest.useFilters = false;
function verifyRequestSent(xhr) {
if (xhr.readyState == FakeXMLHttpRequest.DONE) {
throw new Error("Request done");
}
}
function verifyHeadersReceived(xhr) {
if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
throw new Error("No headers received");
}
}
function verifyResponseBodyType(body) {
if (typeof body != "string") {
var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
body + ", which is not a string.");
error.name = "InvalidBodyException";
throw error;
}
}
sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
async: true,
open: function open(method, url, async, username, password) {
this.method = method;
this.url = url;
this.async = typeof async == "boolean" ? async : true;
this.username = username;
this.password = password;
this.responseText = null;
this.responseXML = null;
this.requestHeaders = {};
this.sendFlag = false;
if(sinon.FakeXMLHttpRequest.useFilters === true) {
var xhrArgs = arguments;
var defake = some(FakeXMLHttpRequest.filters,function(filter) {
return filter.apply(this,xhrArgs)
});
if (defake) {
return sinon.FakeXMLHttpRequest.defake(this,arguments);
}
}
this.readyStateChange(FakeXMLHttpRequest.OPENED);
},
readyStateChange: function readyStateChange(state) {
this.readyState = state;
if (typeof this.onreadystatechange == "function") {
try {
this.onreadystatechange();
} catch (e) {
sinon.logError("Fake XHR onreadystatechange handler", e);
}
}
this.dispatchEvent(new sinon.Event("readystatechange"));
},
setRequestHeader: function setRequestHeader(header, value) {
verifyState(this);
if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
throw new Error("Refused to set unsafe header \"" + header + "\"");
}
if (this.requestHeaders[header]) {
this.requestHeaders[header] += "," + value;
} else {
this.requestHeaders[header] = value;
}
},
// Helps testing
setResponseHeaders: function setResponseHeaders(headers) {
this.responseHeaders = {};
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
this.responseHeaders[header] = headers[header];
}
}
if (this.async) {
this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
} else {
this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
}
},
// Currently treats ALL data as a DOMString (i.e. no Document)
send: function send(data) {
verifyState(this);
if (!/^(get|head)$/i.test(this.method)) {
if (this.requestHeaders["Content-Type"]) {
var value = this.requestHeaders["Content-Type"].split(";");
this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8";
} else {
this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
}
this.requestBody = data;
}
this.errorFlag = false;
this.sendFlag = this.async;
this.readyStateChange(FakeXMLHttpRequest.OPENED);
if (typeof this.onSend == "function") {
this.onSend(this);
}
},
abort: function abort() {
this.aborted = true;
this.responseText = null;
this.errorFlag = true;
this.requestHeaders = {};
if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) {
this.readyStateChange(sinon.FakeXMLHttpRequest.DONE);
this.sendFlag = false;
}
this.readyState = sinon.FakeXMLHttpRequest.UNSENT;
},
getResponseHeader: function getResponseHeader(header) {
if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
return null;
}
if (/^Set-Cookie2?$/i.test(header)) {
return null;
}
header = header.toLowerCase();
for (var h in this.responseHeaders) {
if (h.toLowerCase() == header) {
return this.responseHeaders[h];
}
}
return null;
},
getAllResponseHeaders: function getAllResponseHeaders() {
if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
return "";
}
var headers = "";
for (var header in this.responseHeaders) {
if (this.responseHeaders.hasOwnProperty(header) &&
!/^Set-Cookie2?$/i.test(header)) {
headers += header + ": " + this.responseHeaders[header] + "\r\n";
}
}
return headers;
},
setResponseBody: function setResponseBody(body) {
verifyRequestSent(this);
verifyHeadersReceived(this);
verifyResponseBodyType(body);
var chunkSize = this.chunkSize || 10;
var index = 0;
this.responseText = "";
do {
if (this.async) {
this.readyStateChange(FakeXMLHttpRequest.LOADING);
}
this.responseText += body.substring(index, index + chunkSize);
index += chunkSize;
} while (index < body.length);
var type = this.getResponseHeader("Content-Type");
if (this.responseText &&
(!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
try {
this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
} catch (e) {
// Unable to parse XML - no biggie
}
}
if (this.async) {
this.readyStateChange(FakeXMLHttpRequest.DONE);
} else {
this.readyState = FakeXMLHttpRequest.DONE;
}
},
respond: function respond(status, headers, body) {
this.setResponseHeaders(headers || {});
this.status = typeof status == "number" ? status : 200;
this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
this.setResponseBody(body || "");
}
});
sinon.extend(FakeXMLHttpRequest, {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
});
// Borrowed from JSpec
FakeXMLHttpRequest.parseXML = function parseXML(text) {
var xmlDoc;
if (typeof DOMParser != "undefined") {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
} else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(text);
}
return xmlDoc;
};
FakeXMLHttpRequest.statusCodes = {
100: "Continue",
101: "Switching Protocols",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
300: "Multiple Choice",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Request Entity Too Large",
414: "Request-URI Too Long",
415: "Unsupported Media Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
422: "Unprocessable Entity",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported"
};
sinon.useFakeXMLHttpRequest = function () {
sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
if (xhr.supportsXHR) {
global.XMLHttpRequest = xhr.GlobalXMLHttpRequest;
}
if (xhr.supportsActiveX) {
global.ActiveXObject = xhr.GlobalActiveXObject;
}
delete sinon.FakeXMLHttpRequest.restore;
if (keepOnCreate !== true) {
delete sinon.FakeXMLHttpRequest.onCreate;
}
};
if (xhr.supportsXHR) {
global.XMLHttpRequest = sinon.FakeXMLHttpRequest;
}
if (xhr.supportsActiveX) {
global.ActiveXObject = function ActiveXObject(objId) {
if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
return new sinon.FakeXMLHttpRequest();
}
return new xhr.GlobalActiveXObject(objId);
};
}
return sinon.FakeXMLHttpRequest;
};
sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
})(this);
if (typeof module == "object" && typeof require == "function") {
module.exports = sinon;
}
/**
* @depend fake_xml_http_request.js
*/
/*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/
/*global module, require, window*/
/**
* The Sinon "server" mimics a web server that receives requests from
* sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
* both synchronously and asynchronously. To respond synchronuously, canned
* answers have to be provided upfront.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
if (typeof sinon == "undefined") {
var sinon = {};
}
sinon.fakeServer = (function () {
var push = [].push;
function F() {}
function create(proto) {
F.prototype = proto;
return new F();
}
function responseArray(handler) {
var response = handler;
if (Object.prototype.toString.call(handler) != "[object Array]") {
response = [200, {}, handler];
}
if (typeof response[2] != "string") {
throw new TypeError("Fake server response body should be string, but was " +
typeof response[2]);
}
return response;
}
var wloc = typeof window !== "undefined" ? window.location : {};
var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
function matchOne(response, reqMethod, reqUrl) {
var rmeth = response.method;
var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
var url = response.url;
var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
return matchMethod && matchUrl;
}
function match(response, request) {
var requestMethod = this.getHTTPMethod(request);
var requestUrl = request.url;
if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
requestUrl = requestUrl.replace(rCurrLoc, "");
}
if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
if (typeof response.response == "function") {
var ru = response.url;
var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1));
return response.response.apply(response, args);
}
return true;
}
return false;
}
function log(response, request) {
var str;
str = "Request:\n" + sinon.format(request) + "\n\n";
str += "Response:\n" + sinon.format(response) + "\n\n";
sinon.log(str);
}
return {
create: function () {
var server = create(this);
this.xhr = sinon.useFakeXMLHttpRequest();
server.requests = [];
this.xhr.onCreate = function (xhrObj) {
server.addRequest(xhrObj);
};
return server;
},
addRequest: function addRequest(xhrObj) {
var server = this;
push.call(this.requests, xhrObj);
xhrObj.onSend = function () {
server.handleRequest(this);
};
if (this.autoRespond && !this.responding) {
setTimeout(function () {
server.responding = false;
server.respond();
}, this.autoRespondAfter || 10);
this.responding = true;
}
},
getHTTPMethod: function getHTTPMethod(request) {
if (this.fakeHTTPMethods && /post/i.test(request.method)) {
var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
return !!matches ? matches[1] : request.method;
}
return request.method;
},
handleRequest: function handleRequest(xhr) {
if (xhr.async) {
if (!this.queue) {
this.queue = [];
}
push.call(this.queue, xhr);
} else {
this.processRequest(xhr);
}
},
respondWith: function respondWith(method, url, body) {
if (arguments.length == 1 && typeof method != "function") {
this.response = responseArray(method);
return;
}
if (!this.responses) { this.responses = []; }
if (arguments.length == 1) {
body = method;
url = method = null;
}
if (arguments.length == 2) {
body = url;
url = method;
method = null;
}
push.call(this.responses, {
method: method,
url: url,
response: typeof body == "function" ? body : responseArray(body)
});
},
respond: function respond() {
if (arguments.length > 0) this.respondWith.apply(this, arguments);
var queue = this.queue || [];
var request;
while(request = queue.shift()) {
this.processRequest(request);
}
},
processRequest: function processRequest(request) {
try {
if (request.aborted) {
return;
}
var response = this.response || [404, {}, ""];
if (this.responses) {
for (var i = 0, l = this.responses.length; i < l; i++) {
if (match.call(this, this.responses[i], request)) {
response = this.responses[i].response;
break;
}
}
}
if (request.readyState != 4) {
log(response, request);
request.respond(response[0], response[1], response[2]);
}
} catch (e) {
sinon.logError("Fake server request processing", e);
}
},
restore: function restore() {
return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
}
};
}());
if (typeof module == "object" && typeof require == "function") {
module.exports = sinon;
}
/**
* @depend fake_server.js
* @depend fake_timers.js
*/
/*jslint browser: true, eqeqeq: false, onevar: false*/
/*global sinon*/
/**
* Add-on for sinon.fakeServer that automatically handles a fake timer along with
* the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
* 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
* it polls the object for completion with setInterval. Dispite the direct
* motivation, there is nothing jQuery-specific in this file, so it can be used
* in any environment where the ajax implementation depends on setInterval or
* setTimeout.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function () {
function Server() {}
Server.prototype = sinon.fakeServer;
sinon.fakeServerWithClock = new Server();
sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
if (xhr.async) {
if (typeof setTimeout.clock == "object") {
this.clock = setTimeout.clock;
} else {
this.clock = sinon.useFakeTimers();
this.resetClock = true;
}
if (!this.longestTimeout) {
var clockSetTimeout = this.clock.setTimeout;
var clockSetInterval = this.clock.setInterval;
var server = this;
this.clock.setTimeout = function (fn, timeout) {
server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
return clockSetTimeout.apply(this, arguments);
};
this.clock.setInterval = function (fn, timeout) {
server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
return clockSetInterval.apply(this, arguments);
};
}
}
return sinon.fakeServer.addRequest.call(this, xhr);
};
sinon.fakeServerWithClock.respond = function respond() {
var returnVal = sinon.fakeServer.respond.apply(this, arguments);
if (this.clock) {
this.clock.tick(this.longestTimeout || 0);
this.longestTimeout = 0;
if (this.resetClock) {
this.clock.restore();
this.resetClock = false;
}
}
return returnVal;
};
sinon.fakeServerWithClock.restore = function restore() {
if (this.clock) {
this.clock.restore();
}
return sinon.fakeServer.restore.apply(this, arguments);
};
}());
/**
* @depend ../sinon.js
* @depend collection.js
* @depend util/fake_timers.js
* @depend util/fake_server_with_clock.js
*/
/*jslint eqeqeq: false, onevar: false, plusplus: false*/
/*global require, module*/
/**
* Manages fake collections as well as fake utilities such as Sinon's
* timers and fake XHR implementation in one convenient object.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
if (typeof module == "object" && typeof require == "function") {
var sinon = require("../sinon");
sinon.extend(sinon, require("./util/fake_timers"));
}
(function () {
var push = [].push;
function exposeValue(sandbox, config, key, value) {
if (!value) {
return;
}
if (config.injectInto) {
config.injectInto[key] = value;
} else {
push.call(sandbox.args, value);
}
}
function prepareSandboxFromConfig(config) {
var sandbox = sinon.create(sinon.sandbox);
if (config.useFakeServer) {
if (typeof config.useFakeServer == "object") {
sandbox.serverPrototype = config.useFakeServer;
}
sandbox.useFakeServer();
}
if (config.useFakeTimers) {
if (typeof config.useFakeTimers == "object") {
sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
} else {
sandbox.useFakeTimers();
}
}
return sandbox;
}
sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
useFakeTimers: function useFakeTimers() {
this.clock = sinon.useFakeTimers.apply(sinon, arguments);
return this.add(this.clock);
},
serverPrototype: sinon.fakeServer,
useFakeServer: function useFakeServer() {
var proto = this.serverPrototype || sinon.fakeServer;
if (!proto || !proto.create) {
return null;
}
this.server = proto.create();
return this.add(this.server);
},
inject: function (obj) {
sinon.collection.inject.call(this, obj);
if (this.clock) {
obj.clock = this.clock;
}
if (this.server) {
obj.server = this.server;
obj.requests = this.server.requests;
}
return obj;
},
create: function (config) {
if (!config) {
return sinon.create(sinon.sandbox);
}
var sandbox = prepareSandboxFromConfig(config);
sandbox.args = sandbox.args || [];
var prop, value, exposed = sandbox.inject({});
if (config.properties) {
for (var i = 0, l = config.properties.length; i < l; i++) {
prop = config.properties[i];
value = exposed[prop] || prop == "sandbox" && sandbox;
exposeValue(sandbox, config, prop, value);
}
} else {
exposeValue(sandbox, config, "sandbox", value);
}
return sandbox;
}
});
sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
if (typeof module == "object" && typeof require == "function") {
module.exports = sinon.sandbox;
}
}());
/**
* @depend ../sinon.js
* @depend stub.js
* @depend mock.js
* @depend sandbox.js
*/
/*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/
/*global module, require, sinon*/
/**
* Test function, sandboxes fakes
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function (sinon) {
var commonJSModule = typeof module == "object" && typeof require == "function";
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon) {
return;
}
function test(callback) {
var type = typeof callback;
if (type != "function") {
throw new TypeError("sinon.test needs to wrap a test function, got " + type);
}
return function () {
var config = sinon.getConfig(sinon.config);
config.injectInto = config.injectIntoThis && this || config.injectInto;
var sandbox = sinon.sandbox.create(config);
var exception, result;
var args = Array.prototype.slice.call(arguments).concat(sandbox.args);
try {
result = callback.apply(this, args);
} catch (e) {
exception = e;
}
if (typeof exception !== "undefined") {
sandbox.restore();
throw exception;
}
else {
sandbox.verifyAndRestore();
}
return result;
};
}
test.config = {
injectIntoThis: true,
injectInto: null,
properties: ["spy", "stub", "mock", "clock", "server", "requests"],
useFakeTimers: true,
useFakeServer: true
};
if (commonJSModule) {
module.exports = test;
} else {
sinon.test = test;
}
}(typeof sinon == "object" && sinon || null));
/**
* @depend ../sinon.js
* @depend test.js
*/
/*jslint eqeqeq: false, onevar: false, eqeqeq: false*/
/*global module, require, sinon*/
/**
* Test case, sandboxes all test functions
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function (sinon) {
var commonJSModule = typeof module == "object" && typeof require == "function";
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon || !Object.prototype.hasOwnProperty) {
return;
}
function createTest(property, setUp, tearDown) {
return function () {
if (setUp) {
setUp.apply(this, arguments);
}
var exception, result;
try {
result = property.apply(this, arguments);
} catch (e) {
exception = e;
}
if (tearDown) {
tearDown.apply(this, arguments);
}
if (exception) {
throw exception;
}
return result;
};
}
function testCase(tests, prefix) {
/*jsl:ignore*/
if (!tests || typeof tests != "object") {
throw new TypeError("sinon.testCase needs an object with test functions");
}
/*jsl:end*/
prefix = prefix || "test";
var rPrefix = new RegExp("^" + prefix);
var methods = {}, testName, property, method;
var setUp = tests.setUp;
var tearDown = tests.tearDown;
for (testName in tests) {
if (tests.hasOwnProperty(testName)) {
property = tests[testName];
if (/^(setUp|tearDown)$/.test(testName)) {
continue;
}
if (typeof property == "function" && rPrefix.test(testName)) {
method = property;
if (setUp || tearDown) {
method = createTest(property, setUp, tearDown);
}
methods[testName] = sinon.test(method);
} else {
methods[testName] = tests[testName];
}
}
}
return methods;
}
if (commonJSModule) {
module.exports = testCase;
} else {
sinon.testCase = testCase;
}
}(typeof sinon == "object" && sinon || null));
/**
* @depend ../sinon.js
* @depend stub.js
*/
/*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/
/*global module, require, sinon*/
/**
* Assertions matching the test spy retrieval interface.
*
* @author Christian Johansen (christian@cjohansen.no)
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
(function (sinon, global) {
var commonJSModule = typeof module == "object" && typeof require == "function";
var slice = Array.prototype.slice;
var assert;
if (!sinon && commonJSModule) {
sinon = require("../sinon");
}
if (!sinon) {
return;
}
function verifyIsStub() {
var method;
for (var i = 0, l = arguments.length; i < l; ++i) {
method = arguments[i];
if (!method) {
assert.fail("fake is not a spy");
}
if (typeof method != "function") {
assert.fail(method + " is not a function");
}
if (typeof method.getCall != "function") {
assert.fail(method + " is not stubbed");
}
}
}
function failAssertion(object, msg) {
object = object || global;
var failMethod = object.fail || assert.fail;
failMethod.call(object, msg);
}
function mirrorPropAsAssertion(name, method, message) {
if (arguments.length == 2) {
message = method;
method = name;
}
assert[name] = function (fake) {
verifyIsStub(fake);
var args = slice.call(arguments, 1);
var failed = false;
if (typeof method == "function") {
failed = !method(fake);
} else {
failed = typeof fake[method] == "function" ?
!fake[method].apply(fake, args) : !fake[method];
}
if (failed) {
failAssertion(this, fake.printf.apply(fake, [message].concat(args)));
} else {
assert.pass(name);
}
};
}
function exposedName(prefix, prop) {
return !prefix || /^fail/.test(prop) ? prop :
prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
};
assert = {
failException: "AssertError",
fail: function fail(message) {
var error = new Error(message);
error.name = this.failException || assert.failException;
throw error;
},
pass: function pass(assertion) {},
callOrder: function assertCallOrder() {
verifyIsStub.apply(null, arguments);
var expected = "", actual = "";
if (!sinon.calledInOrder(arguments)) {
try {
expected = [].join.call(arguments, ", ");
actual = sinon.orderByFirstCall(slice.call(arguments)).join(", ");
} catch (e) {
// If this fails, we'll just fall back to the blank string
}
failAssertion(this, "expected " + expected + " to be " +
"called in order but were called as " + actual);
} else {
assert.pass("callOrder");
}
},
callCount: function assertCallCount(method, count) {
verifyIsStub(method);
if (method.callCount != count) {
var msg = "expected %n to be called " + sinon.timesInWords(count) +
" but was called %c%C";
failAssertion(this, method.printf(msg));
} else {
assert.pass("callCount");
}
},
expose: function expose(target, options) {
if (!target) {
throw new TypeError("target is null or undefined");
}
var o = options || {};
var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
for (var method in this) {
if (method != "export" && (includeFail || !/^(fail)/.test(method))) {
target[exposedName(prefix, method)] = this[method];
}
}
return target;
}
};
mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
"expected %n to not have been called but was called %c%C");
mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
mirrorPropAsAssertion("threw", "%n did not throw exception%C");
mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
if (commonJSModule) {
module.exports = assert;
} else {
sinon.assert = assert;
}
}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : global));
return sinon;}.call(typeof window != 'undefined' && window || {})); |
onway.Models.User = Backbone.Model.extend({
/*url:'[la url que va a estar relacionada con el servidor]'*/
});
|
search_result['1101']=["topic_0000000000000288.html","tlece_ApplicantProfileVideos.ThumbnailUrl Property",""]; |
$(function () {
<<<<<<< HEAD
module('modal')
test('should provide no conflict', function () {
var modal = $.fn.modal.noConflict()
ok(!$.fn.modal, 'modal was set back to undefined (org value)')
$.fn.modal = modal
})
test('should be defined on jquery object', function () {
var div = $('<div id="modal-test"></div>')
ok(div.modal, 'modal method is defined')
})
test('should return element', function () {
var div = $('<div id="modal-test"></div>')
ok(div.modal() == div, 'document.body returned')
$('#modal-test').remove()
})
test('should expose defaults var for settings', function () {
ok($.fn.modal.Constructor.DEFAULTS, 'default object exposed')
})
test('should insert into dom when show method is called', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('shown.bs.modal', function () {
ok($('#modal-test').length, 'modal inserted into dom')
$(this).remove()
start()
})
.modal('show')
})
test('should fire show event', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('show.bs.modal', function () {
ok(true, 'show was called')
})
.on('shown.bs.modal', function () {
$(this).remove()
start()
})
.modal('show')
})
test('should not fire shown when default prevented', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('show.bs.modal', function (e) {
e.preventDefault()
ok(true, 'show was called')
start()
})
.on('shown.bs.modal', function () {
ok(false, 'shown was called')
})
.modal('show')
})
test('should hide modal when hide is called', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
ok($('#modal-test').length, 'modal inserted into dom')
$(this).modal('hide')
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
$('#modal-test').remove()
start()
})
.modal('show')
})
test('should toggle when toggle is called', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"></div>')
div
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
ok($('#modal-test').length, 'modal inserted into dom')
div.modal('toggle')
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.modal('toggle')
})
test('should remove from dom when click [data-dismiss=modal]', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"><span class="close" data-dismiss="modal"></span></div>')
div
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
ok($('#modal-test').length, 'modal inserted into dom')
div.find('.close').click()
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.modal('toggle')
})
test('should allow modal close with "backdrop:false"', function () {
stop()
$.support.transition = false
var div = $('<div>', { id: 'modal-test', 'data-backdrop': false })
div
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
div.modal('hide')
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.modal('show')
})
test('should close modal when clicking outside of modal-content', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"><div class="contents"></div></div>')
div
.bind('shown.bs.modal', function () {
ok($('#modal-test').length, 'modal insterted into dom')
$('.contents').click()
ok($('#modal-test').is(':visible'), 'modal visible')
$('#modal-test').click()
})
.bind('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.modal('show')
})
test('should trigger hide event once when clicking outside of modal-content', function () {
stop()
$.support.transition = false
var triggered
var div = $('<div id="modal-test"><div class="contents"></div></div>')
div
.bind('shown.bs.modal', function () {
triggered = 0
$('#modal-test').click()
})
.bind('hide.bs.modal', function () {
triggered += 1
ok(triggered === 1, 'modal hide triggered once')
start()
})
.modal('show')
})
test('should close reopened modal with [data-dismiss=modal] click', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"><div class="contents"><div id="close" data-dismiss="modal"></div></div></div>')
div
.bind('shown.bs.modal', function () {
$('#close').click()
ok(!$('#modal-test').is(':visible'), 'modal hidden')
})
.one('hidden.bs.modal', function () {
div.one('hidden.bs.modal', function () {
start()
}).modal('show')
})
.modal('show')
div.remove()
})
=======
'use strict';
module('modal plugin')
test('should be defined on jquery object', function () {
var div = $('<div id="modal-test"></div>')
ok(div.modal, 'modal method is defined')
})
module('modal', {
setup: function () {
// Run all tests in noConflict mode -- it's the only way to ensure that the plugin works in noConflict mode
$.fn.bootstrapModal = $.fn.modal.noConflict()
},
teardown: function () {
$.fn.modal = $.fn.bootstrapModal
delete $.fn.bootstrapModal
}
})
test('should provide no conflict', function () {
ok(!$.fn.modal, 'modal was set back to undefined (orig value)')
})
test('should return element', function () {
var div = $('<div id="modal-test"></div>')
ok(div.bootstrapModal() == div, 'document.body returned')
$('#modal-test').remove()
})
test('should expose defaults var for settings', function () {
ok($.fn.bootstrapModal.Constructor.DEFAULTS, 'default object exposed')
})
test('should insert into dom when show method is called', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('shown.bs.modal', function () {
ok($('#modal-test').length, 'modal inserted into dom')
$(this).remove()
start()
})
.bootstrapModal('show')
})
test('should fire show event', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('show.bs.modal', function () {
ok(true, 'show was called')
})
.on('shown.bs.modal', function () {
$(this).remove()
start()
})
.bootstrapModal('show')
})
test('should not fire shown when default prevented', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('show.bs.modal', function (e) {
e.preventDefault()
ok(true, 'show was called')
start()
})
.on('shown.bs.modal', function () {
ok(false, 'shown was called')
})
.bootstrapModal('show')
})
test('should hide modal when hide is called', function () {
stop()
$.support.transition = false
$('<div id="modal-test"></div>')
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
ok($('#modal-test').length, 'modal inserted into dom')
$(this).bootstrapModal('hide')
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
$('#modal-test').remove()
start()
})
.bootstrapModal('show')
})
test('should toggle when toggle is called', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"></div>')
div
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
ok($('#modal-test').length, 'modal inserted into dom')
div.bootstrapModal('toggle')
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.bootstrapModal('toggle')
})
test('should remove from dom when click [data-dismiss="modal"]', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"><span class="close" data-dismiss="modal"></span></div>')
div
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
ok($('#modal-test').length, 'modal inserted into dom')
div.find('.close').click()
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.bootstrapModal('toggle')
})
test('should allow modal close with "backdrop:false"', function () {
stop()
$.support.transition = false
var div = $('<div>', { id: 'modal-test', 'data-backdrop': false })
div
.on('shown.bs.modal', function () {
ok($('#modal-test').is(':visible'), 'modal visible')
div.bootstrapModal('hide')
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.bootstrapModal('show')
})
test('should close modal when clicking outside of modal-content', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"><div class="contents"></div></div>')
div
.on('shown.bs.modal', function () {
ok($('#modal-test').length, 'modal insterted into dom')
$('.contents').click()
ok($('#modal-test').is(':visible'), 'modal visible')
$('#modal-test').click()
})
.on('hidden.bs.modal', function () {
ok(!$('#modal-test').is(':visible'), 'modal hidden')
div.remove()
start()
})
.bootstrapModal('show')
})
test('should trigger hide event once when clicking outside of modal-content', function () {
stop()
$.support.transition = false
var triggered
var div = $('<div id="modal-test"><div class="contents"></div></div>')
div
.on('shown.bs.modal', function () {
triggered = 0
$('#modal-test').click()
})
.on('hide.bs.modal', function () {
triggered += 1
ok(triggered === 1, 'modal hide triggered once')
start()
})
.bootstrapModal('show')
})
test('should close reopened modal with [data-dismiss="modal"] click', function () {
stop()
$.support.transition = false
var div = $('<div id="modal-test"><div class="contents"><div id="close" data-dismiss="modal"></div></div></div>')
div
.on('shown.bs.modal', function () {
$('#close').click()
ok(!$('#modal-test').is(':visible'), 'modal hidden')
})
.one('hidden.bs.modal', function () {
div.one('hidden.bs.modal', function () {
start()
}).bootstrapModal('show')
})
.bootstrapModal('show')
div.remove()
})
test('should restore focus to toggling element when modal is hidden after having been opened via data-api', function () {
stop()
$.support.transition = false
var toggleBtn = $('<button data-toggle="modal" data-target="#modal-test">Launch modal</button>').appendTo('#qunit-fixture')
var div = $('<div id="modal-test"><div class="contents"><div id="close" data-dismiss="modal"></div></div></div>')
div
.on('hidden.bs.modal', function () {
window.setTimeout(function () { // give the focus restoration callback a chance to run
equal(document.activeElement, toggleBtn[0], 'toggling element is once again focused')
div.remove()
toggleBtn.remove()
start()
}, 0)
})
.on('shown.bs.modal', function () {
$('#close').click()
})
.appendTo('#qunit-fixture')
toggleBtn.click()
})
test('should not restore focus to toggling element if the associated show event gets prevented', function () {
stop()
$.support.transition = false
var toggleBtn = $('<button data-toggle="modal" data-target="#modal-test">Launch modal</button>').appendTo('#qunit-fixture')
var otherBtn = $('<button id="other-btn">Golden boy</button>').appendTo('#qunit-fixture')
var div = $('<div id="modal-test"><div class="contents"><div id="close" data-dismiss="modal"></div></div></div>')
div
.one('show.bs.modal', function (e) {
e.preventDefault()
otherBtn.focus()
window.setTimeout(function () { // give the focus event from the previous line a chance to run
div.bootstrapModal('show')
}, 0)
})
.on('hidden.bs.modal', function () {
window.setTimeout(function () { // give the focus restoration callback a chance to run (except it shouldn't run in this case)
equal(document.activeElement, otherBtn[0], 'show was prevented, so focus should not have been restored to toggling element')
div.remove()
toggleBtn.remove()
otherBtn.remove()
start()
}, 0)
})
.on('shown.bs.modal', function () {
$('#close').click()
})
.appendTo('#qunit-fixture')
toggleBtn.click()
})
>>>>>>> 1aaad6481cb064f31f85d519cd56e3c1799585cf
})
|
import { get } from 'object-path';
const translationMap = new Map();
/**
* Factory function for creating translation helpers
*
* @example <caption>Creating, and using, a translation helper</caption>
* export class Foo extends Component {
* renderCallback() {
* const { locale } = props(this);
* const t = createTranslationHelper(locale);
*
* return [
* <p>
* {t('text.first_paragraph')}
* </p>,
* <p>
* {t('text.second_paragraph')}
* </p>
* ];
* }
* }
*
* @param {string} locale the locale to create a factory for
* @return {translationHelper} the translation helper
* @throws {TypeError} thrown when no locale is provided
*/
export default function createTranslationHelper(locale) {
if (!locale) {
throw new TypeError('No locale provided');
}
const translationFile = translationMap.get(locale);
return function translationHelper(translationKey) {
const value = get(translationFile, translationKey);
return value ? value : `MISSING TRANSLATION: ${translationKey} for ${locale}`;
};
}
|
// starter.test.js
var expect = require('chai').expect;
var GitStarter = require("../lib/git-starter");
describe('GitStarter', function() {
describe('#applyStarter', function() {
var starter;
var opts = {};
var args = {};
beforeEach(function() {
starter = new GitStarter(opts, args);
});
it('emit "error" on failure', function(done) {
starter.on("error", function(err) {
done();
});
starter.applyStarter();
});
// TODO: ADD MORE TESTS
});
});
|
/* eslint-env node, mocha */
var pack = require('../../')
var path = require('path')
var gulp = require('gulp')
var through = require('through2')
describe('gulp-pack', function () {
describe('sync deps', function () {
gulp.task('sync-deps', function () {
it('should has right deps', function (done) {
var stream = through.obj(function (file, encoding, cb) {
var resMap = null
if (file.relative === 'resource_deps.json') {
resMap = JSON.parse(file.contents.toString())
resMap['index.js'].deps.should.match(['a.js', 'b/index.js'])
resMap['a.js'].deps.should.be.empty()
resMap['b/index.js'].deps.should.be.empty()
done()
}
cb()
})
return gulp.src(path.join(__dirname, '**/*.js'))
.pipe(pack({
genResDeps: true,
entrys: 'index.js'
}))
.pipe(stream)
})
})
gulp.start('sync-deps')
})
})
|
'use strict';
module.exports = function enableAuthentication (server) {
var debug = require('debug')('app-site');
/**
* Enable Authentication
*/
debug('enabling authentication');
server.enableAuth();
};
|
/**
* Created by Toure on 26/11/14.
*/
function getImages(){
$('[id*="uploadMiniature_"]').each(function(){
var $this = $(this);
var imageSelect = $($this).find('img');
var fileSelect = $($this).find('input[type="file"]');
var image = Object.create(Image);
var numero = $(fileSelect).data('numero');
image.numero = numero;
image.src = $(imageSelect).attr('src');
image.alt = $(imageSelect).attr('alt');
mesImages.add(image);
});
}
function moveImage(){
$('#jc_joliecarbundle_voiture_images>[id*="uploadMiniature_"]').each(function(){
var $this = $(this);
$($this).insertBefore($('#images>br'));
});
}
$(document).ready(function(){
moveImage();
getImages();
$('#ajoutImage').click(function(e){
var $this = $(this);
e.preventDefault();
$this.trigger('mouseout');
//var file = document.querySelector('#uploadMiniature_'+lastNumber+' input[type="file"]');
//var img = $('#uploadMiniature_'+lastNumber+' img');
//nouvelle image,si c'est pas une modification d'une zone existante
addUploadMiniature($('#images'),mesImages.count()-1);
//$('#images>br').insertAfter($('#images>div:last-child'));
$(this).remove();
});
});
|
import {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLID,
GraphQLNonNull,
} from 'graphql';
import User, { userFieldResolver } from './User';
import FeedbackVote from './FeedbackVote';
import Node from '../interfaces/Node';
export default new GraphQLObjectType({
name: 'ReplyRequest',
interfaces: [Node],
fields: () => ({
id: { type: new GraphQLNonNull(GraphQLID) },
userId: { type: GraphQLString },
appId: { type: GraphQLString },
user: {
type: User,
description: 'The author of reply request.',
resolve: userFieldResolver,
},
reason: { type: GraphQLString },
feedbackCount: {
type: GraphQLInt,
resolve({ feedbacks = [] }) {
return feedbacks.length;
},
},
positiveFeedbackCount: {
type: GraphQLInt,
resolve({ feedbacks = [] }) {
return feedbacks.filter(fb => fb.score === 1).length;
},
},
negativeFeedbackCount: {
type: GraphQLInt,
resolve({ feedbacks = [] }) {
return feedbacks.filter(fb => fb.score === -1).length;
},
},
createdAt: { type: GraphQLString },
updatedAt: { type: GraphQLString },
ownVote: {
type: FeedbackVote,
description:
'The feedback of current user. null when not logged in or not voted yet.',
resolve({ feedbacks = [] }, args, { userId, appId }) {
if (!userId || !appId) return null;
const ownFeedback = feedbacks.find(
feedback => feedback.userId === userId && feedback.appId === appId
);
if (!ownFeedback) return null;
return ownFeedback.score;
},
},
}),
});
|
//! moment.js
//! version : 2.14.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.moment = factory()
}(this, function () { 'use strict';
var hookCallback;
function utils_hooks__hooks () {
return hookCallback.apply(null, arguments);
}
// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback (callback) {
hookCallback = callback;
}
function isArray(input) {
return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
}
function isObject(input) {
return Object.prototype.toString.call(input) === '[object Object]';
}
function isObjectEmpty(obj) {
var k;
for (k in obj) {
// even if its not own property I'd still call it non-empty
return false;
}
return true;
}
function isDate(input) {
return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
}
function map(arr, fn) {
var res = [], i;
for (i = 0; i < arr.length; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, 'toString')) {
a.toString = b.toString;
}
if (hasOwnProp(b, 'valueOf')) {
a.valueOf = b.valueOf;
}
return a;
}
function create_utc__createUTC (input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, true).utc();
}
function defaultParsingFlags() {
// We need to deep clone this object.
return {
empty : false,
unusedTokens : [],
unusedInput : [],
overflow : -2,
charsLeftOver : 0,
nullInput : false,
invalidMonth : null,
invalidFormat : false,
userInvalidated : false,
iso : false,
parsedDateParts : [],
meridiem : null
};
}
function getParsingFlags(m) {
if (m._pf == null) {
m._pf = defaultParsingFlags();
}
return m._pf;
}
var some;
if (Array.prototype.some) {
some = Array.prototype.some;
} else {
some = function (fun) {
var t = Object(this);
var len = t.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(this, t[i], i, t)) {
return true;
}
}
return false;
};
}
function valid__isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m);
var parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
});
m._isValid = !isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated &&
(!flags.meridiem || (flags.meridiem && parsedParts));
if (m._strict) {
m._isValid = m._isValid &&
flags.charsLeftOver === 0 &&
flags.unusedTokens.length === 0 &&
flags.bigHour === undefined;
}
}
return m._isValid;
}
function valid__createInvalid (flags) {
var m = create_utc__createUTC(NaN);
if (flags != null) {
extend(getParsingFlags(m), flags);
}
else {
getParsingFlags(m).userInvalidated = true;
}
return m;
}
function isUndefined(input) {
return input === void 0;
}
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = utils_hooks__hooks.momentProperties = [];
function copyConfig(to, from) {
var i, prop, val;
if (!isUndefined(from._isAMomentObject)) {
to._isAMomentObject = from._isAMomentObject;
}
if (!isUndefined(from._i)) {
to._i = from._i;
}
if (!isUndefined(from._f)) {
to._f = from._f;
}
if (!isUndefined(from._l)) {
to._l = from._l;
}
if (!isUndefined(from._strict)) {
to._strict = from._strict;
}
if (!isUndefined(from._tzm)) {
to._tzm = from._tzm;
}
if (!isUndefined(from._isUTC)) {
to._isUTC = from._isUTC;
}
if (!isUndefined(from._offset)) {
to._offset = from._offset;
}
if (!isUndefined(from._pf)) {
to._pf = getParsingFlags(from);
}
if (!isUndefined(from._locale)) {
to._locale = from._locale;
}
if (momentProperties.length > 0) {
for (i in momentProperties) {
prop = momentProperties[i];
val = from[prop];
if (!isUndefined(val)) {
to[prop] = val;
}
}
}
return to;
}
var updateInProgress = false;
// Moment prototype object
function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d != null ? config._d.getTime() : NaN);
// Prevent infinite loop in case updateOffset creates new moment
// objects.
if (updateInProgress === false) {
updateInProgress = true;
utils_hooks__hooks.updateOffset(this);
updateInProgress = false;
}
}
function isMoment (obj) {
return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}
function absFloor (number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if ((dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
diffs++;
}
}
return diffs + lengthDiff;
}
function warn(msg) {
if (utils_hooks__hooks.suppressDeprecationWarnings === false &&
(typeof console !== 'undefined') && console.warn) {
console.warn('Deprecation warning: ' + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (utils_hooks__hooks.deprecationHandler != null) {
utils_hooks__hooks.deprecationHandler(null, msg);
}
if (firstTime) {
warn(msg + '\nArguments: ' + Array.prototype.slice.call(arguments).join(', ') + '\n' + (new Error()).stack);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
if (utils_hooks__hooks.deprecationHandler != null) {
utils_hooks__hooks.deprecationHandler(name, msg);
}
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
utils_hooks__hooks.suppressDeprecationWarnings = false;
utils_hooks__hooks.deprecationHandler = null;
function isFunction(input) {
return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
function locale_set__set (config) {
var prop, i;
for (i in config) {
prop = config[i];
if (isFunction(prop)) {
this[i] = prop;
} else {
this['_' + i] = prop;
}
}
this._config = config;
// Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _ordinalParseLenient.
this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
}
function mergeConfigs(parentConfig, childConfig) {
var res = extend({}, parentConfig), prop;
for (prop in childConfig) {
if (hasOwnProp(childConfig, prop)) {
if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
res[prop] = {};
extend(res[prop], parentConfig[prop]);
extend(res[prop], childConfig[prop]);
} else if (childConfig[prop] != null) {
res[prop] = childConfig[prop];
} else {
delete res[prop];
}
}
}
for (prop in parentConfig) {
if (hasOwnProp(parentConfig, prop) &&
!hasOwnProp(childConfig, prop) &&
isObject(parentConfig[prop])) {
// make sure changes to properties don't modify parent config
res[prop] = extend({}, res[prop]);
}
}
return res;
}
function Locale(config) {
if (config != null) {
this.set(config);
}
}
var keys;
if (Object.keys) {
keys = Object.keys;
} else {
keys = function (obj) {
var i, res = [];
for (i in obj) {
if (hasOwnProp(obj, i)) {
res.push(i);
}
}
return res;
};
}
var defaultCalendar = {
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
nextWeek : 'dddd [at] LT',
lastDay : '[Yesterday at] LT',
lastWeek : '[Last] dddd [at] LT',
sameElse : 'L'
};
function locale_calendar__calendar (key, mom, now) {
var output = this._calendar[key] || this._calendar['sameElse'];
return isFunction(output) ? output.call(mom, now) : output;
}
var defaultLongDateFormat = {
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
};
function longDateFormat (key) {
var format = this._longDateFormat[key],
formatUpper = this._longDateFormat[key.toUpperCase()];
if (format || !formatUpper) {
return format;
}
this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
return val.slice(1);
});
return this._longDateFormat[key];
}
var defaultInvalidDate = 'Invalid date';
function invalidDate () {
return this._invalidDate;
}
var defaultOrdinal = '%d';
var defaultOrdinalParse = /\d{1,2}/;
function ordinal (number) {
return this._ordinal.replace('%d', number);
}
var defaultRelativeTime = {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : 'a minute',
mm : '%d minutes',
h : 'an hour',
hh : '%d hours',
d : 'a day',
dd : '%d days',
M : 'a month',
MM : '%d months',
y : 'a year',
yy : '%d years'
};
function relative__relativeTime (number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return (isFunction(output)) ?
output(number, withoutSuffix, string, isFuture) :
output.replace(/%d/i, number);
}
function pastFuture (diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}
var aliases = {};
function addUnitAlias (unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
var priorities = {};
function addUnitPriority(unit, priority) {
priorities[unit] = priority;
}
function getPrioritizedUnits(unitsObj) {
var units = [];
for (var u in unitsObj) {
units.push({unit: u, priority: priorities[u]});
}
units.sort(function (a, b) {
return a.priority - b.priority;
});
return units;
}
function makeGetSet (unit, keepTime) {
return function (value) {
if (value != null) {
get_set__set(this, unit, value);
utils_hooks__hooks.updateOffset(this, keepTime);
return this;
} else {
return get_set__get(this, unit);
}
};
}
function get_set__get (mom, unit) {
return mom.isValid() ?
mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
}
function get_set__set (mom, unit, value) {
if (mom.isValid()) {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
// MOMENTS
function stringGet (units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet (units, value) {
if (typeof units === 'object') {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units);
for (var i = 0; i < prioritized.length; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = '' + Math.abs(number),
zerosToFill = targetLength - absNumber.length,
sign = number >= 0;
return (sign ? (forceSign ? '+' : '') : '-') +
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
}
var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
var formatFunctions = {};
var formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken (token, padded, ordinal, callback) {
var func = callback;
if (typeof callback === 'string') {
func = function () {
return this[callback]();
};
}
if (token) {
formatTokenFunctions[token] = func;
}
if (padded) {
formatTokenFunctions[padded[0]] = function () {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
};
}
if (ordinal) {
formatTokenFunctions[ordinal] = function () {
return this.localeData().ordinal(func.apply(this, arguments), token);
};
}
}
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, '');
}
return input.replace(/\\/g, '');
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens), i, length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = '', i;
for (i = 0; i < length; i++) {
output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
}
return output;
};
}
// format date using native date object
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
var match1 = /\d/; // 0 - 9
var match2 = /\d\d/; // 00 - 99
var match3 = /\d{3}/; // 000 - 999
var match4 = /\d{4}/; // 0000 - 9999
var match6 = /[+-]?\d{6}/; // -999999 - 999999
var match1to2 = /\d\d?/; // 0 - 99
var match3to4 = /\d\d\d\d?/; // 999 - 9999
var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
var match1to3 = /\d{1,3}/; // 0 - 999
var match1to4 = /\d{1,4}/; // 0 - 9999
var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
var matchUnsigned = /\d+/; // 0 - inf
var matchSigned = /[+-]?\d+/; // -inf - inf
var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
var regexes = {};
function addRegexToken (token, regex, strictRegex) {
regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
return (isStrict && strictRegex) ? strictRegex : regex;
};
}
function getParseRegexForToken (token, config) {
if (!hasOwnProp(regexes, token)) {
return new RegExp(unescapeFormat(token));
}
return regexes[token](config._strict, config._locale);
}
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
}));
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var tokens = {};
function addParseToken (token, callback) {
var i, func = callback;
if (typeof token === 'string') {
token = [token];
}
if (typeof callback === 'number') {
func = function (input, array) {
array[callback] = toInt(input);
};
}
for (i = 0; i < token.length; i++) {
tokens[token[i]] = func;
}
}
function addWeekParseToken (token, callback) {
addParseToken(token, function (input, array, config, token) {
config._w = config._w || {};
callback(input, config._w, config, token);
});
}
function addTimeToArrayFromToken(token, input, config) {
if (input != null && hasOwnProp(tokens, token)) {
tokens[token](input, config._a, config, token);
}
}
var YEAR = 0;
var MONTH = 1;
var DATE = 2;
var HOUR = 3;
var MINUTE = 4;
var SECOND = 5;
var MILLISECOND = 6;
var WEEK = 7;
var WEEKDAY = 8;
var indexOf;
if (Array.prototype.indexOf) {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function (o) {
// I know
var i;
for (i = 0; i < this.length; ++i) {
if (this[i] === o) {
return i;
}
}
return -1;
};
}
function daysInMonth(year, month) {
return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
}
// FORMATTING
addFormatToken('M', ['MM', 2], 'Mo', function () {
return this.month() + 1;
});
addFormatToken('MMM', 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken('MMMM', 0, 0, function (format) {
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias('month', 'M');
// PRIORITY
addUnitPriority('month', 8);
// PARSING
addRegexToken('M', match1to2);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
return locale.monthsRegex(isStrict);
});
addParseToken(['M', 'MM'], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
// LOCALES
var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/;
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
function localeMonths (m, format) {
return isArray(this._months) ? this._months[m.month()] :
this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
}
var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
function localeMonthsShort (m, format) {
return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
}
function units_month__handleStrictParse(monthName, format, strict) {
var i, ii, mom, llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
// this is not used
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i = 0; i < 12; ++i) {
mom = create_utc__createUTC([2000, i]);
this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeMonthsParse (monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) {
return units_month__handleStrictParse.call(this, monthName, format, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = create_utc__createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
}
if (!strict && !this._monthsParse[i]) {
regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
return i;
} else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
// MOMENTS
function setMonth (mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
}
if (typeof value === 'string') {
if (/^\d+$/.test(value)) {
value = toInt(value);
} else {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (typeof value !== 'number') {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
function getSetMonth (value) {
if (value != null) {
setMonth(this, value);
utils_hooks__hooks.updateOffset(this, true);
return this;
} else {
return get_set__get(this, 'Month');
}
}
function getDaysInMonth () {
return daysInMonth(this.year(), this.month());
}
var defaultMonthsShortRegex = matchWord;
function monthsShortRegex (isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsShortStrictRegex;
} else {
return this._monthsShortRegex;
}
} else {
if (!hasOwnProp(this, '_monthsShortRegex')) {
this._monthsShortRegex = defaultMonthsShortRegex;
}
return this._monthsShortStrictRegex && isStrict ?
this._monthsShortStrictRegex : this._monthsShortRegex;
}
}
var defaultMonthsRegex = matchWord;
function monthsRegex (isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsStrictRegex;
} else {
return this._monthsRegex;
}
} else {
if (!hasOwnProp(this, '_monthsRegex')) {
this._monthsRegex = defaultMonthsRegex;
}
return this._monthsStrictRegex && isStrict ?
this._monthsStrictRegex : this._monthsRegex;
}
}
function computeMonthsParse () {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var shortPieces = [], longPieces = [], mixedPieces = [],
i, mom;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = create_utc__createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ''));
longPieces.push(this.months(mom, ''));
mixedPieces.push(this.months(mom, ''));
mixedPieces.push(this.monthsShort(mom, ''));
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._monthsShortRegex = this._monthsRegex;
this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
}
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? '' + y : '+' + y;
});
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
// ALIASES
addUnitAlias('year', 'y');
// PRIORITIES
addUnitPriority('year', 1);
// PARSING
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
// HOOKS
utils_hooks__hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', true);
function getIsLeapYear () {
return isLeapYear(this.year());
}
function createDate (y, m, d, h, M, s, ms) {
//can't just apply() to create a date:
//http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
var date = new Date(y, m, d, h, M, s, ms);
//the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
date.setFullYear(y);
}
return date;
}
function createUTCDate (y) {
var date = new Date(Date.UTC.apply(null, arguments));
//the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
return date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
fwd = 7 + dow - doy,
// first-week day local weekday -- which local weekday is fwd
fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
return -fwdlw + fwd - 1;
}
//http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var localWeekday = (7 + weekday - dow) % 7,
weekOffset = firstWeekOffset(year, dow, doy),
dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
resYear, resDayOfYear;
if (dayOfYear <= 0) {
resYear = year - 1;
resDayOfYear = daysInYear(resYear) + dayOfYear;
} else if (dayOfYear > daysInYear(year)) {
resYear = year + 1;
resDayOfYear = dayOfYear - daysInYear(year);
} else {
resYear = year;
resDayOfYear = dayOfYear;
}
return {
year: resYear,
dayOfYear: resDayOfYear
};
}
function weekOfYear(mom, dow, doy) {
var weekOffset = firstWeekOffset(mom.year(), dow, doy),
week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
resWeek, resYear;
if (week < 1) {
resYear = mom.year() - 1;
resWeek = week + weeksInYear(resYear, dow, doy);
} else if (week > weeksInYear(mom.year(), dow, doy)) {
resWeek = week - weeksInYear(mom.year(), dow, doy);
resYear = mom.year() + 1;
} else {
resYear = mom.year();
resWeek = week;
}
return {
week: resWeek,
year: resYear
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy),
weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// FORMATTING
addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
// ALIASES
addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');
// PRIORITIES
addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);
// PARSING
addRegexToken('w', match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W', match1to2);
addRegexToken('WW', match1to2, match2);
addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
});
// HELPERS
// LOCALES
function localeWeek (mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}
var defaultLocaleWeek = {
dow : 0, // Sunday is the first day of the week.
doy : 6 // The week that contains Jan 1st is the first week of the year.
};
function localeFirstDayOfWeek () {
return this._week.dow;
}
function localeFirstDayOfYear () {
return this._week.doy;
}
// MOMENTS
function getSetWeek (input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, 'd');
}
function getSetISOWeek (input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, 'd');
}
// FORMATTING
addFormatToken('d', 0, 'do', 'day');
addFormatToken('dd', 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken('ddd', 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken('dddd', 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
// ALIASES
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);
// PARSING
addRegexToken('d', match1to2);
addRegexToken('e', match1to2);
addRegexToken('E', match1to2);
addRegexToken('dd', function (isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd', function (isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd', function (isStrict, locale) {
return locale.weekdaysRegex(isStrict);
});
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
});
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
week[token] = toInt(input);
});
// HELPERS
function parseWeekday(input, locale) {
if (typeof input !== 'string') {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === 'number') {
return input;
}
return null;
}
function parseIsoWeekday(input, locale) {
if (typeof input === 'string') {
return locale.weekdaysParse(input) % 7 || 7;
}
return isNaN(input) ? null : input;
}
// LOCALES
var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
function localeWeekdays (m, format) {
return isArray(this._weekdays) ? this._weekdays[m.day()] :
this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
}
var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function localeWeekdaysShort (m) {
return this._weekdaysShort[m.day()];
}
var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
function localeWeekdaysMin (m) {
return this._weekdaysMin[m.day()];
}
function day_of_week__handleStrictParse(weekdayName, format, strict) {
var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i = 0; i < 7; ++i) {
mom = create_utc__createUTC([2000, 1]).day(i);
this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeWeekdaysParse (weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) {
return day_of_week__handleStrictParse.call(this, weekdayName, format, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = create_utc__createUTC([2000, 1]).day(i);
if (strict && !this._fullWeekdaysParse[i]) {
this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
}
if (!this._weekdaysParse[i]) {
regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
// MOMENTS
function getSetDayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
}
function getSetLocaleDayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
}
function getSetISODayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (input != null) {
var weekday = parseIsoWeekday(input, this.localeData());
return this.day(this.day() % 7 ? weekday : weekday - 7);
} else {
return this.day() || 7;
}
}
var defaultWeekdaysRegex = matchWord;
function weekdaysRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysStrictRegex;
} else {
return this._weekdaysRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysRegex')) {
this._weekdaysRegex = defaultWeekdaysRegex;
}
return this._weekdaysStrictRegex && isStrict ?
this._weekdaysStrictRegex : this._weekdaysRegex;
}
}
var defaultWeekdaysShortRegex = matchWord;
function weekdaysShortRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysShortStrictRegex;
} else {
return this._weekdaysShortRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysShortRegex')) {
this._weekdaysShortRegex = defaultWeekdaysShortRegex;
}
return this._weekdaysShortStrictRegex && isStrict ?
this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
}
}
var defaultWeekdaysMinRegex = matchWord;
function weekdaysMinRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysMinStrictRegex;
} else {
return this._weekdaysMinRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysMinRegex')) {
this._weekdaysMinRegex = defaultWeekdaysMinRegex;
}
return this._weekdaysMinStrictRegex && isStrict ?
this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
}
}
function computeWeekdaysParse () {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
i, mom, minp, shortp, longp;
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = create_utc__createUTC([2000, 1]).day(i);
minp = this.weekdaysMin(mom, '');
shortp = this.weekdaysShort(mom, '');
longp = this.weekdays(mom, '');
minPieces.push(minp);
shortPieces.push(shortp);
longPieces.push(longp);
mixedPieces.push(minp);
mixedPieces.push(shortp);
mixedPieces.push(longp);
}
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev);
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 7; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._weekdaysShortRegex = this._weekdaysRegex;
this._weekdaysMinRegex = this._weekdaysRegex;
this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function kFormat() {
return this.hours() || 24;
}
addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, hFormat);
addFormatToken('k', ['kk', 2], 0, kFormat);
addFormatToken('hmm', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});
addFormatToken('hmmss', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2);
});
addFormatToken('Hmm', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2);
});
addFormatToken('Hmmss', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2);
});
function meridiem (token, lowercase) {
addFormatToken(token, 0, 0, function () {
return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
});
}
meridiem('a', true);
meridiem('A', false);
// ALIASES
addUnitAlias('hour', 'h');
// PRIORITY
addUnitPriority('hour', 13);
// PARSING
function matchMeridiem (isStrict, locale) {
return locale._meridiemParse;
}
addRegexToken('a', matchMeridiem);
addRegexToken('A', matchMeridiem);
addRegexToken('H', match1to2);
addRegexToken('h', match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);
addParseToken(['H', 'HH'], HOUR);
addParseToken(['a', 'A'], function (input, array, config) {
config._isPm = config._locale.isPM(input);
config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
array[HOUR] = toInt(input);
getParsingFlags(config).bigHour = true;
});
addParseToken('hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
getParsingFlags(config).bigHour = true;
});
addParseToken('hmmss', function (input, array, config) {
var pos1 = input.length - 4;
var pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
getParsingFlags(config).bigHour = true;
});
addParseToken('Hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
});
addParseToken('Hmmss', function (input, array, config) {
var pos1 = input.length - 4;
var pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
});
// LOCALES
function localeIsPM (input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return ((input + '').toLowerCase().charAt(0) === 'p');
}
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
function localeMeridiem (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
}
// MOMENTS
// Setting the hour should keep the time, because the user explicitly
// specified which hour he wants. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
var getSetHour = makeGetSet('Hours', true);
var baseConfig = {
calendar: defaultCalendar,
longDateFormat: defaultLongDateFormat,
invalidDate: defaultInvalidDate,
ordinal: defaultOrdinal,
ordinalParse: defaultOrdinalParse,
relativeTime: defaultRelativeTime,
months: defaultLocaleMonths,
monthsShort: defaultLocaleMonthsShort,
week: defaultLocaleWeek,
weekdays: defaultLocaleWeekdays,
weekdaysMin: defaultLocaleWeekdaysMin,
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: defaultLocaleMeridiemParse
};
// internal storage for locale config files
var locales = {};
var globalLocale;
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
var i = 0, j, next, locale, split;
while (i < names.length) {
split = normalizeLocale(names[i]).split('-');
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join('-'));
if (locale) {
return locale;
}
if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return null;
}
function loadLocale(name) {
var oldLocale = null;
// TODO: Find a better way to register and load all the locales in Node
if (!locales[name] && (typeof module !== 'undefined') &&
module && module.exports) {
try {
oldLocale = globalLocale._abbr;
require('./locale/' + name);
// because defineLocale currently also sets the global locale, we
// want to undo that for lazy loaded locales
locale_locales__getSetGlobalLocale(oldLocale);
} catch (e) { }
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function locale_locales__getSetGlobalLocale (key, values) {
var data;
if (key) {
if (isUndefined(values)) {
data = locale_locales__getLocale(key);
}
else {
data = defineLocale(key, values);
}
if (data) {
// moment.duration._locale = moment._locale = data;
globalLocale = data;
}
}
return globalLocale._abbr;
}
function defineLocale (name, config) {
if (config !== null) {
var parentConfig = baseConfig;
config.abbr = name;
if (locales[name] != null) {
deprecateSimple('defineLocaleOverride',
'use moment.updateLocale(localeName, config) to change ' +
'an existing locale. moment.defineLocale(localeName, ' +
'config) should only be used for creating a new locale ' +
'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
parentConfig = locales[name]._config;
} else if (config.parentLocale != null) {
if (locales[config.parentLocale] != null) {
parentConfig = locales[config.parentLocale]._config;
} else {
// treat as if there is no base config
deprecateSimple('parentLocaleUndefined',
'specified parentLocale is not defined yet. See http://momentjs.com/guides/#/warnings/parent-locale/');
}
}
locales[name] = new Locale(mergeConfigs(parentConfig, config));
// backwards compat for now: also set the locale
locale_locales__getSetGlobalLocale(name);
return locales[name];
} else {
// useful for testing
delete locales[name];
return null;
}
}
function updateLocale(name, config) {
if (config != null) {
var locale, parentConfig = baseConfig;
// MERGE
if (locales[name] != null) {
parentConfig = locales[name]._config;
}
config = mergeConfigs(parentConfig, config);
locale = new Locale(config);
locale.parentLocale = locales[name];
locales[name] = locale;
// backwards compat for now: also set the locale
locale_locales__getSetGlobalLocale(name);
} else {
// pass null for config to unupdate, useful for tests
if (locales[name] != null) {
if (locales[name].parentLocale != null) {
locales[name] = locales[name].parentLocale;
} else if (locales[name] != null) {
delete locales[name];
}
}
}
return locales[name];
}
// returns locale data
function locale_locales__getLocale (key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
}
function locale_locales__listLocales() {
return keys(locales);
}
function checkOverflow (m) {
var overflow;
var a = m._a;
if (a && getParsingFlags(m).overflow === -2) {
overflow =
a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
-1;
if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
overflow = DATE;
}
if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
overflow = WEEK;
}
if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
overflow = WEEKDAY;
}
getParsingFlags(m).overflow = overflow;
}
return m;
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;
var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;
var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
var isoDates = [
['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
['GGGG-[W]WW', /\d{4}-W\d\d/, false],
['YYYY-DDD', /\d{4}-\d{3}/],
['YYYY-MM', /\d{4}-\d\d/, false],
['YYYYYYMMDD', /[+-]\d{10}/],
['YYYYMMDD', /\d{8}/],
// YYYYMM is NOT allowed by the standard
['GGGG[W]WWE', /\d{4}W\d{3}/],
['GGGG[W]WW', /\d{4}W\d{2}/, false],
['YYYYDDD', /\d{7}/]
];
// iso time formats and regexes
var isoTimes = [
['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
['HH:mm:ss', /\d\d:\d\d:\d\d/],
['HH:mm', /\d\d:\d\d/],
['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
['HHmmss', /\d\d\d\d\d\d/],
['HHmm', /\d\d\d\d/],
['HH', /\d\d/]
];
var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
// date from iso format
function configFromISO(config) {
var i, l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime, dateFormat, timeFormat, tzFormat;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDates.length; i < l; i++) {
if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0];
allowTime = isoDates[i][2] !== false;
break;
}
}
if (dateFormat == null) {
config._isValid = false;
return;
}
if (match[3]) {
for (i = 0, l = isoTimes.length; i < l; i++) {
if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || ' ') + isoTimes[i][0];
break;
}
}
if (timeFormat == null) {
config._isValid = false;
return;
}
}
if (!allowTime && timeFormat != null) {
config._isValid = false;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) {
tzFormat = 'Z';
} else {
config._isValid = false;
return;
}
}
config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
configFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
// date from iso format or fallback
function configFromString(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (matched !== null) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config);
if (config._isValid === false) {
delete config._isValid;
utils_hooks__hooks.createFromInputFallback(config);
}
}
utils_hooks__hooks.createFromInputFallback = deprecate(
'moment construction falls back to js Date. This is ' +
'discouraged and will be removed in upcoming major ' +
'release. Please refer to ' +
'http://momentjs.com/guides/#/warnings/date/ for more info.',
function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}
);
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return c;
}
function currentDateArray(config) {
// hooks is actually the exported moment object
var nowValue = new Date(utils_hooks__hooks.now());
if (config._useUTC) {
return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
}
return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray (config) {
var i, date, input = [], currentDate, yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
//compute day of the year from weeks and weekdays
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
//if the day of the year is set, figure out what it is
if (config._dayOfYear) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (config._dayOfYear > daysInYear(yearToUse)) {
getParsingFlags(config)._overflowDayOfYear = true;
}
date = createUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
// Zero out whatever was not defaulted, including time
for (; i < 7; i++) {
config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
}
// Check for 24:00:00.000
if (config._a[HOUR] === 24 &&
config._a[MINUTE] === 0 &&
config._a[SECOND] === 0 &&
config._a[MILLISECOND] === 0) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
// Apply timezone offset from input. The actual utcOffset can be changed
// with parseZone.
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
}
function dayOfYearFromWeekInfo(config) {
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
// TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year);
week = defaults(w.W, 1);
weekday = defaults(w.E, 1);
if (weekday < 1 || weekday > 7) {
weekdayOverflow = true;
}
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year);
week = defaults(w.w, 1);
if (w.d != null) {
// weekday -- low day numbers are considered next week
weekday = w.d;
if (weekday < 0 || weekday > 6) {
weekdayOverflow = true;
}
} else if (w.e != null) {
// local weekday -- counting starts from begining of week
weekday = w.e + dow;
if (w.e < 0 || w.e > 6) {
weekdayOverflow = true;
}
} else {
// default to begining of week
weekday = dow;
}
}
if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
getParsingFlags(config)._overflowWeeks = true;
} else if (weekdayOverflow != null) {
getParsingFlags(config)._overflowWeekday = true;
} else {
temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
}
// constant that refers to the ISO standard
utils_hooks__hooks.ISO_8601 = function () {};
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === utils_hooks__hooks.ISO_8601) {
configFromISO(config);
return;
}
config._a = [];
getParsingFlags(config).empty = true;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var string = '' + config._i,
i, parsedInput, tokens, token, skipped,
stringLength = string.length,
totalParsedInputLength = 0;
tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
// console.log('token', token, 'parsedInput', parsedInput,
// 'regex', getParseRegexForToken(token, config));
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
getParsingFlags(config).unusedInput.push(skipped);
}
string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
totalParsedInputLength += parsedInput.length;
}
// don't parse if it's not a known token
if (formatTokenFunctions[token]) {
if (parsedInput) {
getParsingFlags(config).empty = false;
}
else {
getParsingFlags(config).unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
}
else if (config._strict && !parsedInput) {
getParsingFlags(config).unusedTokens.push(token);
}
}
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
if (string.length > 0) {
getParsingFlags(config).unusedInput.push(string);
}
// clear _12h flag if hour is <= 12
if (config._a[HOUR] <= 12 &&
getParsingFlags(config).bigHour === true &&
config._a[HOUR] > 0) {
getParsingFlags(config).bigHour = undefined;
}
getParsingFlags(config).parsedDateParts = config._a.slice(0);
getParsingFlags(config).meridiem = config._meridiem;
// handle meridiem
config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
configFromArray(config);
checkOverflow(config);
}
function meridiemFixWrap (locale, hour, meridiem) {
var isPm;
if (meridiem == null) {
// nothing to do
return hour;
}
if (locale.meridiemHour != null) {
return locale.meridiemHour(hour, meridiem);
} else if (locale.isPM != null) {
// Fallback
isPm = locale.isPM(meridiem);
if (isPm && hour < 12) {
hour += 12;
}
if (!isPm && hour === 12) {
hour = 0;
}
return hour;
} else {
// this is not supposed to happen
return hour;
}
}
// date from string and array of format strings
function configFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore;
if (config._f.length === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < config._f.length; i++) {
currentScore = 0;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (!valid__isValid(tempConfig)) {
continue;
}
// if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver;
//or tokens
currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
getParsingFlags(tempConfig).score = currentScore;
if (scoreToBeat == null || currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i);
config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
return obj && parseInt(obj, 10);
});
configFromArray(config);
}
function createFromConfig (config) {
var res = new Moment(checkOverflow(prepareConfig(config)));
if (res._nextDay) {
// Adding is smart enough around DST
res.add(1, 'd');
res._nextDay = undefined;
}
return res;
}
function prepareConfig (config) {
var input = config._i,
format = config._f;
config._locale = config._locale || locale_locales__getLocale(config._l);
if (input === null || (format === undefined && input === '')) {
return valid__createInvalid({nullInput: true});
}
if (typeof input === 'string') {
config._i = input = config._locale.preparse(input);
}
if (isMoment(input)) {
return new Moment(checkOverflow(input));
} else if (isArray(format)) {
configFromStringAndArray(config);
} else if (isDate(input)) {
config._d = input;
} else if (format) {
configFromStringAndFormat(config);
} else {
configFromInput(config);
}
if (!valid__isValid(config)) {
config._d = null;
}
return config;
}
function configFromInput(config) {
var input = config._i;
if (input === undefined) {
config._d = new Date(utils_hooks__hooks.now());
} else if (isDate(input)) {
config._d = new Date(input.valueOf());
} else if (typeof input === 'string') {
configFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
configFromArray(config);
} else if (typeof(input) === 'object') {
configFromObject(config);
} else if (typeof(input) === 'number') {
// from milliseconds
config._d = new Date(input);
} else {
utils_hooks__hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC (input, format, locale, strict, isUTC) {
var c = {};
if (typeof(locale) === 'boolean') {
strict = locale;
locale = undefined;
}
if ((isObject(input) && isObjectEmpty(input)) ||
(isArray(input) && input.length === 0)) {
input = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = true;
c._useUTC = c._isUTC = isUTC;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
return createFromConfig(c);
}
function local__createLocal (input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, false);
}
var prototypeMin = deprecate(
'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = local__createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return valid__createInvalid();
}
}
);
var prototypeMax = deprecate(
'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = local__createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return valid__createInvalid();
}
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return local__createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
function min () {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
function max () {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
var now = function () {
return Date.now ? Date.now() : +(new Date());
};
function Duration (duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
// representation for dateAddRemove
this._milliseconds = +milliseconds +
seconds * 1e3 + // 1000
minutes * 6e4 + // 1000 * 60
hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
// Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days +
weeks * 7;
// It is impossible translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months +
quarters * 3 +
years * 12;
this._data = {};
this._locale = locale_locales__getLocale();
this._bubble();
}
function isDuration (obj) {
return obj instanceof Duration;
}
// FORMATTING
function offset (token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset();
var sign = '+';
if (offset < 0) {
offset = -offset;
sign = '-';
}
return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
});
}
offset('Z', ':');
offset('ZZ', '');
// PARSING
addRegexToken('Z', matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var matches = ((string || '').match(matcher) || []);
var chunk = matches[matches.length - 1] || [];
var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
var minutes = +(parts[1] * 60) + toInt(parts[2]);
return parts[0] === '+' ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff = (isMoment(input) || isDate(input) ? input.valueOf() : local__createLocal(input).valueOf()) - res.valueOf();
// Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff);
utils_hooks__hooks.updateOffset(res, false);
return res;
} else {
return local__createLocal(input).local();
}
}
function getDateOffset (m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
utils_hooks__hooks.updateOffset = function () {};
// MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset (input, keepLocalTime) {
var offset = this._offset || 0,
localAdjust;
if (!this.isValid()) {
return input != null ? this : NaN;
}
if (input != null) {
if (typeof input === 'string') {
input = offsetFromString(matchShortOffset, input);
} else if (Math.abs(input) < 16) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
utils_hooks__hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
function getSetZone (input, keepLocalTime) {
if (input != null) {
if (typeof input !== 'string') {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
function setOffsetToUTC (keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
function setOffsetToLocal (keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), 'm');
}
}
return this;
}
function setOffsetToParsedOffset () {
if (this._tzm) {
this.utcOffset(this._tzm);
} else if (typeof this._i === 'string') {
this.utcOffset(offsetFromString(matchOffset, this._i));
}
return this;
}
function hasAlignedHourOffset (input) {
if (!this.isValid()) {
return false;
}
input = input ? local__createLocal(input).utcOffset() : 0;
return (this.utcOffset() - input) % 60 === 0;
}
function isDaylightSavingTime () {
return (
this.utcOffset() > this.clone().month(0).utcOffset() ||
this.utcOffset() > this.clone().month(5).utcOffset()
);
}
function isDaylightSavingTimeShifted () {
if (!isUndefined(this._isDSTShifted)) {
return this._isDSTShifted;
}
var c = {};
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a);
this._isDSTShifted = this.isValid() &&
compareArrays(c._a, other.toArray()) > 0;
} else {
this._isDSTShifted = false;
}
return this._isDSTShifted;
}
function isLocal () {
return this.isValid() ? !this._isUTC : false;
}
function isUtcOffset () {
return this.isValid() ? this._isUTC : false;
}
function isUtc () {
return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
// ASP.NET json date format regex
var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/;
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
function create__createDuration (input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms : input._milliseconds,
d : input._days,
M : input._months
};
} else if (typeof input === 'number') {
duration = {};
if (key) {
duration[key] = input;
} else {
duration.milliseconds = input;
}
} else if (!!(match = aspNetRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : 0,
d : toInt(match[DATE]) * sign,
h : toInt(match[HOUR]) * sign,
m : toInt(match[MINUTE]) * sign,
s : toInt(match[SECOND]) * sign,
ms : toInt(match[MILLISECOND]) * sign
};
} else if (!!(match = isoRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : parseIso(match[2], sign),
M : parseIso(match[3], sign),
w : parseIso(match[4], sign),
d : parseIso(match[5], sign),
h : parseIso(match[6], sign),
m : parseIso(match[7], sign),
s : parseIso(match[8], sign)
};
} else if (duration == null) {// checks for null or undefined
duration = {};
} else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to));
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
return ret;
}
create__createDuration.fn = Duration.prototype;
function parseIso (inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {milliseconds: 0, months: 0};
res.months = other.month() - base.month() +
(other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return {milliseconds: 0, months: 0};
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
function absRound (number) {
if (number < 0) {
return Math.round(-1 * number) * -1;
} else {
return Math.round(number);
}
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
//invert the arguments, but complain about it
if (period !== null && !isNaN(+period)) {
deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
tmp = val; val = period; period = tmp;
}
val = typeof val === 'string' ? +val : val;
dur = create__createDuration(val, period);
add_subtract__addSubtract(this, dur, direction);
return this;
};
}
function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = absRound(duration._days),
months = absRound(duration._months);
if (!mom.isValid()) {
// No op
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
}
if (days) {
get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding);
}
if (months) {
setMonth(mom, get_set__get(mom, 'Month') + months * isAdding);
}
if (updateOffset) {
utils_hooks__hooks.updateOffset(mom, days || months);
}
}
var add_subtract__add = createAdder(1, 'add');
var add_subtract__subtract = createAdder(-1, 'subtract');
function getCalendarFormat(myMoment, now) {
var diff = myMoment.diff(now, 'days', true);
return diff < -6 ? 'sameElse' :
diff < -1 ? 'lastWeek' :
diff < 0 ? 'lastDay' :
diff < 1 ? 'sameDay' :
diff < 2 ? 'nextDay' :
diff < 7 ? 'nextWeek' : 'sameElse';
}
function moment_calendar__calendar (time, formats) {
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || local__createLocal(),
sod = cloneWithOffset(now, this).startOf('day'),
format = utils_hooks__hooks.calendarFormat(this, sod) || 'sameElse';
var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
return this.format(output || this.localeData().calendar(format, this, local__createLocal(now)));
}
function clone () {
return new Moment(this);
}
function isAfter (input, units) {
var localInput = isMoment(input) ? input : local__createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
if (units === 'millisecond') {
return this.valueOf() > localInput.valueOf();
} else {
return localInput.valueOf() < this.clone().startOf(units).valueOf();
}
}
function isBefore (input, units) {
var localInput = isMoment(input) ? input : local__createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
if (units === 'millisecond') {
return this.valueOf() < localInput.valueOf();
} else {
return this.clone().endOf(units).valueOf() < localInput.valueOf();
}
}
function isBetween (from, to, units, inclusivity) {
inclusivity = inclusivity || '()';
return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
(inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
}
function isSame (input, units) {
var localInput = isMoment(input) ? input : local__createLocal(input),
inputMs;
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units || 'millisecond');
if (units === 'millisecond') {
return this.valueOf() === localInput.valueOf();
} else {
inputMs = localInput.valueOf();
return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
}
}
function isSameOrAfter (input, units) {
return this.isSame(input, units) || this.isAfter(input,units);
}
function isSameOrBefore (input, units) {
return this.isSame(input, units) || this.isBefore(input,units);
}
function diff (input, units, asFloat) {
var that,
zoneDelta,
delta, output;
if (!this.isValid()) {
return NaN;
}
that = cloneWithOffset(input, this);
if (!that.isValid()) {
return NaN;
}
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
units = normalizeUnits(units);
if (units === 'year' || units === 'month' || units === 'quarter') {
output = monthDiff(this, that);
if (units === 'quarter') {
output = output / 3;
} else if (units === 'year') {
output = output / 12;
}
} else {
delta = this - that;
output = units === 'second' ? delta / 1e3 : // 1000
units === 'minute' ? delta / 6e4 : // 1000 * 60
units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
delta;
}
return asFloat ? output : absFloor(output);
}
function monthDiff (a, b) {
// difference in months
var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, 'months'),
anchor2, adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor2 - anchor);
}
//check for negative zero, return zero if negative zero
return -(wholeMonthDiff + adjust) || 0;
}
utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
utils_hooks__hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
function toString () {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}
function moment_format__toISOString () {
var m = this.clone().utc();
if (0 < m.year() && m.year() <= 9999) {
if (isFunction(Date.prototype.toISOString)) {
// native implementation is ~50x faster, use it when we can
return this.toDate().toISOString();
} else {
return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
} else {
return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
}
function format (inputString) {
if (!inputString) {
inputString = this.isUtc() ? utils_hooks__hooks.defaultFormatUtc : utils_hooks__hooks.defaultFormat;
}
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}
function from (time, withoutSuffix) {
if (this.isValid() &&
((isMoment(time) && time.isValid()) ||
local__createLocal(time).isValid())) {
return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function fromNow (withoutSuffix) {
return this.from(local__createLocal(), withoutSuffix);
}
function to (time, withoutSuffix) {
if (this.isValid() &&
((isMoment(time) && time.isValid()) ||
local__createLocal(time).isValid())) {
return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function toNow (withoutSuffix) {
return this.to(local__createLocal(), withoutSuffix);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale (key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = locale_locales__getLocale(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
}
var lang = deprecate(
'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
}
);
function localeData () {
return this._locale;
}
function startOf (units) {
units = normalizeUnits(units);
// the following switch intentionally omits break keywords
// to utilize falling through the cases.
switch (units) {
case 'year':
this.month(0);
/* falls through */
case 'quarter':
case 'month':
this.date(1);
/* falls through */
case 'week':
case 'isoWeek':
case 'day':
case 'date':
this.hours(0);
/* falls through */
case 'hour':
this.minutes(0);
/* falls through */
case 'minute':
this.seconds(0);
/* falls through */
case 'second':
this.milliseconds(0);
}
// weeks are a special case
if (units === 'week') {
this.weekday(0);
}
if (units === 'isoWeek') {
this.isoWeekday(1);
}
// quarters are also special
if (units === 'quarter') {
this.month(Math.floor(this.month() / 3) * 3);
}
return this;
}
function endOf (units) {
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond') {
return this;
}
// 'date' is an alias for 'day', so it should be considered as such.
if (units === 'date') {
units = 'day';
}
return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
}
function to_type__valueOf () {
return this._d.valueOf() - ((this._offset || 0) * 60000);
}
function unix () {
return Math.floor(this.valueOf() / 1000);
}
function toDate () {
return new Date(this.valueOf());
}
function toArray () {
var m = this;
return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
}
function toObject () {
var m = this;
return {
years: m.year(),
months: m.month(),
date: m.date(),
hours: m.hours(),
minutes: m.minutes(),
seconds: m.seconds(),
milliseconds: m.milliseconds()
};
}
function toJSON () {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}
function moment_valid__isValid () {
return valid__isValid(this);
}
function parsingFlags () {
return extend({}, getParsingFlags(this));
}
function invalidAt () {
return getParsingFlags(this).overflow;
}
function creationData() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict
};
}
// FORMATTING
addFormatToken(0, ['gg', 2], 0, function () {
return this.weekYear() % 100;
});
addFormatToken(0, ['GG', 2], 0, function () {
return this.isoWeekYear() % 100;
});
function addWeekYearFormatToken (token, getter) {
addFormatToken(0, [token, token.length], 0, getter);
}
addWeekYearFormatToken('gggg', 'weekYear');
addWeekYearFormatToken('ggggg', 'weekYear');
addWeekYearFormatToken('GGGG', 'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');
// ALIASES
addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');
// PRIORITY
addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);
// PARSING
addRegexToken('G', matchSigned);
addRegexToken('g', matchSigned);
addRegexToken('GG', match1to2, match2);
addRegexToken('gg', match1to2, match2);
addRegexToken('GGGG', match1to4, match4);
addRegexToken('gggg', match1to4, match4);
addRegexToken('GGGGG', match1to6, match6);
addRegexToken('ggggg', match1to6, match6);
addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
});
addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
week[token] = utils_hooks__hooks.parseTwoDigitYear(input);
});
// MOMENTS
function getSetWeekYear (input) {
return getSetWeekYearHelper.call(this,
input,
this.week(),
this.weekday(),
this.localeData()._week.dow,
this.localeData()._week.doy);
}
function getSetISOWeekYear (input) {
return getSetWeekYearHelper.call(this,
input, this.isoWeek(), this.isoWeekday(), 1, 4);
}
function getISOWeeksInYear () {
return weeksInYear(this.year(), 1, 4);
}
function getWeeksInYear () {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
if (input == null) {
return weekOfYear(this, dow, doy).year;
} else {
weeksTarget = weeksInYear(input, dow, doy);
if (week > weeksTarget) {
week = weeksTarget;
}
return setWeekAll.call(this, input, week, weekday, dow, doy);
}
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
this.year(date.getUTCFullYear());
this.month(date.getUTCMonth());
this.date(date.getUTCDate());
return this;
}
// FORMATTING
addFormatToken('Q', 0, 'Qo', 'quarter');
// ALIASES
addUnitAlias('quarter', 'Q');
// PRIORITY
addUnitPriority('quarter', 7);
// PARSING
addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
array[MONTH] = (toInt(input) - 1) * 3;
});
// MOMENTS
function getSetQuarter (input) {
return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}
// FORMATTING
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIOROITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0], 10);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet('Date', true);
// FORMATTING
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
// ALIASES
addUnitAlias('dayOfYear', 'DDD');
// PRIORITY
addUnitPriority('dayOfYear', 4);
// PARSING
addRegexToken('DDD', match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
config._dayOfYear = toInt(input);
});
// HELPERS
// MOMENTS
function getSetDayOfYear (input) {
var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
}
// FORMATTING
addFormatToken('m', ['mm', 2], 0, 'minute');
// ALIASES
addUnitAlias('minute', 'm');
// PRIORITY
addUnitPriority('minute', 14);
// PARSING
addRegexToken('m', match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);
// MOMENTS
var getSetMinute = makeGetSet('Minutes', false);
// FORMATTING
addFormatToken('s', ['ss', 2], 0, 'second');
// ALIASES
addUnitAlias('second', 's');
// PRIORITY
addUnitPriority('second', 15);
// PARSING
addRegexToken('s', match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);
// MOMENTS
var getSetSecond = makeGetSet('Seconds', false);
// FORMATTING
addFormatToken('S', 0, 0, function () {
return ~~(this.millisecond() / 100);
});
addFormatToken(0, ['SS', 2], 0, function () {
return ~~(this.millisecond() / 10);
});
addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
return this.millisecond() * 1000000;
});
// ALIASES
addUnitAlias('millisecond', 'ms');
// PRIORITY
addUnitPriority('millisecond', 16);
// PARSING
addRegexToken('S', match1to3, match1);
addRegexToken('SS', match1to3, match2);
addRegexToken('SSS', match1to3, match3);
var token;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
addRegexToken(token, matchUnsigned);
}
function parseMs(input, array) {
array[MILLISECOND] = toInt(('0.' + input) * 1000);
}
for (token = 'S'; token.length <= 9; token += 'S') {
addParseToken(token, parseMs);
}
// MOMENTS
var getSetMillisecond = makeGetSet('Milliseconds', false);
// FORMATTING
addFormatToken('z', 0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');
// MOMENTS
function getZoneAbbr () {
return this._isUTC ? 'UTC' : '';
}
function getZoneName () {
return this._isUTC ? 'Coordinated Universal Time' : '';
}
var momentPrototype__proto = Moment.prototype;
momentPrototype__proto.add = add_subtract__add;
momentPrototype__proto.calendar = moment_calendar__calendar;
momentPrototype__proto.clone = clone;
momentPrototype__proto.diff = diff;
momentPrototype__proto.endOf = endOf;
momentPrototype__proto.format = format;
momentPrototype__proto.from = from;
momentPrototype__proto.fromNow = fromNow;
momentPrototype__proto.to = to;
momentPrototype__proto.toNow = toNow;
momentPrototype__proto.get = stringGet;
momentPrototype__proto.invalidAt = invalidAt;
momentPrototype__proto.isAfter = isAfter;
momentPrototype__proto.isBefore = isBefore;
momentPrototype__proto.isBetween = isBetween;
momentPrototype__proto.isSame = isSame;
momentPrototype__proto.isSameOrAfter = isSameOrAfter;
momentPrototype__proto.isSameOrBefore = isSameOrBefore;
momentPrototype__proto.isValid = moment_valid__isValid;
momentPrototype__proto.lang = lang;
momentPrototype__proto.locale = locale;
momentPrototype__proto.localeData = localeData;
momentPrototype__proto.max = prototypeMax;
momentPrototype__proto.min = prototypeMin;
momentPrototype__proto.parsingFlags = parsingFlags;
momentPrototype__proto.set = stringSet;
momentPrototype__proto.startOf = startOf;
momentPrototype__proto.subtract = add_subtract__subtract;
momentPrototype__proto.toArray = toArray;
momentPrototype__proto.toObject = toObject;
momentPrototype__proto.toDate = toDate;
momentPrototype__proto.toISOString = moment_format__toISOString;
momentPrototype__proto.toJSON = toJSON;
momentPrototype__proto.toString = toString;
momentPrototype__proto.unix = unix;
momentPrototype__proto.valueOf = to_type__valueOf;
momentPrototype__proto.creationData = creationData;
// Year
momentPrototype__proto.year = getSetYear;
momentPrototype__proto.isLeapYear = getIsLeapYear;
// Week Year
momentPrototype__proto.weekYear = getSetWeekYear;
momentPrototype__proto.isoWeekYear = getSetISOWeekYear;
// Quarter
momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter;
// Month
momentPrototype__proto.month = getSetMonth;
momentPrototype__proto.daysInMonth = getDaysInMonth;
// Week
momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek;
momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek;
momentPrototype__proto.weeksInYear = getWeeksInYear;
momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear;
// Day
momentPrototype__proto.date = getSetDayOfMonth;
momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek;
momentPrototype__proto.weekday = getSetLocaleDayOfWeek;
momentPrototype__proto.isoWeekday = getSetISODayOfWeek;
momentPrototype__proto.dayOfYear = getSetDayOfYear;
// Hour
momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour;
// Minute
momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute;
// Second
momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond;
// Millisecond
momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond;
// Offset
momentPrototype__proto.utcOffset = getSetOffset;
momentPrototype__proto.utc = setOffsetToUTC;
momentPrototype__proto.local = setOffsetToLocal;
momentPrototype__proto.parseZone = setOffsetToParsedOffset;
momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset;
momentPrototype__proto.isDST = isDaylightSavingTime;
momentPrototype__proto.isLocal = isLocal;
momentPrototype__proto.isUtcOffset = isUtcOffset;
momentPrototype__proto.isUtc = isUtc;
momentPrototype__proto.isUTC = isUtc;
// Timezone
momentPrototype__proto.zoneAbbr = getZoneAbbr;
momentPrototype__proto.zoneName = getZoneName;
// Deprecations
momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
momentPrototype__proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
var momentPrototype = momentPrototype__proto;
function moment__createUnix (input) {
return local__createLocal(input * 1000);
}
function moment__createInZone () {
return local__createLocal.apply(null, arguments).parseZone();
}
function preParsePostFormat (string) {
return string;
}
var prototype__proto = Locale.prototype;
prototype__proto.calendar = locale_calendar__calendar;
prototype__proto.longDateFormat = longDateFormat;
prototype__proto.invalidDate = invalidDate;
prototype__proto.ordinal = ordinal;
prototype__proto.preparse = preParsePostFormat;
prototype__proto.postformat = preParsePostFormat;
prototype__proto.relativeTime = relative__relativeTime;
prototype__proto.pastFuture = pastFuture;
prototype__proto.set = locale_set__set;
// Month
prototype__proto.months = localeMonths;
prototype__proto.monthsShort = localeMonthsShort;
prototype__proto.monthsParse = localeMonthsParse;
prototype__proto.monthsRegex = monthsRegex;
prototype__proto.monthsShortRegex = monthsShortRegex;
// Week
prototype__proto.week = localeWeek;
prototype__proto.firstDayOfYear = localeFirstDayOfYear;
prototype__proto.firstDayOfWeek = localeFirstDayOfWeek;
// Day of Week
prototype__proto.weekdays = localeWeekdays;
prototype__proto.weekdaysMin = localeWeekdaysMin;
prototype__proto.weekdaysShort = localeWeekdaysShort;
prototype__proto.weekdaysParse = localeWeekdaysParse;
prototype__proto.weekdaysRegex = weekdaysRegex;
prototype__proto.weekdaysShortRegex = weekdaysShortRegex;
prototype__proto.weekdaysMinRegex = weekdaysMinRegex;
// Hours
prototype__proto.isPM = localeIsPM;
prototype__proto.meridiem = localeMeridiem;
function lists__get (format, index, field, setter) {
var locale = locale_locales__getLocale();
var utc = create_utc__createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl (format, index, field) {
if (typeof format === 'number') {
index = format;
format = undefined;
}
format = format || '';
if (index != null) {
return lists__get(format, index, field, 'month');
}
var i;
var out = [];
for (i = 0; i < 12; i++) {
out[i] = lists__get(format, i, field, 'month');
}
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl (localeSorted, format, index, field) {
if (typeof localeSorted === 'boolean') {
if (typeof format === 'number') {
index = format;
format = undefined;
}
format = format || '';
} else {
format = localeSorted;
index = format;
localeSorted = false;
if (typeof format === 'number') {
index = format;
format = undefined;
}
format = format || '';
}
var locale = locale_locales__getLocale(),
shift = localeSorted ? locale._week.dow : 0;
if (index != null) {
return lists__get(format, (index + shift) % 7, field, 'day');
}
var i;
var out = [];
for (i = 0; i < 7; i++) {
out[i] = lists__get(format, (i + shift) % 7, field, 'day');
}
return out;
}
function lists__listMonths (format, index) {
return listMonthsImpl(format, index, 'months');
}
function lists__listMonthsShort (format, index) {
return listMonthsImpl(format, index, 'monthsShort');
}
function lists__listWeekdays (localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}
function lists__listWeekdaysShort (localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}
function lists__listWeekdaysMin (localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}
locale_locales__getSetGlobalLocale('en', {
ordinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal : function (number) {
var b = number % 10,
output = (toInt(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
}
});
// Side effect imports
utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale);
utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale);
var mathAbs = Math.abs;
function duration_abs__abs () {
var data = this._data;
this._milliseconds = mathAbs(this._milliseconds);
this._days = mathAbs(this._days);
this._months = mathAbs(this._months);
data.milliseconds = mathAbs(data.milliseconds);
data.seconds = mathAbs(data.seconds);
data.minutes = mathAbs(data.minutes);
data.hours = mathAbs(data.hours);
data.months = mathAbs(data.months);
data.years = mathAbs(data.years);
return this;
}
function duration_add_subtract__addSubtract (duration, input, value, direction) {
var other = create__createDuration(input, value);
duration._milliseconds += direction * other._milliseconds;
duration._days += direction * other._days;
duration._months += direction * other._months;
return duration._bubble();
}
// supports only 2.0-style add(1, 's') or add(duration)
function duration_add_subtract__add (input, value) {
return duration_add_subtract__addSubtract(this, input, value, 1);
}
// supports only 2.0-style subtract(1, 's') or subtract(duration)
function duration_add_subtract__subtract (input, value) {
return duration_add_subtract__addSubtract(this, input, value, -1);
}
function absCeil (number) {
if (number < 0) {
return Math.floor(number);
} else {
return Math.ceil(number);
}
}
function bubble () {
var milliseconds = this._milliseconds;
var days = this._days;
var months = this._months;
var data = this._data;
var seconds, minutes, hours, years, monthsFromDays;
// if we have a mix of positive and negative values, bubble down first
// check: https://github.com/moment/moment/issues/2166
if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
(milliseconds <= 0 && days <= 0 && months <= 0))) {
milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
days = 0;
months = 0;
}
// The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000;
seconds = absFloor(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absFloor(seconds / 60);
data.minutes = minutes % 60;
hours = absFloor(minutes / 60);
data.hours = hours % 24;
days += absFloor(hours / 24);
// convert days to months
monthsFromDays = absFloor(daysToMonths(days));
months += monthsFromDays;
days -= absCeil(monthsToDays(monthsFromDays));
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
return this;
}
function daysToMonths (days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return days * 4800 / 146097;
}
function monthsToDays (months) {
// the reverse of daysToMonths
return months * 146097 / 4800;
}
function as (units) {
var days;
var months;
var milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === 'month' || units === 'year') {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
return units === 'month' ? months : months / 12;
} else {
// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months));
switch (units) {
case 'week' : return days / 7 + milliseconds / 6048e5;
case 'day' : return days + milliseconds / 864e5;
case 'hour' : return days * 24 + milliseconds / 36e5;
case 'minute' : return days * 1440 + milliseconds / 6e4;
case 'second' : return days * 86400 + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
default: throw new Error('Unknown unit ' + units);
}
}
}
// TODO: Use this.as('ms')?
function duration_as__valueOf () {
return (
this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6
);
}
function makeAs (alias) {
return function () {
return this.as(alias);
};
}
var asMilliseconds = makeAs('ms');
var asSeconds = makeAs('s');
var asMinutes = makeAs('m');
var asHours = makeAs('h');
var asDays = makeAs('d');
var asWeeks = makeAs('w');
var asMonths = makeAs('M');
var asYears = makeAs('y');
function duration_get__get (units) {
units = normalizeUnits(units);
return this[units + 's']();
}
function makeGetter(name) {
return function () {
return this._data[name];
};
}
var milliseconds = makeGetter('milliseconds');
var seconds = makeGetter('seconds');
var minutes = makeGetter('minutes');
var hours = makeGetter('hours');
var days = makeGetter('days');
var months = makeGetter('months');
var years = makeGetter('years');
function weeks () {
return absFloor(this.days() / 7);
}
var round = Math.round;
var thresholds = {
s: 45, // seconds to minute
m: 45, // minutes to hour
h: 22, // hours to day
d: 26, // days to month
M: 11 // months to year
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) {
var duration = create__createDuration(posNegDuration).abs();
var seconds = round(duration.as('s'));
var minutes = round(duration.as('m'));
var hours = round(duration.as('h'));
var days = round(duration.as('d'));
var months = round(duration.as('M'));
var years = round(duration.as('y'));
var a = seconds < thresholds.s && ['s', seconds] ||
minutes <= 1 && ['m'] ||
minutes < thresholds.m && ['mm', minutes] ||
hours <= 1 && ['h'] ||
hours < thresholds.h && ['hh', hours] ||
days <= 1 && ['d'] ||
days < thresholds.d && ['dd', days] ||
months <= 1 && ['M'] ||
months < thresholds.M && ['MM', months] ||
years <= 1 && ['y'] || ['yy', years];
a[2] = withoutSuffix;
a[3] = +posNegDuration > 0;
a[4] = locale;
return substituteTimeAgo.apply(null, a);
}
// This function allows you to set the rounding function for relative time strings
function duration_humanize__getSetRelativeTimeRounding (roundingFunction) {
if (roundingFunction === undefined) {
return round;
}
if (typeof(roundingFunction) === 'function') {
round = roundingFunction;
return true;
}
return false;
}
// This function allows you to set a threshold for relative time strings
function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) {
if (thresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return thresholds[threshold];
}
thresholds[threshold] = limit;
return true;
}
function humanize (withSuffix) {
var locale = this.localeData();
var output = duration_humanize__relativeTime(this, !withSuffix, locale);
if (withSuffix) {
output = locale.pastFuture(+this, output);
}
return locale.postformat(output);
}
var iso_string__abs = Math.abs;
function iso_string__toISOString() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
var seconds = iso_string__abs(this._milliseconds) / 1000;
var days = iso_string__abs(this._days);
var months = iso_string__abs(this._months);
var minutes, hours, years;
// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60);
hours = absFloor(minutes / 60);
seconds %= 60;
minutes %= 60;
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
var Y = years;
var M = months;
var D = days;
var h = hours;
var m = minutes;
var s = seconds;
var total = this.asSeconds();
if (!total) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return 'P0D';
}
return (total < 0 ? '-' : '') +
'P' +
(Y ? Y + 'Y' : '') +
(M ? M + 'M' : '') +
(D ? D + 'D' : '') +
((h || m || s) ? 'T' : '') +
(h ? h + 'H' : '') +
(m ? m + 'M' : '') +
(s ? s + 'S' : '');
}
var duration_prototype__proto = Duration.prototype;
duration_prototype__proto.abs = duration_abs__abs;
duration_prototype__proto.add = duration_add_subtract__add;
duration_prototype__proto.subtract = duration_add_subtract__subtract;
duration_prototype__proto.as = as;
duration_prototype__proto.asMilliseconds = asMilliseconds;
duration_prototype__proto.asSeconds = asSeconds;
duration_prototype__proto.asMinutes = asMinutes;
duration_prototype__proto.asHours = asHours;
duration_prototype__proto.asDays = asDays;
duration_prototype__proto.asWeeks = asWeeks;
duration_prototype__proto.asMonths = asMonths;
duration_prototype__proto.asYears = asYears;
duration_prototype__proto.valueOf = duration_as__valueOf;
duration_prototype__proto._bubble = bubble;
duration_prototype__proto.get = duration_get__get;
duration_prototype__proto.milliseconds = milliseconds;
duration_prototype__proto.seconds = seconds;
duration_prototype__proto.minutes = minutes;
duration_prototype__proto.hours = hours;
duration_prototype__proto.days = days;
duration_prototype__proto.weeks = weeks;
duration_prototype__proto.months = months;
duration_prototype__proto.years = years;
duration_prototype__proto.humanize = humanize;
duration_prototype__proto.toISOString = iso_string__toISOString;
duration_prototype__proto.toString = iso_string__toISOString;
duration_prototype__proto.toJSON = iso_string__toISOString;
duration_prototype__proto.locale = locale;
duration_prototype__proto.localeData = localeData;
// Deprecations
duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString);
duration_prototype__proto.lang = lang;
// Side effect imports
// FORMATTING
addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');
// PARSING
addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
config._d = new Date(parseFloat(input, 10) * 1000);
});
addParseToken('x', function (input, array, config) {
config._d = new Date(toInt(input));
});
// Side effect imports
utils_hooks__hooks.version = '2.14.1';
setHookCallback(local__createLocal);
utils_hooks__hooks.fn = momentPrototype;
utils_hooks__hooks.min = min;
utils_hooks__hooks.max = max;
utils_hooks__hooks.now = now;
utils_hooks__hooks.utc = create_utc__createUTC;
utils_hooks__hooks.unix = moment__createUnix;
utils_hooks__hooks.months = lists__listMonths;
utils_hooks__hooks.isDate = isDate;
utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale;
utils_hooks__hooks.invalid = valid__createInvalid;
utils_hooks__hooks.duration = create__createDuration;
utils_hooks__hooks.isMoment = isMoment;
utils_hooks__hooks.weekdays = lists__listWeekdays;
utils_hooks__hooks.parseZone = moment__createInZone;
utils_hooks__hooks.localeData = locale_locales__getLocale;
utils_hooks__hooks.isDuration = isDuration;
utils_hooks__hooks.monthsShort = lists__listMonthsShort;
utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin;
utils_hooks__hooks.defineLocale = defineLocale;
utils_hooks__hooks.updateLocale = updateLocale;
utils_hooks__hooks.locales = locale_locales__listLocales;
utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort;
utils_hooks__hooks.normalizeUnits = normalizeUnits;
utils_hooks__hooks.relativeTimeRounding = duration_humanize__getSetRelativeTimeRounding;
utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold;
utils_hooks__hooks.calendarFormat = getCalendarFormat;
utils_hooks__hooks.prototype = momentPrototype;
var _moment = utils_hooks__hooks;
return _moment;
}));
|
require('whatwg-fetch');
var fetch = window.fetch;
class Client {
constructor(url) {
this.url = url;
}
get(path) {
console.log(fetch)
var fullPath = `${this.url}${path}`;
return window.fetch(fullPath)
.then(function(response) {
return new Promise(response.json());
}).then(function(json) {
return Promise.resolve(json);
}).catch(function(ex) {
console.log('parsing failed', ex)
})
}
}
var api = new Client('http://www.reddit.com');
api.get('/users')
.catch(function() {
console.log('error')
}) |
function verifyCurrentState(context, moduleMeta, currentState) {
var id = moduleMeta.id;
return (
context.controllers.registry.hasModule(id) &&
context.controllers.registry.getModuleState(id) === currentState
);
}
function setState(context, currentState, nextState) {
return function(moduleMeta) {
if (context.controllers.registry.hasModule(moduleMeta.id)) {
if (!moduleMeta.state || moduleMeta.state === currentState) {
moduleMeta = moduleMeta.withState(nextState);
}
context.controllers.registry.setModule(moduleMeta);
return moduleMeta;
}
throw new Error("Unable to set state because module does not exist");
};
}
function runService(context, currentState, nextState, service, moduleMeta) {
return verifyCurrentState(context, moduleMeta, currentState) ?
service.runAsync(moduleMeta).then(setState(context, currentState, nextState)) :
Promise.resolve(moduleMeta);
}
function runServiceSync(context, currentState, nextState, service, moduleMeta) {
return verifyCurrentState(context, moduleMeta, currentState) ?
setState(context, currentState, nextState)(service.runSync(moduleMeta)) :
moduleMeta;
}
function serviceRunner(context, currentState, nextState, service) {
return function serviceRunnerDelegate(moduleMeta) {
return runService(context, currentState, nextState, service, moduleMeta);
};
}
function serviceRunnerSync(context, currentState, nextState, service) {
return function serviceRunnerSyncDelegate(moduleMeta) {
return runServiceSync(context, currentState, nextState, service, moduleMeta);
};
}
module.exports = {
serviceRunner: serviceRunner,
serviceRunnerSync: serviceRunnerSync,
runService: runService,
runServiceSync: runServiceSync
};
|
(function () {
'use strict';
function bounceOut(time, begin, change, duration) {
if ((time /= duration) < 1 / 2.75) {
return change * (7.5625 * time * time) + begin;
} else if (time < 2 / 2.75) {
return change * (7.5625 * (time -= 1.5 / 2.75) * time + 0.75) + begin;
} else if (time < 2.5 / 2.75) {
return change * (7.5625 * (time -= 2.25 / 2.75) * time + 0.9375) + begin;
} else {
return change * (7.5625 * (time -= 2.625 / 2.75) * time + 0.984375) + begin;
}
}
function bounceIn(time, begin, change, duration) {
return change - bounceOut(duration - time, 0, change, duration) + begin;
}
function bounceInOut(time, begin, change, duration) {
if (time < duration / 2) {
return bounceIn(time * 2, 0, change, duration) * 0.5 + begin;
} else {
return bounceOut(time * 2 - duration, 0, change, duration) * 0.5 + change * 0.5 + begin;
}
};
function circIn(time, begin, change, duration) {
return -change * (Math.sqrt(1 - (time = time / duration) * time) - 1) + begin;
};
function circOut(time, begin, change, duration) {
return change * Math.sqrt(1 - (time = time / duration - 1) * time) + begin;
};
function circInOut(time, begin, change, duration) {
if ((time = time / (duration / 2)) < 1) {
return -change / 2 * (Math.sqrt(1 - time * time) - 1) + begin;
} else {
return change / 2 * (Math.sqrt(1 - (time -= 2) * time) + 1) + begin;
}
};
function cubicIn(time, begin, change, duration) {
return change * (time /= duration) * time * time + begin;
};
function cubicOut(time, begin, change, duration) {
return change * ((time = time / duration - 1) * time * time + 1) + begin;
};
function cubicInOut(time, begin, change, duration) {
if ((time = time / (duration / 2)) < 1) {
return change / 2 * time * time * time + begin;
} else {
return change / 2 * ((time -= 2) * time * time + 2) + begin;
}
};
function expoIn(time, begin, change, duration) {
if (time === 0) {
return begin;
}
return change * Math.pow(2, 10 * (time / duration - 1)) + begin;
};
function expoOut(time, begin, change, duration) {
if (time === duration) {
return begin + change;
}
return change * (-Math.pow(2, -10 * time / duration) + 1) + begin;
};
function expoInOut(time, begin, change, duration) {
if (time === 0) {
return begin;
} else if (time === duration) {
return begin + change;
} else if ((time = time / (duration / 2)) < 1) {
return change / 2 * Math.pow(2, 10 * (time - 1)) + begin;
} else {
return change / 2 * (-Math.pow(2, -10 * (time - 1)) + 2) + begin;
}
};
function linear(time, begin, change, duration) {
return change * time / duration + begin;
};
function quadIn(time, begin, change, duration) {
return change * (time = time / duration) * time + begin;
};
function quadOut(time, begin, change, duration) {
return -change * (time = time / duration) * (time - 2) + begin;
};
function quadInOut(time, begin, change, duration) {
if ((time = time / (duration / 2)) < 1) {
return change / 2 * time * time + begin;
} else {
return -change / 2 * ((time -= 1) * (time - 2) - 1) + begin;
}
};
function quartIn(time, begin, change, duration) {
return change * (time = time / duration) * time * time * time + begin;
};
function quartOut(time, begin, change, duration) {
return -change * ((time = time / duration - 1) * time * time * time - 1) + begin;
};
function quartInOut(time, begin, change, duration) {
if ((time = time / (duration / 2)) < 1) {
return change / 2 * time * time * time * time + begin;
} else {
return -change / 2 * ((time -= 2) * time * time * time - 2) + begin;
}
};
function quintIn(time, begin, change, duration) {
return change * (time = time / duration) * time * time * time * time + begin;
};
function quintOut(time, begin, change, duration) {
return change * ((time = time / duration - 1) * time * time * time * time + 1) + begin;
};
function quintInOut(time, begin, change, duration) {
if ((time = time / (duration / 2)) < 1) {
return change / 2 * time * time * time * time * time + begin;
} else {
return change / 2 * ((time -= 2) * time * time * time * time + 2) + begin;
}
};
function sineIn(time, begin, change, duration) {
return -change * Math.cos(time / duration * (Math.PI / 2)) + change + begin;
};
function sineOut(time, begin, change, duration) {
return change * Math.sin(time / duration * (Math.PI / 2)) + begin;
};
function sineInOut(time, begin, change, duration) {
return -change / 2 * (Math.cos(Math.PI * time / duration) - 1) + begin;
};
var Ease = {
bounceOut: bounceOut,
bounceIn: bounceIn,
bounceInOut: bounceInOut,
circIn: circIn,
circOut: circOut,
circInOut: circInOut,
cubicIn: cubicIn,
cubicOut: cubicOut,
cubicInOut: cubicInOut,
expoIn: expoIn,
expoOut: expoOut,
expoInOut: expoInOut,
linear: linear,
quadIn: quadIn,
quadOut: quadOut,
quadInOut: quadInOut,
quartIn: quartIn,
quartOut: quartOut,
quartInOut: quartInOut,
quintIn: quintIn,
quintOut: quintOut,
quintInOut: quintInOut,
sineIn: sineIn,
sineOut: sineOut,
sineInOut: sineInOut
}
if (typeof exports === 'object') {
module.exports = Ease;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return Ease;
});
} else {
this.Ease = Ease;
}
}.call(this)); |
define(['dispatcher'], function(dispatcher) {
"use strict";
//local
var initialized = false;
var items = {};
var _handleEvent = function(e) {
if (e.type === 'video-add') {
if (items.hasOwnProperty(e.id)) return;
items[e.id] = {
id: e.id,
status: 'not-ready'
}
}
if (e.type === 'video-remove') {
if (!items.hasOwnProperty(e.id)) return;
delete items[e.id];
}
if (e.type === 'video-ready') {
if (items.hasOwnProperty(e.id)) {
items[e.id].status = 'ready';
eventEmitter.dispatch({
type: 'change'
});
}
}
if (e.type === 'video-play') {
if (items.hasOwnProperty(e.id)) {
items[e.id].status = 'play';
eventEmitter.dispatch({
type: 'change'
});
}
}
if (e.type === 'video-stop') {
if (items.hasOwnProperty(e.id)) {
items[e.id].status = 'stop';
eventEmitter.dispatch({
type: 'change'
});
}
}
if (e.type === 'video-reset') {
if (items.hasOwnProperty(e.id)) {
items[e.id].status = 'not-ready';
eventEmitter.dispatch({
type: 'change'
});
}
}
}
var _init = function() {
items = {};
if (initialized) return;
initialized = true;
dispatcher.subscribe(_handleEvent);
}
var eventEmitter = function() {
var _handlers = [];
var dispatch = function(event) {
for (var i = _handlers.length - 1; i >= 0; i--) {
_handlers[i](event);
}
}
var subscribe = function(handler) {
_handlers.push(handler);
}
var unsubscribe = function(handler) {
for (var i = 0; i <= _handlers.length - 1; i++) {
if (_handlers[i] == handler) {
_handlers.splice(i--, 1);
}
}
}
return {
dispatch: dispatch,
subscribe: subscribe,
unsubscribe: unsubscribe
}
}();
var getData = function() {
return {
items: items
}
}
if (!initialized) {
_init();
}
return {
eventEmitter: eventEmitter,
getData: getData
}
}); |
import { fromJS, List as iList } from 'immutable';
import { keysIn } from 'lodash';
const initialState = fromJS({ loading: false, slope: false, course: false, club: false,
holes: [], currentHole: 0, shots: {} });
// // normally this would be imported from /constants, but in trying to keep
// // this starter kit as small as possible we'll just define it here.
// const COUNTER_INCREMENT = 'COUNTER_INCREMENT';
// export default createReducer(initialState, {
// [COUNTER_INCREMENT] : (state) => state + 1
// });
export default function play(state = initialState, action) {
switch ( action.type ) {
case 'SELECT_ITEM':
return state.set(action.model, fromJS(action.item));
case 'DE_SELECT_ITEM':
return state.set(action.model, false);
case 'REQUEST_HOLES':
return state.set('loading', true);
case 'RECEIVE_HOLES':
const firstShots = {};
action.holes.map((hole) => { firstShots[hole.id] = [{lie: 'TEE', finished: false}]; });
return state.merge({holes: fromJS(action.holes), loading: false, shots: firstShots});
case 'CHANGE_HOLE':
return state.merge({currentHole: action.index});
case 'SET_SHOT_DATA':
const shot = fromJS(action.shot);
const searchPath = ['shots', '' + action.holeId + ''];
const shotList = state.getIn(searchPath);
if ( shotList === undefined ) {
return state.setIn(searchPath, iList.of(shot));
} else {
// TODO - this seems pretty wrong!
const oldShot = shotList.get(action.shotIndex);
let newShot = oldShot.merge(shot);
let finished = false;
// All regular properties are there
const requiredKeys = ['success', 'lie', 'club', 'goingFor', 'endLie'];
const foundKeys = keysIn(newShot.toJS());
if ( requiredKeys.every(key => foundKeys.indexOf(key) !== -1) ) {
finished = true;
// Special rules apply for Approach shot
if (newShot.get('goingFor') === 'GREEN') {
finished = newShot.get('distanceFromHole') !== undefined;
}
// Special rule for putt
if (newShot.get('goingFor') === 'HOLE') {
finished = newShot.get('distance') !== undefined;
}
// Special rules also apply for Misses
if (newShot.get('success') === false && !newShot.get('putt')) {
finished = newShot.get('missPosition') !== undefined;
}
}
newShot = newShot.set('finished', finished);
let newShotList = shotList.set(action.shotIndex, newShot);
if ( newShot.get('finished') && newShot.get('endLie') !== 'IN THE HOLE') {
newShotList = newShotList.set(action.shotIndex + 1, fromJS({lie: newShot.get('endLie')}));
}
return state.setIn(searchPath, newShotList);
}
break;
case 'REMOVE_SHOT':
const path = ['shots', '' + action.holeId + ''];
const shots = state.getIn(path);
return state.setIn(path, shots.delete(action.index));
case 'END_ROUND':
return initialState;
default:
return state;
}
}
|
/**
* Created by roderickWang on 8/27/15.
*/
import {MainTypes} from '../constants/ActionTypes';
import Immutable from 'immutable';
import binding from 'redux-2way-binding';
let bindingStore = binding.bindingStore;
const initialState = Immutable.fromJS({
tree: []
});
//TODO defend override redux,write more code
export default bindingStore('menus', initialState, {
[MainTypes.LOAD_MENU]: (data, action) => {
return data.merge(Immutable.fromJS(action.data));
}
})
|
require.config({
paths: {
jquery: '../lib/jquery/jquery-1.8.2.min',
bootstrap: '../lib/bootstrap3/js/bootstrap',
underscore: '../lib/underscore/underscore',
angular: '../lib/angular/angular.min',
angularResource: '../lib/angular/angular-resource',
text: '../lib/require/text',
i18n: '../lib/require/i18n',
/* modernizr: '../lib/modernizr',
html5shiv: '../lib/html5shiv',*/
/* mcore: '../lib/mcore.min',*/
/* fullscreen: '../lib/fullscreen',*/
/* mcustomscrollbar: '../lib/jquery.mCustomScrollbar.concat.min',*/
/* detectbrowser: '../lib/detectbrowser',*/
//res:'../resources/nls/res'
ichart: '../lib/ichart.1.2.src' ,
/* jqueryui:'../lib/jquery-ui-1.10.3.custom' ,*/
/* bootstrapModal:'../lib/bootstrap/js/modal',
bootstrapAlert:'../lib/bootstrap/js/alert',
bootstrapButton:'../lib/bootstrap/js/button',
bootstrapTab:'../lib/bootstrap/js/tab',
bootstrapTooltip:'../lib/bootstrap/js/tooltip',*/
/* jqueryuniform: '../lib/uniform/jquery.uniform.min',*/
linqjs:'../lib/linq',
'angular-strap':'../lib/angular-strap/angular-strap',
'bootstrap-datepicker':'../lib/angular-strap/bootstrap-datepicker' ,
"async":'../lib/async',
"moment": "../lib/moment.min",
"handlebars":"../lib/handlebars",
"icheck":"../lib/icheck/jquery.icheck" ,
"pr-angular":"../lib/pr-angular/pr-angular"
},
shim: {
'angular': {deps: ['jquery'],'exports': 'angular'},
'angular-resource': {deps: ['angular']},
'pr-angular' : {deps: ['angular']},
'bootstrap-datepicker': {deps: ['jquery']},
'angular-strap': {deps: ['angular','bootstrap-datepicker']},
'bootstrap': {deps: ['jquery']},
/*'mcustomscrollbar': {deps: ['jquery']},*/
'jqueryui':{deps: ['jquery']},
'icheck': {deps: ['jquery']},
'underscore': {exports: '_'}
/* 'detectbrowser': {deps: ['modernizr']} ,*/
/* 'bootstrapModal': {deps: ['jquery']},
'bootstrapAlert': {deps: ['jquery']},
'bootstrapButton': {deps: ['jquery']},
'bootstrapTab': {deps: ['jquery']}*/
/*,
'res':{exports:'res'}*/
},
priority: [
"angular"
],
i18n: {
locale: 'en-us'
},
urlArgs: 'v=1.0.0.1'
});
require(['angular',
'app',
'jquery',
'bootstrap',
'controllers/layout',
'controllers/index',
'directives/compare',
'filter/filters' ,
'services/services',
'controllers/include/analysisInclude',
'controllers/leftmenu/index',
'routes'/*,
'detectbrowser'*/
], function (angular) {
angular.bootstrap(document, ['app',function($interpolateProvider){
$interpolateProvider.startSymbol('{{');
$interpolateProvider.endSymbol('}}');
}]);
console.log("Welcome visit Reunion System! ") ;
});
|
/*game.EnemyDeathManager = Object.extend({
//
init: function(x, y, settings){
//always updates function
this.alwaysUpdate = true;
},
update: function(){
if(game.data.player.dead){
//if player dies
me.game.world.removeChild(game.data.player);
//remove player
me.game.world.removeChild(game.data.miniPlayer);
me.state.current().resetPlayer(10, 0);
//resettin player to set coordinates
}
return true;
//return true
}
}); |
'use strict';
var UTILS = require('../utils/utils');
/**
* @constructor
*/
var Analytics = function (options) {
this.options = options;
this.prepare();
this.load();
this.addJsErrorsTracking();
};
// METHODS
Analytics.prototype.prepare = function () {
window._gaq = window._gaq || [];
window._gaq.push(['_setAccount', this.options.GOOGLE_ANALYTICS]);
window._gaq.push(['_trackPageview']);
};
Analytics.prototype.load = function () {
UTILS.loadScript(
('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +
'.google-analytics.com/ga.js'
);
};
Analytics.prototype.addJsErrorsTracking = function () {
window['onerror'] = function (msg, url, line) {
window._gaq.push([
'_trackEvent',
'JavaScript Errors',
msg,
url + " : " + line,
new Date().toUTCString() + ' | ' + navigator.userAgent,
true]);
};
};
exports.Analytics = Analytics; |
import angular from 'angular';
import Header from './header';
import Sidebar from './sidebar';
import Modal from './modal';
let commonModule = angular.module('app.common', [
Header,
Sidebar,
Modal
])
.name;
export default commonModule;
|
import Ember from 'ember';
import componentChild from 'ember-bootstrap/mixins/component-child';
/**
* Mixin for components that act as dropdown toggles.
*
* @class DropdownToggle
* @namespace Mixins
* @public
*/
export default Ember.Mixin.create(componentChild, {
classNames: ['dropdown-toggle'],
attributeBindings: ['data-toggle'],
/**
* @property ariaRole
* @default button
* @type string
* @protected
*/
ariaRole: 'button',
'data-toggle': 'dropdown',
targetObject: Ember.computed.alias('parentView'),
/**
* The default action is set to "toggleDropdown" on the parent {{#crossLink "Components.Dropdown"}}{{/crossLink}}
*
* @property action
* @default toggleDropdown
* @type string
* @protected
*/
action: 'toggleDropdown'
}); |
/**
* Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland.
*
* See the file license.txt for copying permission.
*/
define([
'Underscore',
'jquery'
], function (_, $) {
'use strict';
var ToolbarProvider = function (tbTpl, tbDef) {
this.toolbarTpl = tbTpl;
this.toolbarDef = tbDef;
};
ToolbarProvider.prototype.orderToolbarItems = function (toolbarDef) {
toolbarDef.groups = _.sortBy(toolbarDef.groups, 'index');
_.each(toolbarDef.groups, function (grp) {
grp.items = _.sortBy(grp.items, 'index');
});
return toolbarDef;
};
/**
* Applies defaults to the objs array. If forceApply is true the defaults overwrite values in the
* array, otherwise they are only applied if the object has no value for that property.
* Recursively sets defaults in the the items array.
*/
ToolbarProvider.prototype.applyDefaults = function (objs, defaults, forceApply, defaultCommand) {
var dflt = defaults.group || defaults;
objs.forEach(function (obj) {
Object.keys(dflt).forEach(function (propName) {
if (forceApply || obj[propName] === undefined) {
obj[propName] = dflt[propName];
}
});
if (defaultCommand) {
this.setCommand(obj);
}
if (obj.items) {
this.applyDefaults(obj.items, defaults.item, forceApply, false);
}
}.bind(this));
};
/**
* Changes the index of objects to get them into the desired order. Doesn't actually move the objects.
*/
ToolbarProvider.prototype.orderObjects = function (objects, oldIndex, newIndex) {
objects.forEach(function (obj) {
if ((oldIndex < newIndex) && (obj.index > oldIndex && obj.index <= newIndex)) {
obj.index--;
} else if ((oldIndex > newIndex) && (obj.index >= newIndex && obj.index < oldIndex)) {
obj.index++;
}
});
};
ToolbarProvider.prototype.findInList = function (list, id) {
return _.find(list, function (obj) {
return obj.id === id;
});
};
ToolbarProvider.prototype.findItem = function (groups, items, itemId) {
var item = this.findInList(items, itemId);
if (!item) {
_.find(groups, function (grp) {
item = this.findInList(grp.items, itemId);
return !!item;
}, this);
if (item) {
item = $.extend(true, {}, item);
items.push(item);
}
}
return item;
};
/**
* Names of the toolbar json defs that can be changed via configureToolbar.
*/
ToolbarProvider.prototype.TOOLBAR_GROUP_PROPS = [
'active',
'command',
'commandArgs',
'cssClass',
'hidden',
'index',
'label',
'repeat',
'selectId',
'type',
'value'
];
/**
* Sets properties in srcObj from those in editObj. forceUpdate indicates whether editObj values
* will overwrite values in srcObj.
*/
ToolbarProvider.prototype.updateObject = function (srcObj, editObj, forceUpdate) {
var args = [editObj].concat(ToolbarProvider.prototype.TOOLBAR_GROUP_PROPS),
editProps = _.pick.apply(null, args);
Object.keys(editProps).forEach(function (propName) {
if (srcObj[propName] === undefined || forceUpdate) {
srcObj[propName] = editObj[propName];
}
});
};
/**
* Updates srcItems to reflect the changes specified in editItems.
*/
ToolbarProvider.prototype.mergeItems = function (srcGroups, srcGroup, editGroup) {
var srcItems = srcGroup.items;
editGroup.items.forEach(function (editItem) {
var srcItem = this.findItem(srcGroups, srcItems, editItem.id);
if (srcItem) {
if (editItem.index !== undefined) {
this.orderObjects(srcItems, srcItem.index, editItem.index);
}
this.updateObject(srcItem, editItem, true);
} else {
srcGroup.items.push($.extend({}, editItem));
this.orderObjects(srcItems, 0, editItem.index);
}
}, this);
};
/**
* Applies the default setting for the command and commandArgs group properties if appropriate.
*/
ToolbarProvider.prototype.setCommand = function (group) {
if (group.command === undefined) {
group.command = 'showTab';
}
if (group.commandArgs === undefined) {
group.commandArgs = group.id;
}
};
/**
* Merges the edit definitions into the src definitions to produce a merged toolbar definition.
* src and edits are arrays of objects. Updates the src array in place. Adjusts index properties
* as needed.
*/
ToolbarProvider.prototype.mergeGroups = function (src, edits) {
edits.forEach(function (editGrp) {
var srcGrp = this.findInList(src, editGrp.id);
if (!srcGrp) {
srcGrp = $.extend({}, editGrp);
this.setCommand(srcGrp);
srcGrp.items = [];
src.push(srcGrp);
if (editGrp.items) {
this.mergeItems(src, srcGrp, editGrp);
}
} else {
if (editGrp.index !== undefined) {
this.orderObjects(src, srcGrp.index, editGrp.index);
}
this.updateObject(srcGrp, editGrp, true);
if (editGrp.items) {
this.mergeItems(src, srcGrp, editGrp);
}
}
}, this);
};
/**
* These will be overriden by any defaults specified via the configureToolbar function argument.
*/
ToolbarProvider.prototype.TOOLBAR_DEFAULTS = {
hidden: false,
active: false
};
/**
* Property names in the defaults object that are ignored when copying top level properties to the
* more specific group and item default objects.
*/
ToolbarProvider.prototype.TOOLBAR_DEFAULTS_EXCLUDE = [
'group',
'item'
];
/**
* Create an object that contains the defaults for this configuration. Any top level defaults properties
* specified in the definition are used for both groups and items unless overriden by more specific values
* in the group or item default objects.
* No defaults results in the fallback values being used for both groups and items.
*/
ToolbarProvider.prototype.createDefaults = function (suppliedDefaults) {
var result = {},
defaults = suppliedDefaults || {};
result.group = $.extend(true, {}, this.TOOLBAR_DEFAULTS);
result.item = $.extend(true, {}, this.TOOLBAR_DEFAULTS);
if (defaults) {
// Copy global defaults into each of the local default objects
Object.keys(defaults).forEach(function (propName) {
if (ToolbarProvider.prototype.TOOLBAR_DEFAULTS_EXCLUDE.indexOf(propName) < 0) {
result.group[propName] = defaults[propName];
result.item[propName] = defaults[propName];
}
});
// Copy the local default objects
if (defaults.group) {
Object.keys(defaults.group).forEach(function (propName) {
result.group[propName] = defaults.group[propName];
});
}
if (defaults.item) {
Object.keys(defaults.item).forEach(function (propName) {
result.item[propName] = defaults.item[propName];
});
}
}
return result;
};
ToolbarProvider.prototype.DEFAULT_SETTINGS = {
group: {},
item: {}
};
/**
* New definition will be appied on top of the current definition after the defaults have been
* applied. Defaults overwrite properties in the current definition but not in the supplied
* definition.
* The returned value is the html for the toolbar.
*/
ToolbarProvider.prototype.createToolbar = function (def, suppliedSettings) {
var workingDef = $.extend(true, {}, this.toolbarDef),
workingDefaults = this.createDefaults(workingDef.defaults),
editDefaults = this.createDefaults(def.defaults),
settings = suppliedSettings ? this.createDefaults(suppliedSettings) : this.DEFAULT_SETTINGS,
editGroups = def.groups || [];
this.applyDefaults(workingDef.groups, workingDefaults, false, true);
this.applyDefaults(workingDef.groups, settings, true, true);
this.applyDefaults(editGroups, editDefaults, false, true);
this.mergeGroups(workingDef.groups, editGroups);
this.orderToolbarItems(workingDef);
this.toolbarDef = workingDef;
return _.template(this.toolbarTpl)(workingDef);
};
/**
* Returns the name of the group that contains the most non hidden items.
*/
ToolbarProvider.prototype.getWidestGroupName = function () {
var widestTabObj = this.toolbarDef.groups.filter(function (grp) {
return !grp.hidden;
}).map(function (grp) {
var length = grp.items.reduce(function (count, item) {
return item.hidden ? count : count + 1;
}, 0);
return {
id: grp.id,
length: length
};
}),
id;
if (widestTabObj.length) {
widestTabObj = widestTabObj.reduce(function (prevObj, currentObj) {
return currentObj.length > prevObj.length ? currentObj : prevObj;
});
id = widestTabObj.id;
}
return id;
};
/**
* Returns the name of the active group.
*/
ToolbarProvider.prototype.getActiveGroupName = function () {
var firstVisibleGroupId,
activeGroup = _.find(this.toolbarDef.groups, function (grp) {
if (!grp.hidden) {
firstVisibleGroupId = firstVisibleGroupId || grp.id;
}
return grp.active && !grp.hidden;
});
return (activeGroup && activeGroup.id) || firstVisibleGroupId;
};
/**
* Returns the most recent toolbar definition.
*/
ToolbarProvider.prototype.getToolbarDefinition = function () {
return this.toolbarDef;
};
return ToolbarProvider;
});
|
/**
Module: marchio-datastore
Test: smoke-test
Author: Mitch Allen
*/
/*jshint node: true */
/*jshint mocha: true */
/*jshint esversion: 6 */
"use strict";
var request = require('supertest'),
should = require('should'),
killable = require('killable'),
modulePath = "../modules/index",
GOOGLE_TEST_PROJECT = process.env.MARCHIO_GOOGLE_PROJECT_ID,
TEST_PORT = process.env.MARCHIO_PORT || 8080;
var getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
};
describe('module factory smoke test', () => {
var _factory = null;
var _server = null;
var _testModel = {
name: 'datastore-test',
fields: {
email: { type: String, required: true },
status: { type: String, required: true, default: "NEW" },
// In a real world example, password would be hashed by middleware before being saved
password: { type: String, select: false }, // select: false, exclude from query results
// alpha: { type: String, required: true, default: "AAA" },
// beta : { type: String, default: "BBB" },
}
};
var _hashPassword = function( req, res, next ) {
console.log(req.body);
// if req.body, if req.body.password
// req.body.password = "zorro";
next();
}
var _testHost = `http://localhost:${TEST_PORT}`;
var _postUrl = `/${_testModel.name}`;
before( done => {
delete require.cache[require.resolve(modulePath)];
_factory = require(modulePath);
done();
});
after( done => {
// Call after all tests
done();
});
beforeEach( done => {
// Call before each test
_server = null;
done();
});
afterEach( done => {
// Call after each test
if( _server ) {
// console.log("killing server");
_server.kill(() => {});
}
_server = null;
done();
});
it('module should exist', done => {
should.exist(_factory);
done();
});
it('create method with no spec should be rejected', done => {
_factory.create()
.catch( function(err) {
// We are expecting this error
// console.error(err.message);
err.message.should.eql(_factory.ERROR.MODEL_MUST_BE_DEFINED)
done(); // to pass on err, remove err (done() - no arguments)
}).catch( function(err) {
// We are NOT expecting this error
// console.error(err.message);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with no http route enabled should be rejected', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel
})
// Need dual catch incase should eql fails
.catch( function(err) {
// We are expecting this error
// console.error(err.message);
err.message.should.eql(_factory.ERROR.NO_HTTP_METHODS_ENABLED);
done(); // to pass on err, remove err (done() - no arguments)
})
.catch( function(err) {
// We are NOT expecting this error
// console.error(err.message);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with post set to true should return object', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true
})
.then(function(obj){
should.exist(obj);
done();
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with post set to false should return object', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: false
})
// Need dual catch incase should eql fails
.catch( function(err) {
// We are expecting this error
// console.error(err.message);
err.message.should.eql(_factory.ERROR.NO_HTTP_METHODS_ENABLED);
done(); // to pass on err, remove err (done() - no arguments)
})
.catch( function(err) {
// We are NOT expecting this error
// console.error(err.message);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with get set to true should return object', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
get: true
})
.then(function(obj){
should.exist(obj);
done();
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with get set to false should return object', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
get: false
})
// Need dual catch incase should eql fails
.catch( function(err) {
// We are expecting this error
// console.error(err.message);
err.message.should.eql(_factory.ERROR.NO_HTTP_METHODS_ENABLED);
done(); // to pass on err, remove err (done() - no arguments)
})
.catch( function(err) {
// We are NOT expecting this error
// console.error(err.message);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with post and get set to true should return object', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true
})
.then(function(obj){
should.exist(obj);
done();
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with post set to true and get set to false should return object', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: false
})
.then(function(obj){
should.exist(obj);
done();
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('create method with post set to false and get set to true should return object', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: false,
get: true
})
.then(function(obj){
should.exist(obj);
done();
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('post should succeed', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
request(_testHost)
.post(_postUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(201)
.expect('Content-Type', /json/)
.expect('Location', /datastore-test\/\d{16}/ )
// .expect('Location', /\d{16}/ )
.end(function (err, res) {
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
// // Should not return password
should.not.exist(res.body.password);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
res.header.location.should.eql(`/${_testModel.name}/${res.body._id}`)
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('post with invalid model name in url should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
var _invalidPostUrl = "/bogus";
request(_testHost)
.post(_invalidPostUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(404)
.end(function (err, res) {
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('get should succeed', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// SETUP - need to post at least one record
request(_testHost)
.post(_postUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(201)
.expect('Content-Type', /json/)
.expect('Location', /datastore-test\/\d{16}/ )
.end(function (err, res) {
should.not.exist(err);
should.exist(res);
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
// GET
var _recordId = res.body._id;
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
res.header.location.should.eql(_getUrl);
request(_testHost)
.get(_getUrl)
.expect(200)
.expect('Location', _getUrl )
.end(function (err, res) {
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
// // Should not return password
should.not.exist(res.body.password);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
done();
});
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('numeric false should have no effect', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
numeric: false,
post: true,
get: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// SETUP - need to post at least one record
request(_testHost)
.post(_postUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(201)
.expect('Content-Type', /json/)
.expect('Location', /datastore-test\/\d{16}/ )
.end(function (err, res) {
should.not.exist(err);
should.exist(res);
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
// GET
var _recordId = res.body._id;
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
request(_testHost)
.get(_getUrl)
.expect(200)
.expect('Content-Type', /json/)
.expect('Location', _getUrl )
.end(function (err, res) {
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
// // Should not return password
should.not.exist(res.body.password);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
done();
});
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('numeric true should have no effect', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
numeric: true,
post: true,
get: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// SETUP - need to post at least one record
request(_testHost)
.post(_postUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(201)
.expect('Content-Type', /json/)
.expect('Location', /datastore-test\/\d{16}/ )
.end(function (err, res) {
should.not.exist(err);
should.exist(res);
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
// GET
var _recordId = res.body._id;
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
request(_testHost)
.get(_getUrl)
.expect(200)
.expect('Location', _getUrl )
.end(function (err, res) {
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
// // Should not return password
should.not.exist(res.body.password);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
done();;
});
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('get for a non-existent id should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// GET
var _recordId = '12345678';
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
request(_testHost)
.get(_getUrl)
.expect(404)
.end(function (err, res) {
should.not.exist(err);
// console.log(res.body);
done();;
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('get for a non-numeric id should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// GET
var _recordId = 'BOGUS';
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
request(_testHost)
.get(_getUrl)
.expect(404)
.end(function (err, res) {
should.not.exist(err);
// console.log(res.body);
res.body.error.should.containEql('not a valid id');
done();;
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('put should succeed', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
put: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "testput" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// SETUP - need to post at least one record
request(_testHost)
.post(_postUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(201)
.expect('Content-Type', /json/)
.expect('Location', /datastore-test\/\d{16}/ )
.end(function (err, res) {
should.not.exist(err);
should.exist(res);
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
// PUT
var _recordId = res.body._id;
var _putUrl = `/${_testModel.name}/${_recordId}`;
// console.log("PUT URL: ", _putUrl);
request(_testHost)
.put(_putUrl)
// PROBLEM: hashed password is not included and Datastore doesn't do partial updates
.send({ email: testObject.email, status: "UPDATED" })
// .send({ status: "UPDATED" })
.set('Content-Type', 'application/json')
.expect('Location', _putUrl )
.expect(204) // No content returned
.end(function (err, res) {
should.not.exist(err);
// No content, nothing to verify
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
request(_testHost)
.get(_getUrl)
// Get ALL fields, verify password intact.
.query( { fields: 'email password status'} )
.expect(200)
.end(function (err, res) {
should.not.exist(err);
// console.log("RECORD: ", res.body);
res.body.email.should.eql(testObject.email);
// Should return password based on fields query
should.exist(res.body.password);
// In production the password would be hashed and would not match
res.body.password.should.eql(testObject.password);
res.body.status.should.eql("UPDATED");
should.exist(res.body._id);
done();
});
});
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('put for non-existent id should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
put: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "testput" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// PUT
var _recordId = '123456';
var _putUrl = `/${_testModel.name}/${_recordId}`;
// console.log("PUT URL: ", _putUrl);
request(_testHost)
.put(_putUrl)
.send({ email: testObject.email, status: "UPDATED" })
// .send({ status: "UPDATED" })
.set('Content-Type', 'application/json')
.expect(404) // No content returned
.end(function (err, res) {
should.not.exist(err);
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('put for non-numeric id should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
put: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "testput" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// PUT
var _recordId = 'BOGUS';
var _putUrl = `/${_testModel.name}/${_recordId}`;
// console.log("PUT URL: ", _putUrl);
request(_testHost)
.put(_putUrl)
.send({ email: testObject.email, status: "UPDATED" })
.set('Content-Type', 'application/json')
.expect(404) // No content returned
.end(function (err, res) {
should.not.exist(err);
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('delete should succeed', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
del: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// SETUP - need to post at least one record
request(_testHost)
.post(_postUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(201)
.expect('Content-Type', /json/)
.expect('Location', /datastore-test\/\d{16}/ )
.end(function (err, res) {
should.not.exist(err);
should.exist(res);
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
// DELETE
var _recordId = res.body._id;
var _delUrl = `/${_testModel.name}/${_recordId}`;
// console.log("DEL URL: ", _delUrl);
request(_testHost)
.del(_delUrl)
.expect(204)
.end(function (err, res) {
should.not.exist(err);
// GET (make sure it's gone - expect 404)
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
request(_testHost)
.get(_getUrl)
.expect(404)
.end(function (err, res) {
should.not.exist(err);
// console.log(res.body);
res.body.error.should.containEql('not found');
done();;
});
});
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('delete for a non-existent id should return 204', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
del: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// DELETE
var _recordId = '12345678';
var _delUrl = `/${_testModel.name}/${_recordId}`;
// console.log("DEL URL: ", _delUrl);
request(_testHost)
.del(_delUrl)
.expect(204)
.end(function (err, res) {
should.not.exist(err);
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('delete for a non-numeric id should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
del: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "test" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
// console.log(`TEST HOST: ${_testHost} `);
// DELETE
var _recordId = 'BOGUS';
var _delUrl = `/${_testModel.name}/${_recordId}`;
// console.log("DEL URL: ", _delUrl);
request(_testHost)
.del(_delUrl)
.expect(404)
.end(function (err, res) {
should.not.exist(err);
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('patch should succeed', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
patch: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "testpatch" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
var patchStatus = "UPDATED PATCH STATUS",
testPatch = [
// { "op": "remove", "path": "/password" }
{"op": "replace", "path": "/status", "value": patchStatus }
];
// SETUP - need to post at least one record
request(_testHost)
.post(_postUrl)
.send(testObject)
.set('Content-Type', 'application/json')
.expect(201)
.expect('Content-Type', /json/)
.expect('Location', /datastore-test\/\d{16}/ )
.end(function (err, res) {
should.not.exist(err);
should.exist(res);
should.not.exist(err);
// console.log(res.body);
res.body.email.should.eql(testObject.email);
res.body.status.should.eql("NEW");
should.exist(res.body._id);
// PATCH
var _recordId = res.body._id;
var _patchUrl = `/${_testModel.name}/${_recordId}`;
// console.log("PATCH URL: ", _patchUrl);
request(_testHost)
.patch(_patchUrl)
.send( testPatch )
.set('Content-Type', 'application/json')
.expect(204)
.end(function (err, res) {
should.not.exist(err);
// GET
var _getUrl = `/${_testModel.name}/${_recordId}`;
// console.log("GET URL: ", _getUrl);
request(_testHost)
.get(_getUrl)
.expect(200)
.end(function (err, res) {
should.not.exist(err);
res.body.email.should.eql(testObject.email);
// // Should not return password
should.not.exist(res.body.password);
res.body.status.should.eql(patchStatus);
should.exist(res.body._id);
done();;
});
});
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('patch for non-existent id should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
put: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "testpatch" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
var patchStatus = "UPDATED PATCH STATUS",
testPatch = [
// { "op": "remove", "path": "/password" }
{"op": "replace", "path": "/status", "value": patchStatus }
];
// PATCH
var _recordId = '123456';
var _patchUrl = `/${_testModel.name}/${_recordId}`;
request(_testHost)
.patch(_patchUrl)
.send( testPatch )
.set('Content-Type', 'application/json')
.expect(404)
.end(function (err, res) {
should.not.exist(err);
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
it('patch for non-numeric id should return 404', done => {
_factory.create({
projectId: GOOGLE_TEST_PROJECT,
model: _testModel,
post: true,
get: true,
put: true
})
.then(function(app) {
_server = app.listen(TEST_PORT, () => {
// console.log(`listening on port ${TEST_PORT}`);
});
killable(_server);
return Promise.resolve(true);
})
.then( () => {
var testObject = {
email: "testput" + getRandomInt( 1000, 1000000) + "@smoketest.cloud",
password: "fubar"
};
var patchStatus = "UPDATED PATCH STATUS",
testPatch = [
// { "op": "remove", "path": "/password" }
{"op": "replace", "path": "/status", "value": patchStatus }
];
// PATCH
var _recordId = 'BOGUS';
var _patchUrl = `/${_testModel.name}/${_recordId}`;
request(_testHost)
.patch(_patchUrl)
.send(testPatch)
.set('Content-Type', 'application/json')
.expect(404)
.end(function (err, res) {
should.not.exist(err);
done();
});
})
.catch( function(err) {
console.error(err);
done(err); // to pass on err, remove err (done() - no arguments)
});
});
});
|
var gulp = require('gulp'),
msbuild = require("gulp-msbuild"),
mocha = require("gulp-mocha"),
replace = require('gulp-replace'),
rimraf = require('rimraf'),
runSequence = require('run-sequence'),
baseBuildFile = require('../gulpfile');
gulp.task("win8.1-build",
function(cb){
runSequence( "clean", "win8.1-version", "win8.1-package", "win8.1-deploy", cb);
});
gulp.task("win8.1-version", function () {
var args = baseBuildFile.parseEnv();
var buildNum = args.version.major + "."
+ args.version.minor + "."
+ args.version.revision + "."
+ args.version.build;
return gulp.src('./src/**/package.appxmanifest', { base: './' })
.pipe(replace(/\sVersion=\"[^\"]+\"\s/, ' Version=\"' + buildNum + '\" '))
.pipe(gulp.dest('./'));
});
gulp.task("win8.1-package", function () {
return gulp.src("./Win10Rocks-JS-Starter-win8.1.sln")
.pipe(msbuild({
targets: ['Clean', 'Build'],
toolsVersion: 14.0,
properties: {
AppxBundle: 'Always'
}
}));
});
gulp.task("win8.1-deploy", function () {
gulp.src('./src/app-win8.1/AppPackages/**/*')
.pipe(gulp.dest('./publish/win8.1'));
});
|
var searchData =
[
['operator_2a', ['operator*', ['../classrational.html#acbaf4f76b2caf4aafb850202e29d69ce', 1, 'rational::operator*(const int rhs) const '], ['../classrational.html#a13f267e5cdafffcc44203762548bb5cd', 1, 'rational::operator*(const rational &rhs) const ']]],
['operator_2b_3d', ['operator+=', ['../classrational.html#a9b83ad0c803d2ac242b42e71d954a356', 1, 'rational']]],
['operator_3c_3c', ['operator<<', ['../classrational.html#a5b7c78fca4537715369ba7da02abb4df', 1, 'rational']]],
['operator_3d_3d', ['operator==', ['../classrational.html#a5f9a93cc7fd6309f5eae4c76d81f28d5', 1, 'rational']]]
];
|
'use strict';
var _ = require('lodash')
, TypeSafeMatcher = require('./TypeSafeMatcher')
;
function IsArray() {
return _.create(new TypeSafeMatcher(), {
isExpectedType: function (actual) {
return _.isArray(actual);
},
describeTo: function (description) {
description
.append('an array');
}
});
}
IsArray.array = function () {
return new IsArray();
};
module.exports = IsArray;
|
{
jestExpect(small).not.toBeGreaterThan(big);
}
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'ui.bootstrap',
'infinite-scroll',
'myApp.projects',
'myApp.people',
'myApp.version'
])
.constant('underscore', _)
.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/projects'});
}]);
|
var tree={"files":["LinkedinLogin.js"]}; |
// TODO : Like stylus
module.exports = function(src, module, makeModule, options) {
throw new Error("sass parser not implemented yet")
} |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function()
{
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined, function()
{
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's URL contains a 'g' ...
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: '://scholar.google.com' },
})
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
}); |
/**
* Copyright 2016 aixigo AG
* Released under the MIT license.
* http://laxarjs.org/license
*/
import './artifact_provider_mock_spec';
import './browser_mock_spec';
import './configuration_mock_spec';
import './control_loader_mock_spec';
import './event_bus_mock_spec';
import './flow_service_mock_spec';
import './heartbeat_mock_spec';
import './log_mock_spec';
import './storage_mock_spec';
import './timer_mock_spec';
import './tooling_mock_spec';
import './widget_services_area_helper_mock_spec';
import './widget_services_assets_mock_spec';
import './widget_services_i18n_mock_spec';
import './widget_services_storage_mock_spec';
import './widget_services_visibility_mock_spec';
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Saturation = exports.Hue = exports.EditableInput = exports.Checkboard = exports.Alpha = undefined;
var _Alpha = require('./Alpha');
var _Alpha2 = _interopRequireDefault(_Alpha);
var _Checkboard = require('./Checkboard');
var _Checkboard2 = _interopRequireDefault(_Checkboard);
var _EditableInput = require('./EditableInput');
var _EditableInput2 = _interopRequireDefault(_EditableInput);
var _Hue = require('./Hue');
var _Hue2 = _interopRequireDefault(_Hue);
var _Saturation = require('./Saturation');
var _Saturation2 = _interopRequireDefault(_Saturation);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.Alpha = _Alpha2.default;
exports.Checkboard = _Checkboard2.default;
exports.EditableInput = _EditableInput2.default;
exports.Hue = _Hue2.default;
exports.Saturation = _Saturation2.default; |
import React from 'react';
import Router from 'react-router';
export default class AuthenticationRequired extends React.Component {
constructor(props){
super(props)
}
render () {
if(this.props.user.authenticated){
return (this.props.children)
}
return null
}
}
|
import HaloItem from 'src/components/halo/lively-halo-item.js';
export default class HaloVivideOpenScriptEditorItem extends HaloItem {
// #TODO: drag ScriptEditor out of this halo item
async onClick(evt) {
const inspectTarget = window.that;
this.hideHalo();
const scriptEditor = await inspectTarget.createScriptEditor();
scriptEditor.initialFocus();
}
updateTarget(view) {
this._view = view;
}
}
|
module.exports = {
options: {
sassDir: "app/styles",
cssDir: "tmp/result/assets",
generatedImagesDir: "tmp/result/images",
imagesDir: "public/images",
javascriptsDir: "app",
fontsDir: "public/fonts",
importPath: ["vendor"],
httpImagesPath: "/images",
httpGeneratedImagesPath: "/images/generated",
httpFontsPath: "/fonts",
relativeAssets: false,
debugInfo: true
},
compile: {}
};
|
import React from 'react';
import { parse } from 'react-docgen';
import CodeExample from '../../../components/CodeExample';
import ComponentHeader from '../../../components/ComponentHeader';
import PropTypeDescription from '../../../components/PropTypeDescription';
import Demo from './Demo';
// eslint-disable-next-line
import demoCode from '!raw-loader!./Demo';
// eslint-disable-next-line
import componentCode from '!raw-loader!ringcentral-widgets/components/ContactDisplay';
const ContactDisplayPage = () => {
const info = parse(componentCode);
return (
<div>
<ComponentHeader name="ContactDisplay" description={info.description} />
<CodeExample
code={demoCode}
title="ContactDisplay Example"
>
<Demo />
</CodeExample>
<PropTypeDescription componentInfo={info} />
</div>
);
};
export default ContactDisplayPage;
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var Svg = document.documentElement;
var playArea = document.getElementById('PlayArea');
var playAreaBorder = document.getElementById('PlayAreaBorder');
var P = new PlayArea(playArea, playAreaBorder, window, document.getElementById('BackGround'));
P.setup(12, 24);
var Q = new PieceQueue(P, document.getElementById('Queue'), document.getElementById('QueueBorder'), 10);
P.reset();
//P.Piece = Q.next();
var last = Date.now();
P.PieceCounter = document.createTextNode('');
document.getElementById('PieceCount').appendChild(P.PieceCounter);
P.LineCounter = document.createTextNode('');
document.getElementById('LineCount').appendChild(P.LineCounter);
P.ScoreCounter = document.createTextNode('');
document.getElementById('ScoreBoard').appendChild(P.ScoreCounter);
P.TimeCounter = document.createTextNode('');
document.getElementById('TimeCounter').appendChild(P.TimeCounter);
P.Speedometer = document.createTextNode('');
//document.getElementById('Speedometer').appendChild(P.Speedometer);
P.TargetArea = document.getElementById('TargetArea');
var Paused = false;
setInterval(function() {
var cur = Date.now();
var diff = (cur - last) / 1000;
last = cur;
if (!Paused) {
P.update(diff);
Q.update(diff);
}
}, 1000 / 60);
function Pause() {
if (P.gameOver) {
return;
}
Paused = true;
document.getElementById('GameScreen').style.opacity = 0;
document.getElementById('PauseScreen').style.opacity = 1;
}
function UnPause() {
if (P.gameOver) {
return;
}
Paused = false;
document.getElementById('GameScreen').style.opacity = 1;
document.getElementById('PauseScreen').style.opacity = 0;
}
window.addEventListener(Events.blur, function() {
Pause();
});
window.addEventListener(Events.mousedown, function(event) {
switch (event.button) {
case 0:
P.Piece.rotateCw();
break;
case 1:
P.Piece.drop();
break;
case 2:
P.Piece.rotateCcw();
break;
default:
alert(event.button);
}
event.preventDefault();
});
window.addEventListener(Events.click, function(event) {
event.preventDefault();
});
window.addEventListener(Events.mouseup, function(event) {
event.preventDefault();
});
window.addEventListener(Events.click, function(event) {
event.preventDefault();
});
window.addEventListener(Events.contextmenu, function(event) {
event.preventDefault();
});
window.addEventListener(Events.drag, function(event) {
event.preventDefault();
});
window.addEventListener(Events.keydown, function(event) {
switch (event.keyCode) {
case 37:
case 65:
P.Piece.moveTo(P.Piece.goalX - 1);
break;
case 39:
case 68:
P.Piece.moveTo(P.Piece.goalX + 1);
break;
case 38:
case 87:
P.Piece.rotate180();
break;
case 40:
case 83:
P.Piece.fall();
break;
case 32:
P.Piece.drop();
break;
case 81:
case 17:
P.Piece.rotateCw();
break;
case 69:
case 96:
case 45:
P.Piece.rotateCcw();
break;
case 19:
case 27:
if (Paused) {
UnPause();
}
else {
Pause();
}
break;
default: alert(event.keyCode);
}
event.preventDefault();
});
window.addEventListener(Events.mousemove, function(event) {
var xpos = (event.pageX * P.ratio) + P.xOfs;
P.Piece.moveTo(Math.round(xpos - (P.Piece.size / 2)) - 1);
});
window.addEventListener(Events.mousewheel, function(event) {
var delta = event.wheelDelta || -event.detail;
if (delta < 0) {
P.Piece.fall();
}
else {
P.Piece.rotate180();
}
event.preventDefault();
});
localStorage['Version'] = '100000'; |
// @flow
import React from 'react'
import cn from 'bem-cn'
const bem = cn('icon')
class Button extends React.Component {
render() {
return (
<svg className={bem({'key': true})} enableBackground="new 0 0 24 24" version="1.0" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M9,2C5.1,2,2,5.1,2,9c0,3.9,3.1,7,7,7c3.9,0,7-3.1,7-7C16,5.1,12.9,2,9,2z M7.5,10C6.1,10,5,8.9,5,7.5C5,6.1,6.1,5,7.5,5 C8.9,5,10,6.1,10,7.5C10,8.9,8.9,10,7.5,10z"/>
<path d="M15,11l-4,4l2,2v0h2v2l0,0h2v2l0.7,0.7c0.2,0.2,0.4,0.3,0.7,0.3H21c0.6,0,1-0.4,1-1v-2.6c0-0.3-0.1-0.5-0.3-0.7L15,11z"/>
</svg>
)
}
}
export default Button
|
var searchData=
[
['main',['main',['../_r_l_e_2src_2_b_a_m_v___l_z_w_8c.html#a0ddf1224851353fc92bfbff6f499fa97',1,'main(int argc, char *argv[]): BAMV_LZW.c'],['../_version1_2src_2_b_a_m_v___l_z_w_8c.html#a0ddf1224851353fc92bfbff6f499fa97',1,'main(int argc, char *argv[]): BAMV_LZW.c'],['../_version2_2src_2_b_a_m_v___l_z_w_8c.html#a0ddf1224851353fc92bfbff6f499fa97',1,'main(int argc, char *argv[]): BAMV_LZW.c']]],
['map',['map',['../struct__dict.html#a803be7ed20023f59b68a9374194f37bd',1,'_dict::map()'],['../struct__dict.html#a4ad47d0f0bddd6c5419caa544af5d316',1,'_dict::map()']]]
];
|
var db = openDatabase('prefs', '1.0', 'ouirc preferences', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS prefs (name unique, value)');
});
exports.getServersList = function () {
db.transaction(function () {
tx.executeSql("SELECT * FROM prefs WHERE name = ", [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).text);
}
});
});
} |
'use strict';
const Temperature = require('./scores/temperature');
const Humidity = require('./scores/humidity');
const Luminosity = require('./scores/luminosity');
const EnergyConsumption = require('./scores/energyConsumption');
const Refrigeration = require('./scores/refrigeration');
const Freezing = require('./scores/freezing');
const EglEl = require('./scores/eglEl');
const EnergyBalance = require('./scores/energyBalance');
const PowerPeaks = require('./scores/powerPeaks');
const Water = require('./scores/water');
const utils = require('./utils');
module.exports.Temperature = Temperature;
module.exports.Humidity = Humidity;
module.exports.Luminosity = Luminosity;
module.exports.EnergyConsumption = EnergyConsumption;
module.exports.Refrigeration = Refrigeration;
module.exports.Freezing = Freezing;
module.exports.EglEl = EglEl;
module.exports.EnergyBalance = EnergyBalance;
module.exports.PowerPeaks = PowerPeaks;
module.exports.Water = Water;
module.exports.utils = utils;
|
import {inspect} from 'util';
import NodeConnectionLine from './NodeConnectionLine';
export default class NodeConnectionMerger {
inspect() {
return '[' + inspect(this.connectionSourceNode) + ']:';
}
constructor(connectionSourceNode, direction) {
this.connectionSourceNode = connectionSourceNode;
this.direction = direction;
this.singleSource = false;
this.prioritiesShouldMatch = false;
this.connectionSourceNode.setConnectionPoint(this);
this.sourceNodesToLines = new Map();
}
getSourceNodesToLines() { return this.sourceNodesToLines; }
setTarget(target) {
this.target = target;
return this;
}
connectNode(sourceNode, connectionMessage) {
const line = new NodeConnectionLine(
sourceNode.getNodeSource(), this.direction
);
line.setTarget(this);
this.sourceNodesToLines.set(sourceNode, line);
line.connect(connectionMessage);
return this;
}
disconnectNode(sourceNode, connectionMessage) {
const line = this.sourceNodesToLines.get(sourceNode);
this.sourceNodesToLines.delete(sourceNode);
line.disconnect(connectionMessage);
return this;
}
exchangeConnectionPointMessage(msg) {
return msg
.sendToMergedMessage(this)
.exchangeWithJointConnectionMessage(this.target);
}
connect() {
return this;
}
disconnect() {
return this;
}
sendMessage(message) {
this.target.receiveMessage(message);
return this;
}
sendQuery(query) {
this.sourceNodesToLines.forEach( (line) => line.receiveQuery(query) );
return this;
}
receiveQuery(query) {
query.sendToMergedMessage(this);
return this;
}
}
|
angular.module("ui.bootstrap", ["ui.bootstrap.transition", "ui.bootstrap.collapse", "ui.bootstrap.accordion", "ui.bootstrap.alert", "ui.bootstrap.bindHtml", "ui.bootstrap.buttons", "ui.bootstrap.carousel", "ui.bootstrap.position", "ui.bootstrap.datepicker", "ui.bootstrap.dropdownToggle", "ui.bootstrap.modal", "ui.bootstrap.pagination", "ui.bootstrap.tooltip", "ui.bootstrap.popover", "ui.bootstrap.progressbar", "ui.bootstrap.rating", "ui.bootstrap.tabs", "ui.bootstrap.timepicker", "ui.bootstrap.typeahead"]);
angular.module('ui.bootstrap.transition', [])
/**
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
* @param {DOMElement} element The DOMElement that will be animated.
* @param {string|object|function} trigger The thing that will cause the transition to start:
* - As a string, it represents the css class to be added to the element.
* - As an object, it represents a hash of style attributes to be applied to the element.
* - As a function, it represents a function to be called that will cause the transition to occur.
* @return {Promise} A promise that is resolved when the transition finishes.
*/
.factory('$transition', ['$q', '$timeout', '$rootScope', function ($q, $timeout, $rootScope) {
var $transition = function (element, trigger, options) {
options = options || {};
var deferred = $q.defer();
var endEventName = $transition[options.animation ? "animationEndEventName" : "transitionEndEventName"];
var transitionEndHandler = function (event) {
$rootScope.$apply(function () {
element.unbind(endEventName, transitionEndHandler);
deferred.resolve(element);
});
};
if (endEventName) {
element.bind(endEventName, transitionEndHandler);
}
// Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
$timeout(function () {
if (angular.isString(trigger)) {
element.addClass(trigger);
} else if (angular.isFunction(trigger)) {
trigger(element);
} else if (angular.isObject(trigger)) {
element.css(trigger);
}
//If browser does not support transitions, instantly resolve
if (!endEventName) {
deferred.resolve(element);
}
});
// Add our custom cancel function to the promise that is returned
// We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
// i.e. it will therefore never raise a transitionEnd event for that transition
deferred.promise.cancel = function () {
if (endEventName) {
element.unbind(endEventName, transitionEndHandler);
}
deferred.reject('Transition cancelled');
};
return deferred.promise;
};
// Work out the name of the transitionEnd event
var transElement = document.createElement('trans');
var transitionEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'transition': 'transitionend'
};
var animationEndEventNames = {
'WebkitTransition': 'webkitAnimationEnd',
'MozTransition': 'animationend',
'OTransition': 'oAnimationEnd',
'transition': 'animationend'
};
function findEndEventName(endEventNames) {
for (var name in endEventNames) {
if (transElement.style[name] !== undefined) {
return endEventNames[name];
}
}
}
$transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
$transition.animationEndEventName = findEndEventName(animationEndEventNames);
return $transition;
}]);
angular.module('ui.bootstrap.collapse', ['ui.bootstrap.transition'])
// The collapsible directive indicates a block of html that will expand and collapse
.directive('collapse', ['$transition', function ($transition) {
// CSS transitions don't work with height: auto, so we have to manually change the height to a
// specific value and then once the animation completes, we can reset the height to auto.
// Unfortunately if you do this while the CSS transitions are specified (i.e. in the CSS class
// "collapse") then you trigger a change to height 0 in between.
// The fix is to remove the "collapse" CSS class while changing the height back to auto - phew!
var fixUpHeight = function (scope, element, height) {
// We remove the collapse CSS class to prevent a transition when we change to height: auto
element.removeClass('collapse');
element.css({height: height});
// It appears that reading offsetWidth makes the browser realise that we have changed the
// height already :-/
var x = element[0].offsetWidth;
element.addClass('collapse');
};
return {
link: function (scope, element, attrs) {
var isCollapsed;
var initialAnimSkip = true;
scope.$watch(attrs.collapse, function (value) {
if (value) {
collapse();
} else {
expand();
}
});
var currentTransition;
var doTransition = function (change) {
if (currentTransition) {
currentTransition.cancel();
}
currentTransition = $transition(element, change);
currentTransition.then(
function () {
currentTransition = undefined;
},
function () {
currentTransition = undefined;
}
);
return currentTransition;
};
var expand = function () {
isCollapsed = false;
if (initialAnimSkip) {
initialAnimSkip = false;
expandDone();
} else {
var targetElHeight = element[0].scrollHeight;
if (targetElHeight) {
doTransition({height: targetElHeight + 'px'}).then(expandDone);
} else {
expandDone();
}
}
};
function expandDone() {
if (!isCollapsed) {
fixUpHeight(scope, element, 'auto');
element.addClass('in');
}
}
var collapse = function () {
isCollapsed = true;
element.removeClass('in');
if (initialAnimSkip) {
initialAnimSkip = false;
fixUpHeight(scope, element, 0);
} else {
fixUpHeight(scope, element, element[0].scrollHeight + 'px');
doTransition({'height': '0'});
}
};
}
};
}]);
angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])
.constant('accordionConfig', {
closeOthers: true
})
.controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) {
// This array keeps track of the accordion groups
this.groups = [];
// Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
this.closeOthers = function (openGroup) {
var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
if (closeOthers) {
angular.forEach(this.groups, function (group) {
if (group !== openGroup) {
group.isOpen = false;
}
});
}
};
// This is called from the accordion-group directive to add itself to the accordion
this.addGroup = function (groupScope) {
var that = this;
this.groups.push(groupScope);
groupScope.$on('$destroy', function (event) {
that.removeGroup(groupScope);
});
};
// This is called from the accordion-group directive when to remove itself
this.removeGroup = function (group) {
var index = this.groups.indexOf(group);
if (index !== -1) {
this.groups.splice(this.groups.indexOf(group), 1);
}
};
}])
// The accordion directive simply sets up the directive controller
// and adds an accordion CSS class to itself element.
.directive('accordion', function () {
return {
restrict: 'EA',
controller: 'AccordionController',
transclude: true,
replace: false,
templateUrl: 'template/accordion/accordion.html'
};
})
// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
.directive('accordionGroup', ['$parse', function ($parse) {
return {
require: '^accordion', // We need this directive to be inside an accordion
restrict: 'EA',
transclude: true, // It transcludes the contents of the directive into the template
replace: true, // The element containing the directive will be replaced with the template
templateUrl: 'template/accordion/accordion-group.html',
scope: {heading: '@'}, // Create an isolated scope and interpolate the heading attribute onto this scope
controller: function () {
this.setHeading = function (element) {
this.heading = element;
};
},
link: function (scope, element, attrs, accordionCtrl) {
var getIsOpen, setIsOpen;
accordionCtrl.addGroup(scope);
scope.isOpen = false;
if (attrs.isOpen) {
getIsOpen = $parse(attrs.isOpen);
setIsOpen = getIsOpen.assign;
scope.$parent.$watch(getIsOpen, function (value) {
scope.isOpen = !!value;
});
}
scope.$watch('isOpen', function (value) {
if (value) {
accordionCtrl.closeOthers(scope);
}
if (setIsOpen) {
setIsOpen(scope.$parent, value);
}
});
}
};
}])
// Use accordion-heading below an accordion-group to provide a heading containing HTML
// <accordion-group>
// <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading>
// </accordion-group>
.directive('accordionHeading', function () {
return {
restrict: 'EA',
transclude: true, // Grab the contents to be used as the heading
template: '', // In effect remove this element!
replace: true,
require: '^accordionGroup',
compile: function (element, attr, transclude) {
return function link(scope, element, attr, accordionGroupCtrl) {
// Pass the heading to the accordion-group controller
// so that it can be transcluded into the right place in the template
// [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
accordionGroupCtrl.setHeading(transclude(scope, function () {
}));
};
}
};
})
// Use in the accordion-group template to indicate where you want the heading to be transcluded
// You must provide the property on the accordion-group controller that will hold the transcluded element
// <div class="accordion-group">
// <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div>
// ...
// </div>
.directive('accordionTransclude', function () {
return {
require: '^accordionGroup',
link: function (scope, element, attr, controller) {
scope.$watch(function () {
return controller[attr.accordionTransclude];
}, function (heading) {
if (heading) {
element.html('');
element.append(heading);
}
});
}
};
});
angular.module("ui.bootstrap.alert", [])
.controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) {
$scope.closeable = 'close' in $attrs;
}])
.directive('alert', function () {
return {
restrict: 'EA',
controller: 'AlertController',
templateUrl: 'template/alert/alert.html',
transclude: true,
replace: true,
scope: {
type: '=',
close: '&'
}
};
});
angular.module('ui.bootstrap.bindHtml', [])
.directive('bindHtmlUnsafe', function () {
return function (scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);
scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
});
angular.module('ui.bootstrap.buttons', [])
.constant('buttonConfig', {
activeClass: 'active',
toggleEvent: 'click'
})
.controller('ButtonsController', ['buttonConfig', function (buttonConfig) {
this.activeClass = buttonConfig.activeClass || 'active';
this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])
.directive('btnRadio', function () {
return {
require: ['btnRadio', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
if (!element.hasClass(buttonsCtrl.activeClass)) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(scope.$eval(attrs.btnRadio));
ngModelCtrl.$render();
});
}
});
}
};
})
.directive('btnCheckbox', function () {
return {
require: ['btnCheckbox', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
function getTrueValue() {
return getCheckboxValue(attrs.btnCheckboxTrue, true);
}
function getFalseValue() {
return getCheckboxValue(attrs.btnCheckboxFalse, false);
}
function getCheckboxValue(attributeValue, defaultValue) {
var val = scope.$eval(attributeValue);
return angular.isDefined(val) ? val : defaultValue;
}
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
ngModelCtrl.$render();
});
});
}
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.carousel
*
* @description
* AngularJS version of an image carousel.
*
*/
angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])
.controller('CarouselController', ['$scope', '$timeout', '$transition', '$q', function ($scope, $timeout, $transition, $q) {
var self = this,
slides = self.slides = [],
currentIndex = -1,
currentTimeout, isPlaying;
self.currentSlide = null;
var destroyed = false;
/* direction: "prev" or "next" */
self.select = function (nextSlide, direction) {
var nextIndex = slides.indexOf(nextSlide);
//Decide direction if it's not given
if (direction === undefined) {
direction = nextIndex > currentIndex ? "next" : "prev";
}
if (nextSlide && nextSlide !== self.currentSlide) {
if ($scope.$currentTransition) {
$scope.$currentTransition.cancel();
//Timeout so ng-class in template has time to fix classes for finished slide
$timeout(goNext);
} else {
goNext();
}
}
function goNext() {
// Scope has been destroyed, stop here.
if (destroyed) {
return;
}
//If we have a slide to transition from and we have a transition type and we're allowed, go
if (self.currentSlide && angular.isString(direction) && !$scope.noTransition && nextSlide.$element) {
//We shouldn't do class manip in here, but it's the same weird thing bootstrap does. need to fix sometime
nextSlide.$element.addClass(direction);
var reflow = nextSlide.$element[0].offsetWidth; //force reflow
//Set all other slides to stop doing their stuff for the new transition
angular.forEach(slides, function (slide) {
angular.extend(slide, {direction: '', entering: false, leaving: false, active: false});
});
angular.extend(nextSlide, {direction: direction, active: true, entering: true});
angular.extend(self.currentSlide || {}, {direction: direction, leaving: true});
$scope.$currentTransition = $transition(nextSlide.$element, {});
//We have to create new pointers inside a closure since next & current will change
(function (next, current) {
$scope.$currentTransition.then(
function () {
transitionDone(next, current);
},
function () {
transitionDone(next, current);
}
);
}(nextSlide, self.currentSlide));
} else {
transitionDone(nextSlide, self.currentSlide);
}
self.currentSlide = nextSlide;
currentIndex = nextIndex;
//every time you change slides, reset the timer
restartTimer();
}
function transitionDone(next, current) {
angular.extend(next, {direction: '', active: true, leaving: false, entering: false});
angular.extend(current || {}, {direction: '', active: false, leaving: false, entering: false});
$scope.$currentTransition = null;
}
};
$scope.$on('$destroy', function () {
destroyed = true;
});
/* Allow outside people to call indexOf on slides array */
self.indexOfSlide = function (slide) {
return slides.indexOf(slide);
};
$scope.next = function () {
var newIndex = (currentIndex + 1) % slides.length;
//Prevent this user-triggered transition from occurring if there is already one in progress
if (!$scope.$currentTransition) {
return self.select(slides[newIndex], 'next');
}
};
$scope.prev = function () {
var newIndex = currentIndex - 1 < 0 ? slides.length - 1 : currentIndex - 1;
//Prevent this user-triggered transition from occurring if there is already one in progress
if (!$scope.$currentTransition) {
return self.select(slides[newIndex], 'prev');
}
};
$scope.select = function (slide) {
self.select(slide);
};
$scope.isActive = function (slide) {
return self.currentSlide === slide;
};
$scope.slides = function () {
return slides;
};
$scope.$watch('interval', restartTimer);
$scope.$on('$destroy', resetTimer);
function restartTimer() {
resetTimer();
var interval = +$scope.interval;
if (!isNaN(interval) && interval >= 0) {
currentTimeout = $timeout(timerFn, interval);
}
}
function resetTimer() {
if (currentTimeout) {
$timeout.cancel(currentTimeout);
currentTimeout = null;
}
}
function timerFn() {
if (isPlaying) {
$scope.next();
restartTimer();
} else {
$scope.pause();
}
}
$scope.play = function () {
if (!isPlaying) {
isPlaying = true;
restartTimer();
}
};
$scope.pause = function () {
if (!$scope.noPause) {
isPlaying = false;
resetTimer();
}
};
self.addSlide = function (slide, element) {
slide.$element = element;
slides.push(slide);
//if this is the first slide or the slide is set to active, select it
if (slides.length === 1 || slide.active) {
self.select(slides[slides.length - 1]);
if (slides.length == 1) {
$scope.play();
}
} else {
slide.active = false;
}
};
self.removeSlide = function (slide) {
//get the index of the slide inside the carousel
var index = slides.indexOf(slide);
slides.splice(index, 1);
if (slides.length > 0 && slide.active) {
if (index >= slides.length) {
self.select(slides[index - 1]);
} else {
self.select(slides[index]);
}
} else if (currentIndex > index) {
currentIndex--;
}
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:carousel
* @restrict EA
*
* @description
* Carousel is the outer container for a set of image 'slides' to showcase.
*
* @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
* @param {boolean=} noTransition Whether to disable transitions on the carousel.
* @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<carousel>
<slide>
<img src="http://placekitten.com/150/150" style="margin:auto;">
<div class="carousel-caption">
<p>Beautiful!</p>
</div>
</slide>
<slide>
<img src="http://placekitten.com/100/150" style="margin:auto;">
<div class="carousel-caption">
<p>D'aww!</p>
</div>
</slide>
</carousel>
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('carousel', [function () {
return {
restrict: 'EA',
transclude: true,
replace: true,
controller: 'CarouselController',
require: 'carousel',
templateUrl: 'template/carousel/carousel.html',
scope: {
interval: '=',
noTransition: '=',
noPause: '='
}
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:slide
* @restrict EA
*
* @description
* Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.
*
* @param {boolean=} active Model binding, whether or not this slide is currently active.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="CarouselDemoCtrl">
<carousel>
<slide ng-repeat="slide in slides" active="slide.active">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<p>{{slide.text}}</p>
</div>
</slide>
</carousel>
<div class="row-fluid">
<div class="span6">
<ul>
<li ng-repeat="slide in slides">
<button class="btn btn-mini" ng-class="{'btn-info': !slide.active, 'btn-success': slide.active}" ng-disabled="slide.active" ng-click="slide.active = true">select</button>
{{$index}}: {{slide.text}}
</li>
</ul>
<a class="btn" ng-click="addSlide()">Add Slide</a>
</div>
<div class="span6">
Interval, in milliseconds: <input type="number" ng-model="myInterval">
<br />Enter a negative number to stop the interval.
</div>
</div>
</div>
</file>
<file name="script.js">
function CarouselDemoCtrl($scope) {
$scope.myInterval = 5000;
var slides = $scope.slides = [];
$scope.addSlide = function() {
var newWidth = 200 + ((slides.length + (25 * slides.length)) % 150);
slides.push({
image: 'http://placekitten.com/' + newWidth + '/200',
text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' '
['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
});
};
for (var i=0; i<4; i++) $scope.addSlide();
}
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('slide', ['$parse', function ($parse) {
return {
require: '^carousel',
restrict: 'EA',
transclude: true,
replace: true,
templateUrl: 'template/carousel/slide.html',
scope: {},
link: function (scope, element, attrs, carouselCtrl) {
//Set up optional 'active' = binding
if (attrs.active) {
var getActive = $parse(attrs.active);
var setActive = getActive.assign;
var lastValue = scope.active = getActive(scope.$parent);
scope.$watch(function parentActiveWatch() {
var parentActive = getActive(scope.$parent);
if (parentActive !== scope.active) {
// we are out of sync and need to copy
if (parentActive !== lastValue) {
// parent changed and it has precedence
lastValue = scope.active = parentActive;
} else {
// if the parent can be assigned then do so
setActive(scope.$parent, parentActive = lastValue = scope.active);
}
}
return parentActive;
});
}
carouselCtrl.addSlide(scope, element);
//when the scope is destroyed then remove the slide from the current slides array
scope.$on('$destroy', function () {
carouselCtrl.removeSlide(scope);
});
scope.$watch('active', function (active) {
if (active) {
carouselCtrl.select(scope);
}
});
}
};
}]);
angular.module('ui.bootstrap.position', [])
/**
* A set of utility methods that can be use to retrieve position of DOM elements.
* It is meant to be used where we need to absolute-position DOM elements in
* relation to other, existing elements (this is the case for tooltips, popovers,
* typeahead suggestions etc.).
*/
.factory('$position', ['$document', '$window', function ($document, $window) {
function getStyle(el, cssprop) {
if (el.currentStyle) { //IE
return el.currentStyle[cssprop];
} else if ($window.getComputedStyle) {
return $window.getComputedStyle(el)[cssprop];
}
// finally try and get inline style
return el.style[cssprop];
}
/**
* Checks if a given element is statically positioned
* @param element - raw DOM element
*/
function isStaticPositioned(element) {
return (getStyle(element, "position") || 'static' ) === 'static';
}
/**
* returns the closest, non-statically positioned parentOffset of a given element
* @param element
*/
var parentOffsetEl = function (element) {
var docDomEl = $document[0];
var offsetParent = element.offsetParent || docDomEl;
while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent)) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docDomEl;
};
return {
/**
* Provides read-only equivalent of jQuery's position function:
* http://api.jquery.com/position/
*/
position: function (element) {
var elBCR = this.offset(element);
var offsetParentBCR = {top: 0, left: 0};
var offsetParentEl = parentOffsetEl(element[0]);
if (offsetParentEl != $document[0]) {
offsetParentBCR = this.offset(angular.element(offsetParentEl));
offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
}
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: elBCR.top - offsetParentBCR.top,
left: elBCR.left - offsetParentBCR.left
};
},
/**
* Provides read-only equivalent of jQuery's offset function:
* http://api.jquery.com/offset/
*/
offset: function (element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft)
};
}
};
}]);
angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.position'])
.constant('datepickerConfig', {
dayFormat: 'dd',
monthFormat: 'MMMM',
yearFormat: 'yyyy',
dayHeaderFormat: 'EEE',
dayTitleFormat: 'MMMM yyyy',
monthTitleFormat: 'yyyy',
showWeeks: true,
startingDay: 0,
yearRange: 20,
minDate: null,
maxDate: null
})
.controller('DatepickerController', ['$scope', '$attrs', 'dateFilter', 'datepickerConfig', function ($scope, $attrs, dateFilter, dtConfig) {
var format = {
day: getValue($attrs.dayFormat, dtConfig.dayFormat),
month: getValue($attrs.monthFormat, dtConfig.monthFormat),
year: getValue($attrs.yearFormat, dtConfig.yearFormat),
dayHeader: getValue($attrs.dayHeaderFormat, dtConfig.dayHeaderFormat),
dayTitle: getValue($attrs.dayTitleFormat, dtConfig.dayTitleFormat),
monthTitle: getValue($attrs.monthTitleFormat, dtConfig.monthTitleFormat)
},
startingDay = getValue($attrs.startingDay, dtConfig.startingDay),
yearRange = getValue($attrs.yearRange, dtConfig.yearRange);
this.minDate = dtConfig.minDate ? new Date(dtConfig.minDate) : null;
this.maxDate = dtConfig.maxDate ? new Date(dtConfig.maxDate) : null;
function getValue(value, defaultValue) {
return angular.isDefined(value) ? $scope.$parent.$eval(value) : defaultValue;
}
function getDaysInMonth(year, month) {
return new Date(year, month, 0).getDate();
}
function getDates(startDate, n) {
var dates = new Array(n);
var current = startDate, i = 0;
while (i < n) {
dates[i++] = new Date(current);
current.setDate(current.getDate() + 1);
}
return dates;
}
function makeDate(date, format, isSelected, isSecondary) {
return {date: date, label: dateFilter(date, format), selected: !!isSelected, secondary: !!isSecondary};
}
this.modes = [
{
name: 'day',
getVisibleDates: function (date, selected) {
var year = date.getFullYear(), month = date.getMonth(), firstDayOfMonth = new Date(year, month, 1);
var difference = startingDay - firstDayOfMonth.getDay(),
numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : -difference,
firstDate = new Date(firstDayOfMonth), numDates = 0;
if (numDisplayedFromPreviousMonth > 0) {
firstDate.setDate(-numDisplayedFromPreviousMonth + 1);
numDates += numDisplayedFromPreviousMonth; // Previous
}
numDates += getDaysInMonth(year, month + 1); // Current
numDates += (7 - numDates % 7) % 7; // Next
var days = getDates(firstDate, numDates), labels = new Array(7);
for (var i = 0; i < numDates; i++) {
var dt = new Date(days[i]);
days[i] = makeDate(dt, format.day, (selected && selected.getDate() === dt.getDate() && selected.getMonth() === dt.getMonth() && selected.getFullYear() === dt.getFullYear()), dt.getMonth() !== month);
}
for (var j = 0; j < 7; j++) {
labels[j] = dateFilter(days[j].date, format.dayHeader);
}
return {objects: days, title: dateFilter(date, format.dayTitle), labels: labels};
},
compare: function (date1, date2) {
return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()) );
},
split: 7,
step: {months: 1}
},
{
name: 'month',
getVisibleDates: function (date, selected) {
var months = new Array(12), year = date.getFullYear();
for (var i = 0; i < 12; i++) {
var dt = new Date(year, i, 1);
months[i] = makeDate(dt, format.month, (selected && selected.getMonth() === i && selected.getFullYear() === year));
}
return {objects: months, title: dateFilter(date, format.monthTitle)};
},
compare: function (date1, date2) {
return new Date(date1.getFullYear(), date1.getMonth()) - new Date(date2.getFullYear(), date2.getMonth());
},
split: 3,
step: {years: 1}
},
{
name: 'year',
getVisibleDates: function (date, selected) {
var years = new Array(yearRange), year = date.getFullYear(), startYear = parseInt((year - 1) / yearRange, 10) * yearRange + 1;
for (var i = 0; i < yearRange; i++) {
var dt = new Date(startYear + i, 0, 1);
years[i] = makeDate(dt, format.year, (selected && selected.getFullYear() === dt.getFullYear()));
}
return {objects: years, title: [years[0].label, years[yearRange - 1].label].join(' - ')};
},
compare: function (date1, date2) {
return date1.getFullYear() - date2.getFullYear();
},
split: 5,
step: {years: yearRange}
}
];
this.isDisabled = function (date, mode) {
var currentMode = this.modes[mode || 0];
return ((this.minDate && currentMode.compare(date, this.minDate) < 0) || (this.maxDate && currentMode.compare(date, this.maxDate) > 0) || ($scope.dateDisabled && $scope.dateDisabled({
date: date,
mode: currentMode.name
})));
};
}])
.directive('datepicker', ['dateFilter', '$parse', 'datepickerConfig', '$log', function (dateFilter, $parse, datepickerConfig, $log) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/datepicker.html',
scope: {
dateDisabled: '&'
},
require: ['datepicker', '?^ngModel'],
controller: 'DatepickerController',
link: function (scope, element, attrs, ctrls) {
var datepickerCtrl = ctrls[0], ngModel = ctrls[1];
if (!ngModel) {
return; // do nothing if no ng-model
}
// Configuration parameters
var mode = 0, selected = new Date(), showWeeks = datepickerConfig.showWeeks;
if (attrs.showWeeks) {
scope.$parent.$watch($parse(attrs.showWeeks), function (value) {
showWeeks = !!value;
updateShowWeekNumbers();
});
} else {
updateShowWeekNumbers();
}
if (attrs.min) {
scope.$parent.$watch($parse(attrs.min), function (value) {
datepickerCtrl.minDate = value ? new Date(value) : null;
refill();
});
}
if (attrs.max) {
scope.$parent.$watch($parse(attrs.max), function (value) {
datepickerCtrl.maxDate = value ? new Date(value) : null;
refill();
});
}
function updateShowWeekNumbers() {
scope.showWeekNumbers = mode === 0 && showWeeks;
}
// Split array into smaller arrays
function split(arr, size) {
var arrays = [];
while (arr.length > 0) {
arrays.push(arr.splice(0, size));
}
return arrays;
}
function refill(updateSelected) {
var date = null, valid = true;
if (ngModel.$modelValue) {
date = new Date(ngModel.$modelValue);
if (isNaN(date)) {
valid = false;
$log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
} else if (updateSelected) {
selected = date;
}
}
ngModel.$setValidity('date', valid);
var currentMode = datepickerCtrl.modes[mode], data = currentMode.getVisibleDates(selected, date);
angular.forEach(data.objects, function (obj) {
obj.disabled = datepickerCtrl.isDisabled(obj.date, mode);
});
ngModel.$setValidity('date-disabled', (!date || !datepickerCtrl.isDisabled(date)));
scope.rows = split(data.objects, currentMode.split);
scope.labels = data.labels || [];
scope.title = data.title;
}
function setMode(value) {
mode = value;
updateShowWeekNumbers();
refill();
}
ngModel.$render = function () {
refill(true);
};
scope.select = function (date) {
if (mode === 0) {
var dt = ngModel.$modelValue ? new Date(ngModel.$modelValue) : new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
ngModel.$setViewValue(dt);
refill(true);
} else {
selected = date;
setMode(mode - 1);
}
};
scope.move = function (direction) {
var step = datepickerCtrl.modes[mode].step;
selected.setMonth(selected.getMonth() + direction * (step.months || 0));
selected.setFullYear(selected.getFullYear() + direction * (step.years || 0));
refill();
};
scope.toggleMode = function () {
setMode((mode + 1) % datepickerCtrl.modes.length);
};
scope.getWeekNumber = function (row) {
return ( mode === 0 && scope.showWeekNumbers && row.length === 7 ) ? getISO8601WeekNumber(row[0].date) : null;
};
function getISO8601WeekNumber(date) {
var checkDate = new Date(date);
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
}
};
}])
.constant('datepickerPopupConfig', {
dateFormat: 'yyyy-MM-dd',
currentText: 'Today',
toggleWeeksText: 'Weeks',
clearText: 'Clear',
closeText: 'Done',
closeOnDateSelection: true,
appendToBody: false,
showButtonBar: true
})
.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'datepickerPopupConfig', 'datepickerConfig',
function ($compile, $parse, $document, $position, dateFilter, datepickerPopupConfig, datepickerConfig) {
return {
restrict: 'EA',
require: 'ngModel',
link: function (originalScope, element, attrs, ngModel) {
var scope = originalScope.$new(), // create a child scope so we are not polluting original one
dateFormat,
closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? originalScope.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,
appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? originalScope.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;
attrs.$observe('datepickerPopup', function (value) {
dateFormat = value || datepickerPopupConfig.dateFormat;
ngModel.$render();
});
scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? originalScope.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;
originalScope.$on('$destroy', function () {
$popup.remove();
scope.$destroy();
});
attrs.$observe('currentText', function (text) {
scope.currentText = angular.isDefined(text) ? text : datepickerPopupConfig.currentText;
});
attrs.$observe('toggleWeeksText', function (text) {
scope.toggleWeeksText = angular.isDefined(text) ? text : datepickerPopupConfig.toggleWeeksText;
});
attrs.$observe('clearText', function (text) {
scope.clearText = angular.isDefined(text) ? text : datepickerPopupConfig.clearText;
});
attrs.$observe('closeText', function (text) {
scope.closeText = angular.isDefined(text) ? text : datepickerPopupConfig.closeText;
});
var getIsOpen, setIsOpen;
if (attrs.isOpen) {
getIsOpen = $parse(attrs.isOpen);
setIsOpen = getIsOpen.assign;
originalScope.$watch(getIsOpen, function updateOpen(value) {
scope.isOpen = !!value;
});
}
scope.isOpen = getIsOpen ? getIsOpen(originalScope) : false; // Initial state
function setOpen(value) {
if (setIsOpen) {
setIsOpen(originalScope, !!value);
} else {
scope.isOpen = !!value;
}
}
var documentClickBind = function (event) {
if (scope.isOpen && event.target !== element[0]) {
scope.$apply(function () {
setOpen(false);
});
}
};
var elementFocusBind = function () {
scope.$apply(function () {
setOpen(true);
});
};
// popup element used to display calendar
var popupEl = angular.element('<div datepicker-popup-wrap><div datepicker></div></div>');
popupEl.attr({
'ng-model': 'date',
'ng-change': 'dateSelection()'
});
var datepickerEl = angular.element(popupEl.children()[0]);
if (attrs.datepickerOptions) {
datepickerEl.attr(angular.extend({}, originalScope.$eval(attrs.datepickerOptions)));
}
// TODO: reverse from dateFilter string to Date object
function parseDate(viewValue) {
if (!viewValue) {
ngModel.$setValidity('date', true);
return null;
} else if (angular.isDate(viewValue)) {
ngModel.$setValidity('date', true);
return viewValue;
} else if (angular.isString(viewValue)) {
var date = new Date(viewValue);
if (isNaN(date)) {
ngModel.$setValidity('date', false);
return undefined;
} else {
ngModel.$setValidity('date', true);
return date;
}
} else {
ngModel.$setValidity('date', false);
return undefined;
}
}
ngModel.$parsers.unshift(parseDate);
// Inner change
scope.dateSelection = function (dt) {
if (angular.isDefined(dt)) {
scope.date = dt;
}
ngModel.$setViewValue(scope.date);
ngModel.$render();
if (closeOnDateSelection) {
setOpen(false);
}
};
element.bind('input change keyup', function () {
scope.$apply(function () {
scope.date = ngModel.$modelValue;
});
});
// Outter change
ngModel.$render = function () {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
scope.date = ngModel.$modelValue;
};
function addWatchableAttribute(attribute, scopeProperty, datepickerAttribute) {
if (attribute) {
originalScope.$watch($parse(attribute), function (value) {
scope[scopeProperty] = value;
});
datepickerEl.attr(datepickerAttribute || scopeProperty, scopeProperty);
}
}
addWatchableAttribute(attrs.min, 'min');
addWatchableAttribute(attrs.max, 'max');
if (attrs.showWeeks) {
addWatchableAttribute(attrs.showWeeks, 'showWeeks', 'show-weeks');
} else {
scope.showWeeks = datepickerConfig.showWeeks;
datepickerEl.attr('show-weeks', 'showWeeks');
}
if (attrs.dateDisabled) {
datepickerEl.attr('date-disabled', attrs.dateDisabled);
}
function updatePosition() {
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
}
var documentBindingInitialized = false, elementFocusInitialized = false;
scope.$watch('isOpen', function (value) {
if (value) {
updatePosition();
$document.bind('click', documentClickBind);
if (elementFocusInitialized) {
element.unbind('focus', elementFocusBind);
}
element[0].focus();
documentBindingInitialized = true;
} else {
if (documentBindingInitialized) {
$document.unbind('click', documentClickBind);
}
element.bind('focus', elementFocusBind);
elementFocusInitialized = true;
}
if (setIsOpen) {
setIsOpen(originalScope, value);
}
});
scope.today = function () {
scope.dateSelection(new Date());
};
scope.clear = function () {
scope.dateSelection(null);
};
var $popup = $compile(popupEl)(scope);
if (appendToBody) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
}
};
}])
.directive('datepickerPopupWrap', function () {
return {
restrict: 'EA',
replace: true,
transclude: true,
templateUrl: 'template/datepicker/popup.html',
link: function (scope, element, attrs) {
element.bind('click', function (event) {
event.preventDefault();
event.stopPropagation();
});
}
};
});
/*
* dropdownToggle - Provides dropdown menu functionality in place of bootstrap js
* @restrict class or attribute
* @example:
<li class="dropdown">
<a class="dropdown-toggle">My Dropdown Menu</a>
<ul class="dropdown-menu">
<li ng-repeat="choice in dropChoices">
<a ng-href="{{choice.href}}">{{choice.text}}</a>
</li>
</ul>
</li>
*/
angular.module('ui.bootstrap.dropdownToggle', []).directive('dropdownToggle', ['$document', '$location', function ($document, $location) {
var openElement = null,
closeMenu = angular.noop;
return {
restrict: 'CA',
link: function (scope, element, attrs) {
scope.$watch('$location.path', function () {
closeMenu();
});
element.parent().bind('click', function () {
closeMenu();
});
element.bind('click', function (event) {
var elementWasOpen = (element === openElement);
event.preventDefault();
event.stopPropagation();
if (!!openElement) {
closeMenu();
}
if (!elementWasOpen && !element.hasClass('disabled') && !element.prop('disabled')) {
element.parent().addClass('open');
openElement = element;
closeMenu = function (event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
$document.unbind('click', closeMenu);
element.parent().removeClass('open');
closeMenu = angular.noop;
openElement = null;
};
$document.bind('click', closeMenu);
}
});
}
};
}]);
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function () {
return {
createNew: function () {
var stack = [];
return {
add: function (key, value) {
stack.push({
key: key,
value: value
});
},
get: function (key) {
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
return stack[i];
}
}
},
keys: function () {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function () {
return stack[stack.length - 1];
},
remove: function (key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function () {
return stack.splice(stack.length - 1, 1)[0];
},
length: function () {
return stack.length;
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('modalBackdrop', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/modal/backdrop.html',
link: function (scope) {
scope.animate = false;
//trigger CSS transitions
$timeout(function () {
scope.animate = true;
});
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static') {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
}
};
}])
.directive('modalWindow', ['$timeout', function ($timeout) {
return {
restrict: 'EA',
scope: {
index: '@'
},
replace: true,
transclude: true,
templateUrl: 'template/modal/window.html',
link: function (scope, element, attrs) {
scope.windowClass = attrs.windowClass || '';
// focus a freshly-opened modal
element[0].focus();
$timeout(function () {
// trigger CSS transitions
scope.animate = true;
});
}
};
}])
.factory('$modalStack', ['$document', '$compile', '$rootScope', '$$stackedMap',
function ($document, $compile, $rootScope, $$stackedMap) {
var OPENED_MODAL_CLASS = 'modal-open';
var backdropjqLiteEl, backdropDomEl;
var backdropScope = $rootScope.$new(true);
var openedWindows = $$stackedMap.createNew();
var $modalStack = {};
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function (newBackdropIndex) {
backdropScope.index = newBackdropIndex;
});
function removeModalWindow(modalInstance) {
var body = $document.find('body').eq(0);
var modalWindow = openedWindows.get(modalInstance).value;
//clean up the stack
openedWindows.remove(modalInstance);
//remove window DOM element
modalWindow.modalDomEl.remove();
body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() == -1) {
backdropDomEl.remove();
backdropDomEl = undefined;
}
//destroy scope
modalWindow.modalScope.$destroy();
}
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key);
});
}
}
});
$modalStack.open = function (modalInstance, modal) {
openedWindows.add(modalInstance, {
deferred: modal.deferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard
});
var body = $document.find('body').eq(0);
if (backdropIndex() >= 0 && !backdropDomEl) {
backdropjqLiteEl = angular.element('<div modal-backdrop></div>');
backdropDomEl = $compile(backdropjqLiteEl)(backdropScope);
body.append(backdropDomEl);
}
var angularDomEl = angular.element('<div modal-window></div>');
angularDomEl.attr('window-class', modal.windowClass);
angularDomEl.attr('index', openedWindows.length() - 1);
angularDomEl.html(modal.content);
var modalDomEl = $compile(angularDomEl)(modal.scope);
openedWindows.top().value.modalDomEl = modalDomEl;
body.append(modalDomEl);
body.addClass(OPENED_MODAL_CLASS);
};
$modalStack.close = function (modalInstance, result) {
var modal = openedWindows.get(modalInstance);
if (modal) {
modal.value.deferred.resolve(result);
removeModalWindow(modalInstance);
}
};
$modalStack.dismiss = function (modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance).value;
if (modalWindow) {
modalWindow.deferred.reject(reason);
removeModalWindow(modalInstance);
}
};
$modalStack.getTop = function () {
return openedWindows.top();
};
return $modalStack;
}])
.provider('$modal', function () {
var $modalProvider = {
options: {
backdrop: true, //can be also false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',
function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$http.get(options.templateUrl, {cache: $templateCache}).then(function (result) {
return result.data;
});
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value, key) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
}
});
return promisesArr;
}
$modal.open = function (modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
close: function (result) {
$modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
$modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
var ctrlInstance, ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$modalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function (value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
content: tplAndVars[0],
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
windowClass: modalOptions.windowClass
});
}, function resolveError(reason) {
modalResultDeferred.reject(reason);
});
templateAndResolvePromise.then(function () {
modalOpenedDeferred.resolve(true);
}, function () {
modalOpenedDeferred.reject(false);
});
return modalInstance;
};
return $modal;
}]
};
return $modalProvider;
});
angular.module('ui.bootstrap.pagination', [])
.controller('PaginationController', ['$scope', '$attrs', '$parse', '$interpolate', function ($scope, $attrs, $parse, $interpolate) {
var self = this,
setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
this.init = function (defaultItemsPerPage) {
if ($attrs.itemsPerPage) {
$scope.$parent.$watch($parse($attrs.itemsPerPage), function (value) {
self.itemsPerPage = parseInt(value, 10);
$scope.totalPages = self.calculateTotalPages();
});
} else {
this.itemsPerPage = defaultItemsPerPage;
}
};
this.noPrevious = function () {
return this.page === 1;
};
this.noNext = function () {
return this.page === $scope.totalPages;
};
this.isActive = function (page) {
return this.page === page;
};
this.calculateTotalPages = function () {
var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
return Math.max(totalPages || 0, 1);
};
this.getAttributeValue = function (attribute, defaultValue, interpolate) {
return angular.isDefined(attribute) ? (interpolate ? $interpolate(attribute)($scope.$parent) : $scope.$parent.$eval(attribute)) : defaultValue;
};
this.render = function () {
this.page = parseInt($scope.page, 10) || 1;
if (this.page > 0 && this.page <= $scope.totalPages) {
$scope.pages = this.getPages(this.page, $scope.totalPages);
}
};
$scope.selectPage = function (page) {
if (!self.isActive(page) && page > 0 && page <= $scope.totalPages) {
$scope.page = page;
$scope.onSelectPage({page: page});
}
};
$scope.$watch('page', function () {
self.render();
});
$scope.$watch('totalItems', function () {
$scope.totalPages = self.calculateTotalPages();
});
$scope.$watch('totalPages', function (value) {
setNumPages($scope.$parent, value); // Readonly variable
if (self.page > value) {
$scope.selectPage(value);
} else {
self.render();
}
});
}])
.constant('paginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
directionLinks: true,
firstText: 'First',
previousText: 'Previous',
nextText: 'Next',
lastText: 'Last',
rotate: true
})
.directive('pagination', ['$parse', 'paginationConfig', function ($parse, config) {
return {
restrict: 'EA',
scope: {
page: '=',
totalItems: '=',
onSelectPage: ' &'
},
controller: 'PaginationController',
templateUrl: 'template/pagination/pagination.html',
replace: true,
link: function (scope, element, attrs, paginationCtrl) {
// Setup configuration parameters
var maxSize,
boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks, config.boundaryLinks),
directionLinks = paginationCtrl.getAttributeValue(attrs.directionLinks, config.directionLinks),
firstText = paginationCtrl.getAttributeValue(attrs.firstText, config.firstText, true),
previousText = paginationCtrl.getAttributeValue(attrs.previousText, config.previousText, true),
nextText = paginationCtrl.getAttributeValue(attrs.nextText, config.nextText, true),
lastText = paginationCtrl.getAttributeValue(attrs.lastText, config.lastText, true),
rotate = paginationCtrl.getAttributeValue(attrs.rotate, config.rotate);
paginationCtrl.init(config.itemsPerPage);
if (attrs.maxSize) {
scope.$parent.$watch($parse(attrs.maxSize), function (value) {
maxSize = parseInt(value, 10);
paginationCtrl.render();
});
}
// Create page object used in template
function makePage(number, text, isActive, isDisabled) {
return {
number: number,
text: text,
active: isActive,
disabled: isDisabled
};
}
paginationCtrl.getPages = function (currentPage, totalPages) {
var pages = [];
// Default page limits
var startPage = 1, endPage = totalPages;
var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );
// recompute if maxSize
if (isMaxSized) {
if (rotate) {
// Current page is displayed in the middle of the visible ones
startPage = Math.max(currentPage - Math.floor(maxSize / 2), 1);
endPage = startPage + maxSize - 1;
// Adjust if limit is exceeded
if (endPage > totalPages) {
endPage = totalPages;
startPage = endPage - maxSize + 1;
}
} else {
// Visible pages are paginated with maxSize
startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
// Adjust last page if limit is exceeded
endPage = Math.min(startPage + maxSize - 1, totalPages);
}
}
// Add page number links
for (var number = startPage; number <= endPage; number++) {
var page = makePage(number, number, paginationCtrl.isActive(number), false);
pages.push(page);
}
// Add links to move between page sets
if (isMaxSized && !rotate) {
if (startPage > 1) {
var previousPageSet = makePage(startPage - 1, '...', false, false);
pages.unshift(previousPageSet);
}
if (endPage < totalPages) {
var nextPageSet = makePage(endPage + 1, '...', false, false);
pages.push(nextPageSet);
}
}
// Add previous & next links
if (directionLinks) {
var previousPage = makePage(currentPage - 1, previousText, false, paginationCtrl.noPrevious());
pages.unshift(previousPage);
var nextPage = makePage(currentPage + 1, nextText, false, paginationCtrl.noNext());
pages.push(nextPage);
}
// Add first & last links
if (boundaryLinks) {
var firstPage = makePage(1, firstText, false, paginationCtrl.noPrevious());
pages.unshift(firstPage);
var lastPage = makePage(totalPages, lastText, false, paginationCtrl.noNext());
pages.push(lastPage);
}
return pages;
};
}
};
}])
.constant('pagerConfig', {
itemsPerPage: 10,
previousText: '« Previous',
nextText: 'Next »',
align: true
})
.directive('pager', ['pagerConfig', function (config) {
return {
restrict: 'EA',
scope: {
page: '=',
totalItems: '=',
onSelectPage: ' &'
},
controller: 'PaginationController',
templateUrl: 'template/pagination/pager.html',
replace: true,
link: function (scope, element, attrs, paginationCtrl) {
// Setup configuration parameters
var previousText = paginationCtrl.getAttributeValue(attrs.previousText, config.previousText, true),
nextText = paginationCtrl.getAttributeValue(attrs.nextText, config.nextText, true),
align = paginationCtrl.getAttributeValue(attrs.align, config.align);
paginationCtrl.init(config.itemsPerPage);
// Create page object used in template
function makePage(number, text, isDisabled, isPrevious, isNext) {
return {
number: number,
text: text,
disabled: isDisabled,
previous: ( align && isPrevious ),
next: ( align && isNext )
};
}
paginationCtrl.getPages = function (currentPage) {
return [
makePage(currentPage - 1, previousText, paginationCtrl.noPrevious(), true, false),
makePage(currentPage + 1, nextText, paginationCtrl.noNext(), false, true)
];
};
}
};
}]);
/**
* The following features are still outstanding: animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html tooltips, and selector delegation.
*/
angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
/**
* The $tooltip service creates tooltip- and popover-like directives as well as
* houses global options for them.
*/
.provider('$tooltip', function () {
// The default options tooltip and popover.
var defaultOptions = {
placement: 'top',
animation: true,
popupDelay: 0
};
// Default hide triggers for each show trigger
var triggerMap = {
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur'
};
// The options specified to the provider globally.
var globalOptions = {};
/**
* `options({})` allows global configuration of all tooltips in the
* application.
*
* var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
* // place tooltips left instead of top by default
* $tooltipProvider.options( { placement: 'left' } );
* });
*/
this.options = function (value) {
angular.extend(globalOptions, value);
};
/**
* This allows you to extend the set of trigger mappings available. E.g.:
*
* $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
*/
this.setTriggers = function setTriggers(triggers) {
angular.extend(triggerMap, triggers);
};
/**
* This is a helper function for translating camel-case to snake-case.
*/
function snake_case(name) {
var regexp = /[A-Z]/g;
var separator = '-';
return name.replace(regexp, function (letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
/**
* Returns the actual instance of the $tooltip service.
* TODO support multiple triggers
*/
this.$get = ['$window', '$compile', '$timeout', '$parse', '$document', '$position', '$interpolate', function ($window, $compile, $timeout, $parse, $document, $position, $interpolate) {
return function $tooltip(type, prefix, defaultTriggerShow) {
var options = angular.extend({}, defaultOptions, globalOptions);
/**
* Returns an object of show and hide triggers.
*
* If a trigger is supplied,
* it is used to show the tooltip; otherwise, it will use the `trigger`
* option passed to the `$tooltipProvider.options` method; else it will
* default to the trigger supplied to this directive factory.
*
* The hide trigger is based on the show trigger. If the `trigger` option
* was passed to the `$tooltipProvider.options` method, it will use the
* mapped trigger from `triggerMap` or the passed trigger if the map is
* undefined; otherwise, it uses the `triggerMap` value of the show
* trigger; else it will just use the show trigger.
*/
function getTriggers(trigger) {
var show = trigger || options.trigger || defaultTriggerShow;
var hide = triggerMap[show] || show;
return {
show: show,
hide: hide
};
}
var directiveName = snake_case(type);
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var template =
'<div ' + directiveName + '-popup ' +
'title="' + startSym + 'tt_title' + endSym + '" ' +
'content="' + startSym + 'tt_content' + endSym + '" ' +
'placement="' + startSym + 'tt_placement' + endSym + '" ' +
'animation="tt_animation" ' +
'is-open="tt_isOpen"' +
'>' +
'</div>';
return {
restrict: 'EA',
scope: true,
link: function link(scope, element, attrs) {
var tooltip = $compile(template)(scope);
var transitionTimeout;
var popupTimeout;
var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false;
var triggers = getTriggers(undefined);
var hasRegisteredTriggers = false;
var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']);
// By default, the tooltip is not open.
// TODO add ability to start tooltip opened
scope.tt_isOpen = false;
function toggleTooltipBind() {
if (!scope.tt_isOpen) {
showTooltipBind();
} else {
hideTooltipBind();
}
}
// Show the tooltip with delay if specified, otherwise show it immediately
function showTooltipBind() {
if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) {
return;
}
if (scope.tt_popupDelay) {
popupTimeout = $timeout(show, scope.tt_popupDelay);
} else {
scope.$apply(show);
}
}
function hideTooltipBind() {
scope.$apply(function () {
hide();
});
}
// Show the tooltip popup element.
function show() {
var position,
ttWidth,
ttHeight,
ttPosition;
// Don't show empty tooltips.
if (!scope.tt_content) {
return;
}
// If there is a pending remove transition, we must cancel it, lest the
// tooltip be mysteriously removed.
if (transitionTimeout) {
$timeout.cancel(transitionTimeout);
}
// Set the initial positioning.
tooltip.css({top: 0, left: 0, display: 'block'});
// Now we add it to the DOM because need some info about it. But it's not
// visible yet anyway.
if (appendToBody) {
$document.find('body').append(tooltip);
} else {
element.after(tooltip);
}
// Get the position of the directive element.
position = appendToBody ? $position.offset(element) : $position.position(element);
// Get the height and width of the tooltip so we can center it.
ttWidth = tooltip.prop('offsetWidth');
ttHeight = tooltip.prop('offsetHeight');
// Calculate the tooltip's top and left coordinates to center it with
// this directive.
switch (scope.tt_placement) {
case 'right':
ttPosition = {
top: position.top + position.height / 2 - ttHeight / 2,
left: position.left + position.width
};
break;
case 'bottom':
ttPosition = {
top: position.top + position.height,
left: position.left + position.width / 2 - ttWidth / 2
};
break;
case 'left':
ttPosition = {
top: position.top + position.height / 2 - ttHeight / 2,
left: position.left - ttWidth
};
break;
default:
ttPosition = {
top: position.top - ttHeight,
left: position.left + position.width / 2 - ttWidth / 2
};
break;
}
ttPosition.top += 'px';
ttPosition.left += 'px';
// Now set the calculated positioning.
tooltip.css(ttPosition);
// And show the tooltip.
scope.tt_isOpen = true;
}
// Hide the tooltip popup element.
function hide() {
// First things first: we don't show it anymore.
scope.tt_isOpen = false;
//if tooltip is going to be shown after delay, we must cancel this
$timeout.cancel(popupTimeout);
// And now we remove it from the DOM. However, if we have animation, we
// need to wait for it to expire beforehand.
// FIXME: this is a placeholder for a port of the transitions library.
if (scope.tt_animation) {
transitionTimeout = $timeout(function () {
tooltip.remove();
}, 500);
} else {
tooltip.remove();
}
}
/**
* Observe the relevant attributes.
*/
attrs.$observe(type, function (val) {
scope.tt_content = val;
if (!val && scope.tt_isOpen) {
hide();
}
});
attrs.$observe(prefix + 'Title', function (val) {
scope.tt_title = val;
});
attrs.$observe(prefix + 'Placement', function (val) {
scope.tt_placement = angular.isDefined(val) ? val : options.placement;
});
attrs.$observe(prefix + 'PopupDelay', function (val) {
var delay = parseInt(val, 10);
scope.tt_popupDelay = !isNaN(delay) ? delay : options.popupDelay;
});
var unregisterTriggers = function () {
if (hasRegisteredTriggers) {
element.unbind(triggers.show, showTooltipBind);
element.unbind(triggers.hide, hideTooltipBind);
}
};
attrs.$observe(prefix + 'Trigger', function (val) {
unregisterTriggers();
triggers = getTriggers(val);
if (triggers.show === triggers.hide) {
element.bind(triggers.show, toggleTooltipBind);
} else {
element.bind(triggers.show, showTooltipBind);
element.bind(triggers.hide, hideTooltipBind);
}
hasRegisteredTriggers = true;
});
var animation = scope.$eval(attrs[prefix + 'Animation']);
scope.tt_animation = angular.isDefined(animation) ? !!animation : options.animation;
attrs.$observe(prefix + 'AppendToBody', function (val) {
appendToBody = angular.isDefined(val) ? $parse(val)(scope) : appendToBody;
});
// if a tooltip is attached to <body> we need to remove it on
// location change as its parent scope will probably not be destroyed
// by the change.
if (appendToBody) {
scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess() {
if (scope.tt_isOpen) {
hide();
}
});
}
// Make sure tooltip is destroyed and removed.
scope.$on('$destroy', function onDestroyTooltip() {
$timeout.cancel(transitionTimeout);
$timeout.cancel(popupTimeout);
unregisterTriggers();
tooltip.remove();
tooltip.unbind();
tooltip = null;
});
}
};
};
}];
})
.directive('tooltipPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: {content: '@', placement: '@', animation: '&', isOpen: '&'},
templateUrl: 'template/tooltip/tooltip-popup.html'
};
})
.directive('tooltip', ['$tooltip', function ($tooltip) {
return $tooltip('tooltip', 'tooltip', 'mouseenter');
}])
.directive('tooltipHtmlUnsafePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: {content: '@', placement: '@', animation: '&', isOpen: '&'},
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
};
})
.directive('tooltipHtmlUnsafe', ['$tooltip', function ($tooltip) {
return $tooltip('tooltipHtmlUnsafe', 'tooltip', 'mouseenter');
}]);
/**
* The following features are still outstanding: popup delay, animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html popovers, and selector delegatation.
*/
angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip'])
.directive('popoverPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: {title: '@', content: '@', placement: '@', animation: '&', isOpen: '&'},
templateUrl: 'template/popover/popover.html'
};
})
.directive('popover', ['$compile', '$timeout', '$parse', '$window', '$tooltip', function ($compile, $timeout, $parse, $window, $tooltip) {
return $tooltip('popover', 'popover', 'click');
}]);
angular.module('ui.bootstrap.progressbar', ['ui.bootstrap.transition'])
.constant('progressConfig', {
animate: true,
max: 100
})
.controller('ProgressController', ['$scope', '$attrs', 'progressConfig', '$transition', function ($scope, $attrs, progressConfig, $transition) {
var self = this,
bars = [],
max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max,
animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
this.addBar = function (bar, element) {
var oldValue = 0, index = bar.$parent.$index;
if (angular.isDefined(index) && bars[index]) {
oldValue = bars[index].value;
}
bars.push(bar);
this.update(element, bar.value, oldValue);
bar.$watch('value', function (value, oldValue) {
if (value !== oldValue) {
self.update(element, value, oldValue);
}
});
bar.$on('$destroy', function () {
self.removeBar(bar);
});
};
// Update bar element width
this.update = function (element, newValue, oldValue) {
var percent = this.getPercentage(newValue);
if (animate) {
element.css('width', this.getPercentage(oldValue) + '%');
$transition(element, {width: percent + '%'});
} else {
element.css({'transition': 'none', 'width': percent + '%'});
}
};
this.removeBar = function (bar) {
bars.splice(bars.indexOf(bar), 1);
};
this.getPercentage = function (value) {
return Math.round(100 * value / max);
};
}])
.directive('progress', function () {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
require: 'progress',
scope: {},
template: '<div class="progress" ng-transclude></div>'
//templateUrl: 'template/progressbar/progress.html' // Works in AngularJS 1.2
};
})
.directive('bar', function () {
return {
restrict: 'EA',
replace: true,
transclude: true,
require: '^progress',
scope: {
value: '=',
type: '@'
},
templateUrl: 'template/progressbar/bar.html',
link: function (scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, element);
}
};
})
.directive('progressbar', function () {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
scope: {
value: '=',
type: '@'
},
templateUrl: 'template/progressbar/progressbar.html',
link: function (scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, angular.element(element.children()[0]));
}
};
});
angular.module('ui.bootstrap.rating', [])
.constant('ratingConfig', {
max: 5,
stateOn: null,
stateOff: null
})
.controller('RatingController', ['$scope', '$attrs', '$parse', 'ratingConfig', function ($scope, $attrs, $parse, ratingConfig) {
this.maxRange = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max;
this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
this.createRateObjects = function (states) {
var defaultOptions = {
stateOn: this.stateOn,
stateOff: this.stateOff
};
for (var i = 0, n = states.length; i < n; i++) {
states[i] = angular.extend({index: i}, defaultOptions, states[i]);
}
return states;
};
// Get objects used in template
$scope.range = angular.isDefined($attrs.ratingStates) ? this.createRateObjects(angular.copy($scope.$parent.$eval($attrs.ratingStates))) : this.createRateObjects(new Array(this.maxRange));
$scope.rate = function (value) {
if ($scope.readonly || $scope.value === value) {
return;
}
$scope.value = value;
};
$scope.enter = function (value) {
if (!$scope.readonly) {
$scope.val = value;
}
$scope.onHover({value: value});
};
$scope.reset = function () {
$scope.val = angular.copy($scope.value);
$scope.onLeave();
};
$scope.$watch('value', function (value) {
$scope.val = value;
});
$scope.readonly = false;
if ($attrs.readonly) {
$scope.$parent.$watch($parse($attrs.readonly), function (value) {
$scope.readonly = !!value;
});
}
}])
.directive('rating', function () {
return {
restrict: 'EA',
scope: {
value: '=',
onHover: '&',
onLeave: '&'
},
controller: 'RatingController',
templateUrl: 'template/rating/rating.html',
replace: true
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.tabs
*
* @description
* AngularJS version of the tabs directive.
*/
angular.module('ui.bootstrap.tabs', [])
.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
var ctrl = this,
tabs = ctrl.tabs = $scope.tabs = [];
ctrl.select = function (tab) {
angular.forEach(tabs, function (tab) {
tab.active = false;
});
tab.active = true;
};
ctrl.addTab = function addTab(tab) {
tabs.push(tab);
if (tabs.length === 1 || tab.active) {
ctrl.select(tab);
}
};
ctrl.removeTab = function removeTab(tab) {
var index = tabs.indexOf(tab);
//Select a new tab if the tab to be removed is selected
if (tab.active && tabs.length > 1) {
//If this is the last tab, select the previous tab. else, the next tab.
var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
ctrl.select(tabs[newActiveIndex]);
}
tabs.splice(index, 1);
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabset
* @restrict EA
*
* @description
* Tabset is the outer container for the tabs directive
*
* @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab heading="Vertical Tab 1"><b>First</b> Content!</tab>
<tab heading="Vertical Tab 2"><i>Second</i> Content!</tab>
</tabset>
<hr />
<tabset vertical="true">
<tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
<tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
</tabset>
</file>
</example>
*/
.directive('tabset', function () {
return {
restrict: 'EA',
transclude: true,
replace: true,
scope: {},
controller: 'TabsetController',
templateUrl: 'template/tabs/tabset.html',
link: function (scope, element, attrs) {
scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
scope.type = angular.isDefined(attrs.type) ? scope.$parent.$eval(attrs.type) : 'tabs';
}
};
})
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tab
* @restrict EA
*
* @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
* @param {string=} select An expression to evaluate when the tab is selected.
* @param {boolean=} active A binding, telling whether or not this tab is selected.
* @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
*
* @description
* Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="TabsDemoCtrl">
<button class="btn btn-small" ng-click="items[0].active = true">
Select item 1, using active binding
</button>
<button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
Enable/disable item 2, using disabled binding
</button>
<br />
<tabset>
<tab heading="Tab 1">First Tab</tab>
<tab select="alertMe()">
<tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
Second Tab, with alert callback and html heading!
</tab>
<tab ng-repeat="item in items"
heading="{{item.title}}"
disabled="item.disabled"
active="item.active">
{{item.content}}
</tab>
</tabset>
</div>
</file>
<file name="script.js">
function TabsDemoCtrl($scope) {
$scope.items = [
{ title:"Dynamic Title 1", content:"Dynamic Item 0" },
{ title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
];
$scope.alertMe = function() {
setTimeout(function() {
alert("You've selected the alert tab!");
});
};
};
</file>
</example>
*/
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabHeading
* @restrict EA
*
* @description
* Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab>
<tab-heading><b>HTML</b> in my titles?!</tab-heading>
And some content, too!
</tab>
<tab>
<tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
That's right.
</tab>
</tabset>
</file>
</example>
*/
.directive('tab', ['$parse', function ($parse) {
return {
require: '^tabset',
restrict: 'EA',
replace: true,
templateUrl: 'template/tabs/tab.html',
transclude: true,
scope: {
heading: '@',
onSelect: '&select', //This callback is called in contentHeadingTransclude
//once it inserts the tab's content into the dom
onDeselect: '&deselect'
},
controller: function () {
//Empty controller so other directives can require being 'under' a tab
},
compile: function (elm, attrs, transclude) {
return function postLink(scope, elm, attrs, tabsetCtrl) {
var getActive, setActive;
if (attrs.active) {
getActive = $parse(attrs.active);
setActive = getActive.assign;
scope.$parent.$watch(getActive, function updateActive(value, oldVal) {
// Avoid re-initializing scope.active as it is already initialized
// below. (watcher is called async during init with value ===
// oldVal)
if (value !== oldVal) {
scope.active = !!value;
}
});
scope.active = getActive(scope.$parent);
} else {
setActive = getActive = angular.noop;
}
scope.$watch('active', function (active) {
// Note this watcher also initializes and assigns scope.active to the
// attrs.active expression.
setActive(scope.$parent, active);
if (active) {
tabsetCtrl.select(scope);
scope.onSelect();
} else {
scope.onDeselect();
}
});
scope.disabled = false;
if (attrs.disabled) {
scope.$parent.$watch($parse(attrs.disabled), function (value) {
scope.disabled = !!value;
});
}
scope.select = function () {
if (!scope.disabled) {
scope.active = true;
}
};
tabsetCtrl.addTab(scope);
scope.$on('$destroy', function () {
tabsetCtrl.removeTab(scope);
});
//We need to transclude later, once the content container is ready.
//when this link happens, we're inside a tab heading.
scope.$transcludeFn = transclude;
};
}
};
}])
.directive('tabHeadingTransclude', [function () {
return {
restrict: 'A',
require: '^tab',
link: function (scope, elm, attrs, tabCtrl) {
scope.$watch('headingElement', function updateHeadingElement(heading) {
if (heading) {
elm.html('');
elm.append(heading);
}
});
}
};
}])
.directive('tabContentTransclude', function () {
return {
restrict: 'A',
require: '^tabset',
link: function (scope, elm, attrs) {
var tab = scope.$eval(attrs.tabContentTransclude);
//Now our tab is ready to be transcluded: both the tab heading area
//and the tab content area are loaded. Transclude 'em both.
tab.$transcludeFn(tab.$parent, function (contents) {
angular.forEach(contents, function (node) {
if (isTabHeading(node)) {
//Let tabHeadingTransclude know.
tab.headingElement = node;
} else {
elm.append(node);
}
});
});
}
};
function isTabHeading(node) {
return node.tagName && (
node.hasAttribute('tab-heading') ||
node.hasAttribute('data-tab-heading') ||
node.tagName.toLowerCase() === 'tab-heading' ||
node.tagName.toLowerCase() === 'data-tab-heading'
);
}
})
;
angular.module('ui.bootstrap.timepicker', [])
.constant('timepickerConfig', {
hourStep: 1,
minuteStep: 1,
showMeridian: true,
meridians: null,
readonlyInput: false,
mousewheel: true
})
.directive('timepicker', ['$parse', '$log', 'timepickerConfig', '$locale', function ($parse, $log, timepickerConfig, $locale) {
return {
restrict: 'EA',
require: '?^ngModel',
replace: true,
scope: {},
templateUrl: 'template/timepicker/timepicker.html',
link: function (scope, element, attrs, ngModel) {
if (!ngModel) {
return; // do nothing if no ng-model
}
var selected = new Date(),
meridians = angular.isDefined(attrs.meridians) ? scope.$parent.$eval(attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;
var hourStep = timepickerConfig.hourStep;
if (attrs.hourStep) {
scope.$parent.$watch($parse(attrs.hourStep), function (value) {
hourStep = parseInt(value, 10);
});
}
var minuteStep = timepickerConfig.minuteStep;
if (attrs.minuteStep) {
scope.$parent.$watch($parse(attrs.minuteStep), function (value) {
minuteStep = parseInt(value, 10);
});
}
// 12H / 24H mode
scope.showMeridian = timepickerConfig.showMeridian;
if (attrs.showMeridian) {
scope.$parent.$watch($parse(attrs.showMeridian), function (value) {
scope.showMeridian = !!value;
if (ngModel.$error.time) {
// Evaluate from template
var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
if (angular.isDefined(hours) && angular.isDefined(minutes)) {
selected.setHours(hours);
refresh();
}
} else {
updateTemplate();
}
});
}
// Get scope.hours in 24H mode if valid
function getHoursFromTemplate() {
var hours = parseInt(scope.hours, 10);
var valid = ( scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
if (!valid) {
return undefined;
}
if (scope.showMeridian) {
if (hours === 12) {
hours = 0;
}
if (scope.meridian === meridians[1]) {
hours = hours + 12;
}
}
return hours;
}
function getMinutesFromTemplate() {
var minutes = parseInt(scope.minutes, 10);
return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
}
function pad(value) {
return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;
}
// Input elements
var inputs = element.find('input'), hoursInputEl = inputs.eq(0), minutesInputEl = inputs.eq(1);
// Respond on mousewheel spin
var mousewheel = (angular.isDefined(attrs.mousewheel)) ? scope.$eval(attrs.mousewheel) : timepickerConfig.mousewheel;
if (mousewheel) {
var isScrollingUp = function (e) {
if (e.originalEvent) {
e = e.originalEvent;
}
//pick correct delta variable depending on event
var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
return (e.detail || delta > 0);
};
hoursInputEl.bind('mousewheel wheel', function (e) {
scope.$apply((isScrollingUp(e)) ? scope.incrementHours() : scope.decrementHours());
e.preventDefault();
});
minutesInputEl.bind('mousewheel wheel', function (e) {
scope.$apply((isScrollingUp(e)) ? scope.incrementMinutes() : scope.decrementMinutes());
e.preventDefault();
});
}
scope.readonlyInput = (angular.isDefined(attrs.readonlyInput)) ? scope.$eval(attrs.readonlyInput) : timepickerConfig.readonlyInput;
if (!scope.readonlyInput) {
var invalidate = function (invalidHours, invalidMinutes) {
ngModel.$setViewValue(null);
ngModel.$setValidity('time', false);
if (angular.isDefined(invalidHours)) {
scope.invalidHours = invalidHours;
}
if (angular.isDefined(invalidMinutes)) {
scope.invalidMinutes = invalidMinutes;
}
};
scope.updateHours = function () {
var hours = getHoursFromTemplate();
if (angular.isDefined(hours)) {
selected.setHours(hours);
refresh('h');
} else {
invalidate(true);
}
};
hoursInputEl.bind('blur', function (e) {
if (!scope.validHours && scope.hours < 10) {
scope.$apply(function () {
scope.hours = pad(scope.hours);
});
}
});
scope.updateMinutes = function () {
var minutes = getMinutesFromTemplate();
if (angular.isDefined(minutes)) {
selected.setMinutes(minutes);
refresh('m');
} else {
invalidate(undefined, true);
}
};
minutesInputEl.bind('blur', function (e) {
if (!scope.invalidMinutes && scope.minutes < 10) {
scope.$apply(function () {
scope.minutes = pad(scope.minutes);
});
}
});
} else {
scope.updateHours = angular.noop;
scope.updateMinutes = angular.noop;
}
ngModel.$render = function () {
var date = ngModel.$modelValue ? new Date(ngModel.$modelValue) : null;
if (isNaN(date)) {
ngModel.$setValidity('time', false);
$log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
} else {
if (date) {
selected = date;
}
makeValid();
updateTemplate();
}
};
// Call internally when we know that model is valid.
function refresh(keyboardChange) {
makeValid();
ngModel.$setViewValue(new Date(selected));
updateTemplate(keyboardChange);
}
function makeValid() {
ngModel.$setValidity('time', true);
scope.invalidHours = false;
scope.invalidMinutes = false;
}
function updateTemplate(keyboardChange) {
var hours = selected.getHours(), minutes = selected.getMinutes();
if (scope.showMeridian) {
hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
}
scope.hours = keyboardChange === 'h' ? hours : pad(hours);
scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);
scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
}
function addMinutes(minutes) {
var dt = new Date(selected.getTime() + minutes * 60000);
selected.setHours(dt.getHours(), dt.getMinutes());
refresh();
}
scope.incrementHours = function () {
addMinutes(hourStep * 60);
};
scope.decrementHours = function () {
addMinutes(-hourStep * 60);
};
scope.incrementMinutes = function () {
addMinutes(minuteStep);
};
scope.decrementMinutes = function () {
addMinutes(-minuteStep);
};
scope.toggleMeridian = function () {
addMinutes(12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1));
};
}
};
}]);
angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
/**
* A helper service that can parse typeahead's syntax (string provided by users)
* Extracted to a separate service for ease of unit testing
*/
.factory('typeaheadParser', ['$parse', function ($parse) {
// 00000111000000000000022200000000000000003333333333333330000000000044000
var TYPEAHEAD_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+(.*)$/;
return {
parse: function (input) {
var match = input.match(TYPEAHEAD_REGEXP), modelMapper, viewMapper, source;
if (!match) {
throw new Error(
"Expected typeahead specification in form of '_modelValue_ (as _label_)? for _item_ in _collection_'" +
" but got '" + input + "'.");
}
return {
itemName: match[3],
source: $parse(match[4]),
viewMapper: $parse(match[2] || match[1]),
modelMapper: $parse(match[1])
};
}
};
}])
.directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser',
function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) {
var HOT_KEYS = [9, 13, 27, 38, 40];
return {
require: 'ngModel',
link: function (originalScope, element, attrs, modelCtrl) {
//SUPPORTED ATTRIBUTES (OPTIONS)
//minimal no of characters that needs to be entered before typeahead kicks-in
var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;
//minimal wait time after last character typed before typehead kicks-in
var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
//should it restrict model values to the ones selected from the popup only?
var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
//binding to a variable that indicates if matches are being retrieved asynchronously
var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
//a callback executed when a match is selected
var onSelectCallback = $parse(attrs.typeaheadOnSelect);
var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
var appendToBody = attrs.typeaheadAppendToBody ? $parse(attrs.typeaheadAppendToBody) : false;
//INTERNAL VARIABLES
//model setter executed upon match selection
var $setModelValue = $parse(attrs.ngModel).assign;
//expressions used by typeahead
var parserResult = typeaheadParser.parse(attrs.typeahead);
var hasFocus;
//pop-up element used to display matches
var popUpEl = angular.element('<div typeahead-popup></div>');
popUpEl.attr({
matches: 'matches',
active: 'activeIdx',
select: 'select(activeIdx)',
query: 'query',
position: 'position'
});
//custom item template
if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
}
//create a child scope for the typeahead directive so we are not polluting original scope
//with typeahead-specific data (matches, query etc.)
var scope = originalScope.$new();
originalScope.$on('$destroy', function () {
scope.$destroy();
});
var resetMatches = function () {
scope.matches = [];
scope.activeIdx = -1;
};
var getMatchesAsync = function (inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function (matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
if (inputValue === modelCtrl.$viewValue && hasFocus) {
if (matches.length > 0) {
scope.activeIdx = 0;
scope.matches.length = 0;
//transform labels
for (var i = 0; i < matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
} else {
resetMatches();
}
isLoadingSetter(originalScope, false);
}
}, function () {
resetMatches();
isLoadingSetter(originalScope, false);
});
};
resetMatches();
//we need to propagate user's query so we can higlight matches
scope.query = undefined;
//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
var timeoutPromise;
//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
modelCtrl.$parsers.unshift(function (inputValue) {
hasFocus = true;
if (inputValue && inputValue.length >= minSearch) {
if (waitTime > 0) {
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);//cancel previous timeout
}
timeoutPromise = $timeout(function () {
getMatchesAsync(inputValue);
}, waitTime);
} else {
getMatchesAsync(inputValue);
}
} else {
isLoadingSetter(originalScope, false);
resetMatches();
}
if (isEditable) {
return inputValue;
} else {
if (!inputValue) {
// Reset in case user had typed something previously.
modelCtrl.$setValidity('editable', true);
return inputValue;
} else {
modelCtrl.$setValidity('editable', false);
return undefined;
}
}
});
modelCtrl.$formatters.push(function (modelValue) {
var candidateViewValue, emptyViewValue;
var locals = {};
if (inputFormatter) {
locals['$model'] = modelValue;
return inputFormatter(originalScope, locals);
} else {
//it might happen that we don't have enough info to properly render input value
//we need to check for this situation and simply return model value if we can't apply custom formatting
locals[parserResult.itemName] = modelValue;
candidateViewValue = parserResult.viewMapper(originalScope, locals);
locals[parserResult.itemName] = undefined;
emptyViewValue = parserResult.viewMapper(originalScope, locals);
return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue;
}
});
scope.select = function (activeIdx) {
//called from within the $digest() cycle
var locals = {};
var model, item;
locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
model = parserResult.modelMapper(originalScope, locals);
$setModelValue(originalScope, model);
modelCtrl.$setValidity('editable', true);
onSelectCallback(originalScope, {
$item: item,
$model: model,
$label: parserResult.viewMapper(originalScope, locals)
});
resetMatches();
//return focus to the input element if a mach was selected via a mouse click event
element[0].focus();
};
//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
element.bind('keydown', function (evt) {
//typeahead is open and an "interesting" key was pressed
if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
return;
}
evt.preventDefault();
if (evt.which === 40) {
scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
scope.$digest();
} else if (evt.which === 38) {
scope.activeIdx = (scope.activeIdx ? scope.activeIdx : scope.matches.length) - 1;
scope.$digest();
} else if (evt.which === 13 || evt.which === 9) {
scope.$apply(function () {
scope.select(scope.activeIdx);
});
} else if (evt.which === 27) {
evt.stopPropagation();
resetMatches();
scope.$digest();
}
});
element.bind('blur', function (evt) {
hasFocus = false;
});
// Keep reference to click handler to unbind it.
var dismissClickHandler = function (evt) {
if (element[0] !== evt.target) {
resetMatches();
scope.$digest();
}
};
$document.bind('click', dismissClickHandler);
originalScope.$on('$destroy', function () {
$document.unbind('click', dismissClickHandler);
});
var $popup = $compile(popUpEl)(scope);
if (appendToBody) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
}
};
}])
.directive('typeaheadPopup', function () {
return {
restrict: 'EA',
scope: {
matches: '=',
query: '=',
active: '=',
position: '=',
select: '&'
},
replace: true,
templateUrl: 'template/typeahead/typeahead-popup.html',
link: function (scope, element, attrs) {
scope.templateUrl = attrs.templateUrl;
scope.isOpen = function () {
return scope.matches.length > 0;
};
scope.isActive = function (matchIdx) {
return scope.active == matchIdx;
};
scope.selectActive = function (matchIdx) {
scope.active = matchIdx;
};
scope.selectMatch = function (activeIdx) {
scope.select({activeIdx: activeIdx});
};
}
};
})
.directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) {
return {
restrict: 'EA',
scope: {
index: '=',
match: '=',
query: '='
},
link: function (scope, element, attrs) {
var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
$http.get(tplUrl, {cache: $templateCache}).success(function (tplContent) {
element.replaceWith($compile(tplContent.trim())(scope));
});
}
};
}])
.filter('typeaheadHighlight', function () {
function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
return function (matchItem, query) {
return query ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
};
});
|
/*
'use strict';
var superagent = require('superagent');
var chaiExpect = require('chai').expect;
var Mirror = require('../models/Mirror');
describe('Mirror Model Unit Tests:', function() {
var mirror = null;
beforeEach(function(done) {
mirror = new Mirror({
email: 'treyqg15',
phone: '6011111111'
});
mirror.save(function() {
done();
});
});
describe('Has Attribute Email', function() {
it('Should have an attribute called Email', function(done) {
console.log('email: ' + mirror.email);
chaiExpect(mirror).to.have.property('email');
done();
});
});
describe('Email Attribute Not Empty', function() {
it('Email Attribute should contain a value', function(done) {
console.log('email: ' + mirror.email);
chaiExpect(mirror).to.have.property('email').that.has.length.above(0);
done();
});
});
describe('Email Attribute Is String', function() {
it('Email Attribute should be a String', function(done) {
console.log('email: ' + mirror.email);
chaiExpect(mirror).to.have.property('email').that.is.a('string');
done();
});
});
afterEach(function(done) {
Mirror.remove().exec();
done();
});
});
describe('AJAX Requests', function() {
describe('POST Requests',function(done) {
it('POST: create new object', function(done) {
superagent.post('http://localhost:3000/test/')
.send({
name: 'John',
email: 'john@rpjs.co'
})
.end(function(e,res){
console.log(e);
chaiExpect(e).to.eql(null);
console.log(res.body);
done();
});
});
});
describe('GET Requests',function(done) {
var id = null;
it('GET: retrieves all test objects', function(done){
superagent.get('http://localhost:3000/test/')
.end(function(e, res){
console.log(e);
chaiExpect(e).to.eql(null);
console.log(res.body);
chaiExpect(typeof res.body).to.eql('object');
id = res.body[0]._id;
done();
});
});
it('GET: retrieve object with ID', function(done){
superagent.get('http://localhost:3000/test/'+id)
.end(function(e, res){
console.log(e);
chaiExpect(e).to.eql(null);
console.log(res.body);
chaiExpect(typeof res.body).to.eql('object');
done();
});
});
});
});
*/ |
'use strict';
var path = require('path');
var fs = require('fs');
var sign = require('upyun-http-signature');
var async = require('async');
var request = require('request');
var pkg = require('../package.json');
module.exports = function(list, config, callback) {
if(list.length <= 0) {
return callback('no job to do');
}
async.eachLimit(list, 20, function(item, callback) {
fs.stat(item, function(err, stats) {
if (err) {
return callback(err);
}
var length = stats.size;
var date = new Date().toGMTString();
//request options
var options = {
url: 'http://v0.api.upyun.com/',
headers: {
'User-Agent': 'UPYUN-Hopper/' + pkg.version,
'Mkdir': true
}
};
options.headers.Authorization = sign('PUT', path.join(config.bucket, config.path || '', path.basename(item)), date, length, config.password, config.operator);
options.headers.Date = date;
options.url = options.url + path.join(config.bucket, config.path || '', path.basename(item));
fs.createReadStream(item).pipe(request.put(options, function(err, res, body) {
if (err) {
return callback(err);
}
callback(null);
}));
})
}, function(err) {
if(err) {
return callback(err);
}
var result = list.map(function(item) {
return path.join('http://' + config.bucket + '.b0.upaiyun.com/', config.path, path.basename(item));
});
callback(null, result);
});
};
|
var validation = require("utilities/validation");
module.exports = Backbone.Model.extend({
validate: function() {
var attrs = this.attributes, errors = [];
if (!validation.required(attrs.role))
errors.push({ key: "role", message: "The role is required." });
if (!validation.required(attrs.company))
errors.push({ key: "company", message: "The company is required." });
if (!validation.required(attrs.operatingArea))
errors.push({ key: "operatingArea", message: "The operating area is required." });
if (!validation.required(attrs.firstName))
errors.push({ key: "firstName", message: "The first name is required." });
if (!validation.required(attrs.lastName))
errors.push({ key: "lastName", message: "The last name is required." });
if (attrs.phone !== "" && !validation.phone(attrs.phone))
errors.push({ key: "phone", message: "The phone number is invalid." });
if (!validation.email(attrs.email))
errors.push({ key: "email", message: "The email address is invalid." });
if (!validation.required(attrs.password))
errors.push({ key: "password", message: "The password is required." });
if (!validation.required(attrs.confirmedPassword))
errors.push({ key: "confirmedPassword", message: "The confirmed password is required." });
if (attrs.password !== attrs.confirmedPassword) {
errors.push({ key: "password", message: "The passwords must match." });
errors.push({ key: "confirmedPassword", message: "The passwords must match." });
}
return errors;
}
}); |
'use strict';
module.exports = function(Group) {
// Group.getEntireCompany = function(id,cb) {
// var app = Team.app;
// Team.findById(id, function(err, team) {
// // links the object
// if(err) {
// console.log(err);
// } else {
// team.members({ teamId:id },function(err, profiles){
// team.projects({ teamId:id },function(err, products){
// // Team.media({ teamId:id },function(err, media){
// var media = { files : [ 'http://bit.ly/1IuNOek', 'http://bit.ly/1M9PmiD' ]};
// // ----- compile object for response -----
// var response = {
// details: team,
// members : profiles,
// projects : products,
// media: media
// };
// cb(null, response);
// // });
// });
// });
// }
// });
// };
//
//
// Team.remoteMethod('getEntireCompany', {
// accepts: [{arg: 'id', type: 'string'}],
// returns: {arg: 'company', type: 'object'},
// http: {path:'/entirecompany/:id', verb: 'get'}
// });
//
// Team.getPartCompany = function(id,cb) {
// var app = Team.app;
// Team.findById(id, function(err, team) {
// // links the object
// if(err) {
// console.log(err);
// } else {
// team.members({ teamId:id },function(err, profiles){
// var media = { files : [ 'http://bit.ly/1IuNOek', 'http://bit.ly/1M9PmiD' ]};
// // ----- compile object for response -----
// var response = {
// details: team,
// members : profiles,
// media: media
// };
// cb(null, response);
// });
// }
// });
// };
//
//
// Team.remoteMethod('getPartCompany', {
// accepts: [{arg: 'id', type: 'string'}],
// returns: {arg: 'team', type: 'object'},
// http: {path:'/partcompany/:id', verb: 'get'}
// });
};
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import NavItem from './NavItem.react';
const SidebarNav = () => {
return (
<ul className="sidebar-nav">
<NavItem glyph="dashboard" name="Dashboard" />
<NavItem glyph="envelope" name="Mailbox" />
<NavItem glyph="picture" name="Gallery" />
<NavItem glyph="calendar" name="Calendar" />
<NavItem glyph="stats" name="Data" />
</ul>
);
};
// Which props do we want to inject, given the global state?
const select = (state) => ({ data: state });
// Wrap the component to inject dispatch and state into it
export default connect(select)(SidebarNav); |
import React from 'react';
import PropTypes from 'prop-types';
const Icon = (props) =>
<svg
width={props.width}
height={props.height}
viewBox={props.viewBox}
color={props.color}
>
<path d={props.icon} />
</svg>;
Icon.propTypes = {
icon: PropTypes.string.isRequired,
viewBox: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
color: PropTypes.string,
};
Icon.defaultProps = {
width: 32,
height: 32,
color: '#000',
};
export default Icon;
|
// ==UserScript==
// @name browse view: cleaner view by hiding duplicate name information
// @description https://github.com/solygen/userscripts/blob/master/doc/magickartenmarkt.de.md#browse-viewuserjs
// @version 1.0.1
// @grant none
// @icon https://www.magickartenmarkt.de/Products/Singles/Magic+2010/img/c0a10b062a8c3b48a5c29b779b3ac51e/static/misc/favicon-96x96.png
// @namespace https://github.com/solygen/userscripts
// @repository https://github.com/solygen/userscripts.git
// @license MIT
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
//
// @include https://www.magickartenmarkt.de/?mainPage=browseUserProducts*
// @include https://www.magiccardmarket.eu/?mainPage=browseUserProducts*
// @include https://fr.magiccardmarket.eu/?mainPage=browseUserProducts*
// @include https://es.magiccardmarket.eu/?mainPage=browseUserProducts*
// @include https://id.magiccardmarket.eu/?mainPage=browseUserProducts*
//
// @updateURL https://rawgithub.com/solygen/userscripts/master/scripts/magickartenmarkt.de/browse-view.user.js
// @downloadURL https://rawgithub.com/solygen/userscripts/master/scripts/magickartenmarkt.de/browse-view.user.js
// @homepage https://github.com/solygen/userscripts
// ==/UserScript==
(function () {
'use strict';
var $summary = $('.navBarTopText').length ? $($('.navBarTopText').children()[0]) : $($('#siteContents').children()[2]),
$table = $('tbody'),
$rows = $('tbody').find('tr'),
list,
hits = 0,
//flag green
tolerance = 0.1,
pricelevel = [],
lastname,
FAVORITE = ' \u2605', //' \u2665',
NOFAVORITE = ' \u2606'; //'\u2661';
//sort cards (name, price)
(function sortCards() {
$rows.sort(function (a, b) {
function getKey(node) {
var price = parseFloat($($(node).children()[13]).text().trim().replace(',', '.').replace('€', ''), 10),
$node = $(node);
//consider playset
if ($($(node).children()[9]).find('img').size()) {
price = price / 4;
}
//hack: +1000 to get right sort order (e.g. 8, 12, 102)
return $($(node).children()[2]).find('a').text() + price + 1000;
}
var keyA = getKey(a),
keyB = getKey(b);
return keyA.localeCompare(keyB);
});
}());
//apply order
(function applyOrder() {
$table.empty();
$.each($rows, function (index, row) {
$table.append(row);
});
}());
//add column header
(function addColumnHeader() {
var header = $('.col_price').clone();
header
.removeClass('col_price')
.addClass('col_price_sold')
.html('∅')
.insertBefore($('.col_price'));
//expand footer row
$('.footerCell_0').attr('colspan', 13);
}());
function addCell(row) {
var cell = $(row.children()[10]).clone();
cell
.addClass('col_price_sold')
.insertBefore($(row.children()[13]));
}
function colorizePrice(price, saleprice, row) {
var field = $(row.children()[14]);
if (!price) {
return;
} else if (saleprice <= parseFloat(price, 10) + tolerance) {
field.css('color', 'green');
} else {
field.css('color', 'red');
}
}
function getSalePrice($row) {
var salesprice = $($row.children()[13])
.text()
.replace(',', '.')
.replace('€', '')
.trim();
return parseFloat(salesprice, 10);
}
function toggle(name) {
var isfav = $('.favorite').text() === FAVORITE;
if (isfav) {
$('.favorite').text(NOFAVORITE);
localStorage.removeItem('favorite:' + name);
} else {
$('.favorite').text(FAVORITE);
localStorage.setItem('favorite:' + name, !isfav);
}
}
function setLevel() {
var level,
name = $('.H1_PageTitle').text().split(' ')[2],
sum = 0;
//sum
$.each(pricelevel, function () {
sum += parseFloat(this) || 0;
});
//average
level = Math.round(sum / pricelevel.length * 100) / 100;
//add level to dom/local storage
$('.H1_PageTitle').text($('.H1_PageTitle').text() + ' (' + level + ')');
level = localStorage.setItem('seller:' + name, level);
//add star
var star = localStorage.getItem('favorite:' + name) ? FAVORITE : NOFAVORITE,
fav = $('<span class="favorite" style="color: red; cursor: pointer">').on('click', function () {toggle(name);} ).append(star);
$('.H1_PageTitle').append(fav);
}
//process entries
list = $($.find('.dualTextDiv')).find('a');
$.each(list, function (index, value) {
var $namecell = $(value),
$row = $($namecell.parent().parent().parent().parent()),
name = $namecell.text(),
price = localStorage.getItem(name),
salesprice = getSalePrice($row);
//consider playset
if ($($row.children()[10]).find('img').size()) {
salesprice = salesprice / 4;
}
//average price (sold)
addCell($row);
colorizePrice(price, salesprice, $row);
//set content of new cell and apply style
if (name === lastname) {
$($row.children()[2]).empty();
$row.css('font-weight', 100)
.find('.col_price_sold').empty();
} else {
hits++;
pricelevel.push(salesprice / (price || salesprice));
$row.find('.col_price_sold')
.text(price ? (price + ' €')
.replace('.', ',') : '');
}
//remember name
lastname = name;
});
//show price level
setLevel();
//update hits value
$summary.text(hits + ' hits');
})();
|
'use strict';
var isUint8Array = require( './../lib' );
console.log( isUint8Array( new Uint8Array( 10 ) ) );
// returns true
console.log( isUint8Array( new Int8Array( 10 ) ) );
// returns false
console.log( isUint8Array( new Uint8ClampedArray( 10 ) ) );
// returns false
console.log( isUint8Array( new Int16Array( 10 ) ) );
// returns false
console.log( isUint8Array( new Uint16Array( 10 ) ) );
// returns false
console.log( isUint8Array( new Int32Array( 10 ) ) );
// returns false
console.log( isUint8Array( new Uint32Array( 10 ) ) );
// returns false
console.log( isUint8Array( new Float32Array( 10 ) ) );
// returns false
console.log( isUint8Array( new Float64Array( 10 ) ) );
// returns false
console.log( isUint8Array( new Array( 10 ) ) );
// returns false
console.log( isUint8Array( {} ) );
// returns false
console.log( isUint8Array( null ) );
// returns false
|
import React, {PureComponent} from 'react';
import {EventEmitter} from 'events';
import PropTypes from 'prop-types';
import autobind from 'autobind-decorator';
import contextMenu from 'electron-context-menu';
@autobind
class ResponseWebview extends PureComponent {
_handleSetWebviewRef (n) {
this._webview = n;
if (n) {
contextMenu({window: this._webview});
}
}
_handleDOMReady () {
this._webview.removeEventListener('dom-ready', this._handleDOMReady);
this._setBody();
}
_setBody () {
const {body, contentType, url} = this.props;
const newBody = body.replace('<head>', `<head><base href="${url}">`);
this._webview.loadURL(`data:${contentType},${encodeURIComponent(newBody)}`);
// This is kind of hacky but electron-context-menu fails to save images if
// this isn't here.
this._webview.webContents = this._webview;
this._webview.webContents.session = new EventEmitter();
}
componentDidUpdate () {
this._setBody();
}
componentDidMount () {
this._webview.addEventListener('dom-ready', this._handleDOMReady);
}
render () {
return (
<webview ref={this._handleSetWebviewRef} src="about:blank"></webview>
);
}
}
ResponseWebview.propTypes = {
body: PropTypes.string.isRequired,
contentType: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
};
export default ResponseWebview;
|
function setName(obj) {
obj.name = "Nicholas";
obj = new Object();
obj.name = "Greg";
}
let person = new Object();
setName(person);
console.log(person.name); // "Nicholas"
|
"use strict";
process.env.SLACK_TOKEN = "12345";
process.env.SLACK_CHANNEL = "abcdef";
const { ServiceBroker } = require("moleculer");
const { MoleculerError } = require("moleculer").Errors;
jest.mock("@slack/client");
const { WebClient } = require('@slack/client');
WebClient.mockImplementation(() => {
return {
chat: {
postMessage: jest.fn().mockImplementationOnce(() => Promise.resolve({
ts: "111"
})).mockImplementation(() => Promise.reject({
message: "errMessage",
detail: "errDetail"
}))
}
};
});
function protectReject(err) {
console.error(err.stack);
expect(err).toBe(true);
}
const SlackService = require("../../src");
describe("Test SlackService", () => {
const broker = new ServiceBroker({ logger: false});
const service = broker.createService(SlackService);
it("should be created", () => {
expect(service).toBeDefined();
});
it("should create Slack client instance", () => {
return broker.start().catch(protectReject).then(() => {
expect(service.client).toBeDefined();
expect(WebClient).toHaveBeenCalledTimes(1);
expect(WebClient).toHaveBeenCalledWith(process.env.SLACK_TOKEN);
});
});
it("should call client.chat.postMessage", () => {
return service.sendMessage("Hello world").catch(protectReject).then(res => {
expect(res).toEqual({
ts: "111"
});
expect(service.client.chat.postMessage).toHaveBeenCalledTimes(1);
expect(service.client.chat.postMessage).toHaveBeenCalledWith({
channel: process.env.SLACK_CHANNEL,
text: "Hello world",
});
});
});
it("should call client.messages.create and return with error", () => {
return service.sendMessage().then(protectReject).catch(err => {
expect(err).toBeInstanceOf(MoleculerError);
expect(err.message).toBe("errMessage errDetail");
expect(err.code).toBe(500);
expect(err.type).toBe("POSTMESSAGE_ERROR");
});
});
it("should call the sendMessage method successfully", () => {
let message = {
sid: "12345"
};
service.sendMessage = jest.fn(() => Promise.resolve(message));
return broker.call("slack.send", {message: "Test Slack"}).catch(protectReject).then(res => {
expect(res).toBe(message);
expect(service.sendMessage).toHaveBeenCalledTimes(1);
expect(service.sendMessage).toHaveBeenCalledWith("Test Slack", undefined);
return broker.stop();
});
});
it("should call the sendMessage method successfully with channel", () => {
let message = {
sid: "12345"
};
service.sendMessage = jest.fn(() => Promise.resolve(message));
return broker.call("slack.send", { message: "Test Slack", channel: "some-topic" }).catch(protectReject).then(res => {
expect(res).toBe(message);
expect(service.sendMessage).toHaveBeenCalledTimes(1);
expect(service.sendMessage).toHaveBeenCalledWith("Test Slack", "some-topic");
return broker.stop();
});
});
it("should call the sendMessage method successfully with channel and thread_ts", () => {
let message = {
sid: "12345"
};
service.sendMessage = jest.fn(() => Promise.resolve(message));
return broker.call("slack.send", { message: "Test Slack", channel: "some-topic" , ts: "some-thread"}).catch(protectReject).then(res => {
expect(res).toBe(message);
expect(service.sendMessage).toHaveBeenCalledTimes(1);
expect(service.sendMessage).toHaveBeenCalledWith("Test Slack", "some-topic", "some-thread");
return broker.stop();
});
});
});
|
var expect = require('chai').expect;
var Drac = require('../');
describe('match rules', function () {
var testFunc = Drac.define({
params: {
name: { match: /^abc[0-9]+/ }
}
}, function(name) { return 'hello ' + name; });
it('should give correct result', function() {
var result = testFunc('abc1230987');
expect(result).to.equal('hello abc1230987');
});
it('should throw error on non-string parameters', function () {
expect(function() {
testFunc(3);
}).to.throw(Error);
});
it('should throw error on invalid parameters', function () {
expect(function() {
testFunc('bbc1230987');
}).to.throw(Error);
});
});
|
define('ember-bootstrap/components/bs-progress', ['exports', 'ember'], function (exports, _ember) {
'use strict';
/**
Use to group one (or more) [Components.ProgressBar](Components.ProgressBar.html) components inside it.
@class Progress
@namespace Components
@extends Ember.Component
@public
*/
exports['default'] = _ember['default'].Component.extend({
classNames: ['progress']
});
}); |
let config = {}
if (process.env.KARROT.FCM_CONFIG === 'dev') {
config = require('./firebase.config.dev').default
}
else if (process.env.KARROT.FCM_CONFIG === 'prod') {
config = require('./firebase.config.prod').default
}
export default config
|
/**
* @author ashconnell / http://ashconnell.com/
*/
var html2canvas = require('html2canvas');
var throttle = require('lodash.throttle');
THREE.Interface = function (html, methods, options) {
THREE.Object3D.call( this );
this.type = 'Interface';
this.methods = methods || {};
this.options = options || {};
this.scaler = 0.0025;
this.queue = [];
// set throttling
if (this.options.throttle !== false) {
this.options.throttle = this.options.throttle || 250;
this.render = throttle(this.render, this.options.throttle);
}
// bind method contexts to this instance
for (var prop in this.methods) {
if (typeof this.methods[prop] === 'function') {
this.methods[prop] = this.methods[prop].bind(this);
}
}
// create singleton image we will update with canvas renders
this.image = new Image();
this.image.onload = this.onImageReady.bind(this);
// render the interface plane
this.render(html);
}
THREE.Interface.prototype = Object.create( THREE.Object3D.prototype );
THREE.Interface.prototype.constructor = THREE.Interface;
THREE.Interface.prototype.render = function (html) {
// convert html to element
if (html) {
this.element = this.makeElement(html);
}
// clone the elment and add to dom
var clone = this.element.cloneNode(true);
this.queue.push(clone);
if (!this.isRendering) {
this.renderNext();
}
}
THREE.Interface.prototype.renderImmediate = function (html) {
}
THREE.Interface.prototype.renderNext = function () {
this.isRendering = true;
var clone = this.queue.shift();
document.body.appendChild(clone);
// load any <img> tags in the dom element
this.loadImages(clone, function () {
// check size changes
this.sizeChanged = (this.lastHeight !== clone.clientHeight || this.lastWidth !== clone.clientWidth);
this.lastHeight = clone.clientHeight;
this.lastWidth = clone.clientWidth;
// render!
html2canvas(clone).then(function (canvas) {
// update image src, will fire loaded event when ready
this.image.src = canvas.toDataURL();
// calculate button positions
this.getBounds(clone);
// dispose of cloned element
document.body.removeChild(clone);
clone = null;
}.bind(this));
}.bind(this));
}
THREE.Interface.prototype.onImageReady = function () {
// create or recreate plane if size changed
if (this.sizeChanged) {
this.makePlane();
}
// dispose of any previous texture
if (this.plane.material.map) {
this.plane.material.map.dispose();
}
// update plane texture
this.plane.material.map = new THREE.Texture(this.image);
this.plane.material.map.needsUpdate = true;
if (this.queue.length) {
this.renderNext();
} else {
this.isRendering = false;
}
}
THREE.Interface.prototype.makePlane = function () {
// remove and dispose of current plane (if any)
if (this.plane) {
this.remove(this.plane);
this.plane.geometry.dispose();
this.plane.material.dispose();
}
// transpose element to plane size using scaler
var width = this.scaler * this.lastWidth;
var height = this.scaler * this.lastHeight;
// create plane
// var texture = new THREE.Texture(this.image);
var geometry = new THREE.PlaneGeometry(width, height);
var material = new THREE.MeshLambertMaterial({
// texture will be updated with canvas render
// map: texture,
// enable css opacity, rgba etc
transparent: true,
// makes the interface always on top
depthTest: !this.options.alwaysOnTop
});
this.plane = new THREE.Mesh(geometry, material);
this.add(this.plane);
}
THREE.Interface.prototype.makeElement = function (html) {
// create a wrapper element (so we don't muck with user defined styles)
var elem = document.createElement('div');
elem.style.position = 'absolute';
elem.style.top = 0;
elem.style.left = 0;
elem.style.zIndex = -1;
elem.style.display = 'inline-block';
elem.style.boxSizing = 'border-box';
// handlers
if (typeof html == 'string') {
// strings get added as innerHTML
elem.innerHTML = html;
} else if (html instanceof Array) {
// arrays get concatenated and added as innerHTML
elem.innerHTML = html.join('');
} else if (html.nodeType && html.nodeType === 1) {
// actual nodes just get added as child
elem.appendChild(html);
} else {
console.error('html must be String, Array or HTMLElement');
}
// remove existing observer (if any)
if (this.observer) {
this.observer.disconnect();
}
// set up observer if option is set
if (this.options.observe === true) {
var config = { attributes: true, childList: true, characterData: true, subtree: true };
this.observer = new MutationObserver(this.onElementChange.bind(this));
this.observer.observe(elem, config);
}
return elem;
}
THREE.Interface.prototype.onElementChange = function () {
this.render();
}
THREE.Interface.prototype.loadImages = function (clone, done) {
// find all <img> elements
var images = Array.prototype.slice.call(clone.querySelectorAll('img'));
if (!images.length) return done();
// wait until they all load
var total = images.length;
var complete = 0;
for (var i=0; i < images.length; i++) {
var img = images[i];
img.addEventListener('load', function () {
complete++;
if (complete === total) done(); // done!
});
}
}
THREE.Interface.prototype.performClick = function (point) {
// convert ray point from world to local
this.plane.worldToLocal(point);
// debug shows click point
if (this.options.debug) {
var geometry = new THREE.SphereGeometry(0.05);
var material = new THREE.MeshLambertMaterial({ color: 'green' });
var box = new THREE.Mesh(geometry, material);
box.position.copy(point);
this.plane.add(box);
}
// convert point into pixel coords
var click = {
x: (point.x + (this.plane.geometry.parameters.width / 2)) / this.scaler,
y: -(point.y - (this.plane.geometry.parameters.height / 2)) / this.scaler
};
// fire any hits (if any)
for (var i=0; i < this.bounds.length; i++) {
var btn = this.bounds[i];
if (click.y >= btn.top && click.y <= btn.bottom &&
click.x >= btn.left && click.x <= btn.right) {
eval('this.methods.' + btn.onclick);
}
}
}
THREE.Interface.prototype.getBounds = function (clone) {
// get button bounds
this.bounds = [];
var elems = clone.querySelectorAll('[onclick]');
for (var i=0; i < elems.length; i++) {
var btn = elems[i];
var b = btn.getBoundingClientRect();
this.bounds.push({
top: b.top,
left: b.left,
right: b.right,
bottom: b.bottom,
width: b.width,
height: b.height,
onclick: btn.getAttribute('onclick'),
elem: btn
});
}
}
|
const fs = require('fs')
const okfind=require("./okfindandreplace.js")
startingDirectory = process.argv[2];
if (!startingDirectory) {
throw Error("A file to watch must be specified!");
}
console.log("Now Searching: " + startingDirectory + " for localization occurrences");
okfind.findAll(startingDirectory, function(error,files) {
console.log("Found " + files.length + " files")
}) |
'use strict';
const fs = require('fs'),
decamelize = require('decamelize'),
camelcase = require('camelcase'),
sequelize = require('sequelize'),
path = require('path');
/**
* Created by Adrian on 29-Mar-16.
* This component is used to load up all the sql / postgre models.
*/
module.exports = function init(thorin, Store) {
const async = thorin.util.async;
const NAME_SEPARATOR = '_';
const loader = {};
const extendModels = {}; // hash of {modelName: [fns]}}
/*
* Load up all the models.
* */
function loadModels(fpath, modelFiles) {
try {
fpath = path.normalize(fpath);
if (!fs.existsSync(fpath)) throw 1;
} catch (e) {
return false;
}
if (path.extname(fpath) === '.js') {
// we have a file.
let itemName = path.basename(fpath);
itemName = itemName.substr(0, itemName.lastIndexOf('.'));
let itemCode = decamelize(itemName);
let item = {
fullPath: fpath,
code: itemCode,
name: itemName,
path: path.basename(fpath)
};
modelFiles.push(item);
return true;
}
const items = thorin.util.readDirectory(fpath, {
ext: 'js',
relative: true
});
if (items.length === 0) {
return true;
}
for (let i = 0; i < items.length; i++) {
let itemPath = items[i];
let item = {
fullPath: path.normalize(fpath + '/' + itemPath)
};
itemPath = itemPath.substr(0, itemPath.lastIndexOf('.'));
let itemName = decamelize(itemPath, NAME_SEPARATOR);
itemName = itemName.split(path.sep).join(NAME_SEPARATOR);
item.name = itemName;
item.code = camelcase(itemName);
item.path = itemPath.split(path.sep).join('/');
modelFiles.push(item);
}
return true;
}
/*
* initialize the models and create their appropiate model instance.
* */
function initModels(seqObj, modelFiles, models, tablePrefix) {
modelFiles.forEach((item) => {
var modelFn;
try {
modelFn = require(item.fullPath);
} catch (e) {
console.error('Thorin.sql: could not require model: ' + item.fullPath + '\n', e.stack);
return;
}
if (modelFn == null) return; // we skip it
if (typeof modelFn !== 'function') {
console.error(thorin.error('SQL.INVALID_MODEL', 'SQL Model: ' + item.fullPath + ' must export a function(modelObj){}'));
return;
}
if (modelFn.name === 'extend') {
if (typeof extendModels[item.code] === 'undefined') extendModels[item.code] = [];
extendModels[item.code].push(modelFn);
return;
}
let modelObj = loader.buildModel(seqObj, modelFn, item, tablePrefix);
if (modelObj) {
if (typeof models[modelObj.code] !== 'undefined') {
console.error(thorin.error('SQL.ADD_MODEL', 'SQL Store: model ' + modelObj.code + ' was already declared.'));
return;
}
models[modelObj.code] = modelObj;
}
});
}
/*
* This will build the thorin store model object.
* */
loader.buildModel = function BuildStoreModel(seqObj, modelFn, item, tablePrefix) {
if (!item.name) {
item.name = decamelize(item.code, '_');
item.code = camelcase(item.code);
}
let modelObj = new Store.Model(item.code, item.name, item.fullPath);
modelFn(modelObj, sequelize, seqObj);
if (typeof extendModels[item.code] !== 'undefined') {
for (let i = 0; i < extendModels[item.code].length; i++) {
let extendFn = extendModels[item.code][i];
extendFn(modelObj, sequelize, seqObj);
}
delete extendModels[item.code];
}
if (!modelObj.isValid()) {
console.error(thorin.error('SQL.INVALID_MODEL', 'SQL Model: ' + (item.fullPath || item.code) + ' does not contain valid information.'));
return;
}
if (typeof tablePrefix === 'string' && tablePrefix) {
modelObj.prefix = tablePrefix;
}
return modelObj;
};
/*
* For each model, we will create its definition and attach it to sequelize.
* */
function createInstances(seqObj, models, config, done) {
Object.keys(models).forEach((key) => {
let modelObj = models[key],
attributes = {},
options = thorin.util.extend({}, modelObj.options);
modelObj.privateAttributes = [];
// map the attributes
Object.keys(modelObj.fields).forEach((fieldName) => {
let fieldOpt = modelObj.fields[fieldName];
if (modelObj.getters[fieldName]) {
fieldOpt.get = modelObj.getters[fieldName];
}
if (modelObj.setters[fieldName]) {
fieldOpt.set = modelObj.setters[fieldName];
}
if (fieldOpt.private) {
modelObj.privateAttributes.push(fieldName);
}
attributes[fieldName] = fieldOpt;
});
if (options.createdAt === true) options.createdAt = 'created_at';
if (options.updatedAt === true) {
options.updatedAt = 'updated_at';
if (!attributes[options.updatedAt]) {
attributes[options.updatedAt] = {
defaultValue: null,
allowNull: true,
type: sequelize.DATE
}
}
}
if (options.deletedAt === true) {
options.deletedAt = 'deleted_at';
if (!attributes[options.deletedAt]) {
attributes[options.deletedAt] = {
defaultValue: null,
allowNull: true,
type: sequelize.DATE
}
}
}
// create the inner options.
options.underscored = true;
options.charset = config.options.charset || 'utf8';
options.collate = config.options.collate || 'utf8_general_ci';
options.tableName = modelObj.tableName;
options.indexes = modelObj.indexes;
options.instanceMethods = modelObj.methods;
options.classMethods = modelObj.statics;
options.hooks = modelObj.hooks;
options.validate = {};
let validatorId = 0;
// set validations
modelObj.validations.forEach((item) => {
if (item.name) { // we have a field validator.
if (!attributes[item.name]) {
console.warn('Thorin.sql: model ' + key + " does not have field " + item.name + ' for validator.');
return;
}
if (!attributes[item.name].validate) attributes[item.name].validate = {};
attributes[item.name].validate['validate' + item.name + validatorId] = item.fn;
validatorId++;
return;
}
// we have a model validator.
options.validate['thorinValidate' + validatorId] = item.fn;
validatorId++;
});
// wrap the toJSON function to exclude private fields.
function ToJSON(jsonName) {
if (jsonName === 'result') jsonName = 'default';
let args = Array.prototype.slice.call(arguments);
if (typeof jsonName === 'undefined') {
jsonName = 'default';
} else if (typeof jsonName === 'string') {
args.splice(0, 1); //remove the name.
}
let jsonFn = modelObj.jsons[jsonName],
result = this.dataValues;
if (typeof jsonFn === 'undefined' && jsonName !== 'default') { // silent fallback
if (typeof modelObj.jsons['default'] === 'function') {
result = modelObj.jsons['default'].apply(this, args);
}
} else {
if (typeof modelObj.jsons[jsonName] === 'function') {
result = modelObj.jsons[jsonName].apply(this, args);
} else {
result = this.dataValues;
}
}
if (result === this) {
result = this.dataValues;
}
if (typeof result === 'object' && result != null) {
for (let i = 0; i < modelObj.privateAttributes.length; i++) {
if (typeof result[modelObj.privateAttributes[i]] !== 'undefined') {
delete result[modelObj.privateAttributes[i]];
}
}
}
return result;
}
options.instanceMethods['toJSON'] = ToJSON;
// we do a synonym to .json()
options.instanceMethods['json'] = ToJSON;
// Check model prefix
if (typeof modelObj.prefix === 'string' && typeof options.tableName === 'string') {
options.tableName = modelObj.prefix + options.tableName;
}
var modelInstance;
try {
modelInstance = seqObj.define(modelObj.code, attributes, options);
} catch (e) {
console.error('Thorin.sql: could not create sequelize schema for: ' + modelObj.code + '\n', e.stack);
return;
}
if (typeof attributes['id'] === 'undefined') {
if (modelObj.options.primaryKey === false) {
modelInstance.removeAttribute('id');
}
}
modelObj.setInstance(modelInstance);
});
done();
}
/*
* Creates the associations between models.
* */
function createAssociations(models, done) {
Object.keys(models).forEach((key) => {
let modelObj = models[key],
instanceObj = modelObj.getInstance();
modelObj.relations.forEach((relation) => {
let targetModel = models[relation.name];
if (!targetModel) {
throw thorin.error('SQL.INVALID_ASSOCIATION', 'Target association: ' + relation.type + " " + relation.name + ' does not exist for ' + modelObj.code);
}
let targetInstanceObj = targetModel.getInstance();
let opt = thorin.util.extend(getAssociationOptions(targetModel.tableName, relation.options, modelObj), {
as: targetModel.code
}, relation.options);
relation.options = opt;
if (opt.private) {
modelObj.privateAttributes.push(opt.foreignKey.name);
}
try {
instanceObj[relation.type](targetInstanceObj, opt);
} catch (e) {
console.error('Thorin.sql: could not create sequelize association: %s %s %s', modelObj.code, relation.type, targetModel.code, e.stack);
}
});
});
done();
}
/*
* Initialize the loader and load some models for preparation.
* */
loader.load = function LoadModels(storeObj, modelPath, models, tablePrefix) {
/* step one: load and parse their info. */
let files = [];
loadModels(modelPath, files);
initModels(storeObj.getInstance(), files, models, tablePrefix);
};
/*
* Initializes the loader.
* */
loader.finalizeLoading = function initialize(storeObj, config, models, onDone) {
var calls = [],
seqObj = storeObj.getInstance();
/* step three: create the models. */
calls.push((done) => {
createInstances(seqObj, models, config, done);
});
/* step 4: create associations */
calls.push((done) => {
createAssociations(models, done);
});
/* next, */
async.series(calls, (err) => {
if (err) return onDone(err);
onDone();
});
};
/* PRIVATE */
function getAssociationOptions(name, opt, modelObj) {
let options = {
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
};
if (typeof opt.constraints !== 'boolean') {
options.constraints = true;
}
let primaryObj = modelObj.getPrimary(),
fk = (primaryObj ? primaryObj.name : 'id');
fk = fk.charAt(0).toUpperCase() + fk.substr(1);
let canBeNull = (typeof opt['allowNull'] === 'boolean' ? opt['allowNull'] : true);
if (!opt.foreignKey) {
options.foreignKey = {
name: decamelize((opt.as || name) + fk, '_'),
allowNull: canBeNull
};
} else if (typeof opt.foreignKey === 'string') {
options.foreignKey = {
name: options.foreignKey,
allowNull: canBeNull
};
}
return options;
}
return loader;
};
|
const services = (function (fetch, URL, BASE_URL) {
const prepareQuery = function (url, params) {
const urlObject = new URL(url);
Object.keys(params)
.filter(x => !!params[x])
.forEach(key => urlObject.searchParams.append(key, params[key]));
return urlObject;
};
return {
async getNearByGasStations(lat, lon, limit = 10, distance = 10, fuel = 'lpg') {
const query = prepareQuery(`${BASE_URL}/rest/fuel-near-me`, { lat, lon, limit, distance, fuel });
const rawResult = await fetch(query);
return await rawResult.json();
}
}
}(window.fetch, window.URL, window.location.origin)); |
/**
* Created by reamd on 2016/2/25.
*/
describe("msgBox", function() {
var should = chai.should();
it("should is a object", function() {
var msgbox = new msgBox({});
msgbox.should.be.a('object');
});
it("check it property", function() {
var msgbox = new msgBox({});
msgbox.should.have.property('width').with.equal('');
msgbox.should.have.property('minWidth').with.equal('0');
msgbox.should.have.property('maxWidth').with.equal('100%');
msgbox.should.have.property('height').with.equal('');
msgbox.should.have.property('title').with.equal('');
msgbox.should.have.property('body').with.equal('');
msgbox.should.have.property('btnLabel').with.a('array').with.length(0);
msgbox.should.have.property('visible').with.equal(true);
msgbox.should.have.property('isClose').with.equal(true);
msgbox.should.have.property('openMsg').with.a('function');
msgbox.should.have.property('closeMsg').with.a('function');
msgbox.should.have.property('complete').with.a('function');
msgbox.should.have.property('firstCallback').with.a('function');
msgbox.should.have.property('secondCallback').with.a('function');
});
}); |
ngGridDirectives.directive('ngCell', ['$compile', '$domUtilityService', '$utilityService', function ($compile, domUtilityService, utilityService) {
var ngCell = {
scope: false,
compile: function() {
return {
pre: function($scope, iElement) {
var html;
var cellTemplate = $scope.col.cellTemplate.replace(COL_FIELD, utilityService.preEval('row.entity.' + $scope.col.field) );
if ($scope.col.enableCellEdit) {
html = $scope.col.cellEditTemplate;
html = html.replace(CELL_EDITABLE_CONDITION, $scope.col.cellEditableCondition);
html = html.replace(DISPLAY_CELL_TEMPLATE, cellTemplate);
html = html.replace(EDITABLE_CELL_TEMPLATE, $scope.col.editableCellTemplate.replace(COL_FIELD, utilityService.preEval('row.entity.' + $scope.col.field)));
} else {
html = cellTemplate;
}
var cellElement = $(html);
iElement.append(cellElement);
$compile(cellElement)($scope);
if ($scope.enableCellSelection && cellElement[0].className.indexOf('ngSelectionCell') === -1) {
cellElement[0].setAttribute('tabindex', 0);
cellElement.addClass('ngCellElement');
}
},
post: function($scope, iElement) {
if ($scope.enableCellSelection) {
$scope.domAccessProvider.selectionHandlers($scope, iElement);
}
$scope.$on('$destroy', $scope.$on('ngGridEventDigestCell', function() {
domUtilityService.digest($scope);
}));
}
};
}
};
return ngCell;
}]); |
//--------------------------------------------------------------------------
// サウンドテストシーン
//--------------------------------------------------------------------------
(function(){
//--------------------------------------------------------------------------
// メソッド
//--------------------------------------------------------------------------
// コンストラクタ
SoundTestScene = function()
{
this.debugMenu; // デバッグメニュー
this.sound; // サウンド
SceneBase.call(this);
}
// 初期化
SoundTestScene.prototype.Initialize = function()
{
// サウンド読み込み
var soundManager = SoundManager.GetInstance();
this.sound = soundManager.Load("resources/sound/se/crrect_answer3.mp3");
// デバッグメニューセットアップ
var this_ = this;
this.debugMenu = new DebugMenu();
this.debugMenu.SetTitle(this.GetSceneName());
this.debugMenu.AddMenu("Play", function(index){ this_.OnPlay(); });
this.debugMenu.AddMenu("Stop", function(index){ this_.OnStop(); });
this.debugMenu.AddMenu("Pause", function(index){ this_.OnPause(); });
this.debugMenu.AddMenu("Resume", function(index){ this_.OnResume(); });
this.debugMenu.SetBack("DebugMenu");
return true;
}
// 終了
SoundTestScene.prototype.Finalize = function()
{
// サウンド解放
var soundManager = SoundManager.GetInstance();
soundManager.Release(this.sound);
this.sound = null;
}
// 更新
SoundTestScene.prototype.Update = function(deltaTime)
{
this.debugMenu.Update();
}
// 描画
SoundTestScene.prototype.Draw = function()
{
this.debugMenu.Draw();
}
// 再生通知
SoundTestScene.prototype.OnPlay = function()
{
this.sound.Play();
}
// 停止通知
SoundTestScene.prototype.OnStop = function()
{
this.sound.Stop();
}
// 中断通知
SoundTestScene.prototype.OnPause = function()
{
this.sound.Pause();
}
// 再開通知
SoundTestScene.prototype.OnResume = function()
{
this.sound.Resume();
}
//--------------------------------------------------------------------------
// 継承
//--------------------------------------------------------------------------
Object.setPrototypeOf(SoundTestScene.prototype, SceneBase.prototype);
})();
|
import EmberRouter from '@ember/routing/router';
import config from './config/environment';
export default class Router extends EmberRouter {
location = config.locationType;
rootURL = config.rootURL;
}
Router.map(function() {
this.route('first-route');
this.route('second-route');
this.route('third-route');
});
|
const express = require('express');
const app = express();
const aws = require('aws-sdk');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const getErrorHandler = require('./error-handlers/error-handler');
const ensureAuth = require('./auth/ensure-auth')();
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(express.static('./public'));
const auth = require('./routes/auth');
const posts = require('./routes/posts');
const me = require('./routes/me');
app.use('/api/auth', auth);
app.use('/api/posts', ensureAuth, posts);
app.use('/api/me', ensureAuth, me);
app.use(getErrorHandler());
const S3_BUCKET = process.env.S3_BUCKET_NAME;
app.get('/sign-s3', (req, res) => {
const s3 = new aws.S3();
const fileName = req.query['file-name'];
const fileType = req.query['file-type'];
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if(err){
console.log(err);
return res.end();
}
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
res.write(JSON.stringify(returnData));
res.end();
});
});
module.exports = app; |
'use strict'
var thunks = require('..')
var thunk = thunks()
thunk()(function () {
throw new Error('111111')
})
|
var O_DELETE_CONFIRM = "Delete Confirmation";
var O_DELETE_CONFIRM_DESC = "Please confirm that you would like to delete the selected items";
var O_LATEST_SIGNATURE = "<div class='signatureInfo'>Latest signature version (major update): 20140901, updated on 1st Sep 2014</div>";
var O_DOWNLOAD_FILES = "Downloading files";
var O_DOWNLOAD_TERMINATED = "Downloading terminates";
var O_APIKEY = "API key";
var O_BLACKLIST_IP = "Blacklist IPs";
var O_WHITELIST_IP = "Whitelist IPs";
var O_MONITORLIST_IP = "Monitor IPs";
var O_BLACKLIST_CONFIRM = "Blacklist_IPs_confirmation";
var O_BLACKLIST_CONFIRM_DESC = "Please confirm that you would like to blacklist the selected items";
var O_WHITELIST_CONFIRM = "Whitelist IPs confirmation";
var O_WHITELIST_CONFIRM_DESC = "Please confirm that you would like to whitelist the selected items";
var O_MONILIST_CONFIRM = "Monitored IPs confirmation";
var O_MONILIST_CONFIRM_DESC = "Please confirm that you would like to monitor the selected items";
var O_UPDATE_HOST = "Update Host";
var O_UPDATE_HOST_CONFIRM = "Update Host confirmation";
var O_UPDATE_HOST_CONFIRM_DESC = "Please confirm that you would like to updatehost the selected items";
var O_FILTER = "Filter";
var O_IMPACT = "Impact";
var O_DESCRIPTION = "Description";
var O_ATTACKTYPE = "Attack Type";
var O_RULE = "Rule";
var O_FILTER = "Filter";
var O_CHANGE_IP_STATUS= "Change IP Status";
var O_CHANGE_IP_STATUS_DESC= "This will change the access control rules for this IP/IP range. Are you sure you want to change the status?";
var O_CHANGE_VAR_STATUS = "Change Variables Status";
var O_CHANGE_VAR_STATUS_DESC = "This will change the access control rules for this variables. Are you sure you want to change the status?";
var O_CHANGE_FIREWALL_STATUS = "Change Firewall Status";
var O_CHANGE_FIREWALL_STATUS_DESC = "This will change the access control rules for firewall. Are you sure you want to change the status?";
var O_ANTI_HACKING_SCANNING_OPTIONS = "<b>Anti-Hacking Scanning Options</b>";
var O_SECRET_WORD = "Secret Word";
var O_SECRET_WORD_DESC = "Secret Word, please note this down. The secret word allows you to get in OSE Suite when you are blocked.";
var O_DEVELOPMENT_MODE = "Development Mode";
var O_FRONTEND_BLOCKING_MODE = "Frontend Blocking Mode";
var O_ENABLE_SFSPAM = "Enable Stop Forum Spam";
var O_SFS_CONFIDENCE_LEVEL = "Stop Forum Spam Confidence Level (between 1 and 100)";
var O_EDIT_EMAIL_TEMP = "Edit email template";
var O_EDIT = "Edit";
var O_EMAIL_TYPE = "Email Type";
var O_EMAIL_SUBJECT = "Email Subject";
var O_EMAIL_BODY = "Email Body";
var O_USER = "User";
var O_USER_ID = "User ID";
var O_EMAIL = "Email";
var O_ADD_A_LINK = "Add a linkage";
var O_SCANNED_FILE_EXTENSIONS_DESC = "Only the following file extensions have been tested and supported by OSE Anti-Virus, if you broke the system after changing the file extension field, please revert the file extension value to the following: <br/> <b>htm,html,shtm,shtml,css,js,php,php3,php4,php5,inc,phtml,jpg,jpeg,gif,png,bmp,c,sh,pl,perl,cgi,txt</b>";
var O_UPDATE_VERSION_DESC = "This will update local anti-virus database";
var O_CLAMAV_DESC = "To use ClamAV Anti-Virus, please ensure you have installed ClamAV or consult your hosting company on whether ClamAV is installed. If you have a dedicated server, please see this <a href = ' http://www.centrora.com/blog/install-free-antivirus-clamav-on-linux/' target='_blank'>tutorial</a> on how to install ClamAV. Once installed, please see <a href='http://www.centrora.com/blog/free-antivirus-for-wordpress/' target = '_blank'>this tutorial</a> to enable ClamAV scanning in Centrora Security.";
var O_CLAMAV_SOCKET_LOCATION = "Clam AV Socket path (if installed) ";
var O_DO_NOT_SCAN_BIGGER_THAN = "Do not scan files bigger than (unit: MB)";
var O_ENABLE_CLAMAV_SCANNING = "Enable ClamAV Scanning";
var O_PLEASE_ENTER_A_PATH = "Please enter a path for scanning";
var O_SCAN_PATH = "Scanning Path";
var O_INIT_DATABASE = "Initialize Database";
var O_STOP = "Stop" ;
var O_SCAN_VIRUS = "Scan Viruses";
var O_VIRUS_SCANNING = "Viruses Scanning";
var O_SCAN_VIRUS_CONTINUE = "Continue Scan";
var VIRUS_SCANNING_IN_PROGRESS = "Virus Scanning In Progress";
var DB_INITIALIZATION_IN_PROGRESS = "Database Initialization In Progress";
var O_FILE_ID = "File ID";
var O_FILE_NAME = "File Name";
var O_CONFIDENCE = "Confidence";
var O_LOAD_DATA_CONFIRMATION = "Load data confirmation";
var O_LOAD_DATA_CONFIRMATION_DESC = "Please confirm that you would like to load the Wordpress whitelisted variable rules";
var ADD_A_VARIABLE = "Add a Variable";
var O_VARIABLE_NAME = "Variable Name";
var O_VARIABLES = "Variables";
var LOAD_WORDPRESS_DATA = "Load WordPress default variables";
var LOAD_WORDPRESS_CONFIRMATION = "Please confirm that you would like to load the Wordpress whitelisted variable rules";
var O_CLEAR_DATA = "Clear Data";
var O_CLEAR_DATA_CONFIRMATION = "Clear Data Confirmation";
var O_CLEAR_DATA_CONFIRMATION_DESC = "Please confirm that you would like to clear all variables, it will remove some other hacking information related to this rule";
var O_STATUS_EXP = "Status Explanation";
var O_CLOSE = "Close";
var O_INITDB_COMPLETED = "Database Initialization Completed";
var O_INITDB_INPROGRESS = "Database Initialization In Progress";
var O_INITDB_TERMINATED = "Database Initialization Terminated";
var O_VSSCAN_INPROGRESS = "Virus Scanning In Progress";
var O_VSSCAN_COMPLETED = "Virus Scanning Completed";
var O_VSSCAN_TERMINATED = "Virus Scanning In Terminated";
var O_PLS_ENTER_ADMIN_EMAIL = "Please enter an administrator email in the SEO section";
var O_PLEASE_WAIT = "Please wait, this will take a few seconds ...";
var O_PLS_ENTER_ADMIN_EMAIL_LONG = "Please edit your custom ban page and meta keywords and descriptions here. These will help you maintain Search Engine Ranking when OSE blocks search engine bots by mistake.";
var O_CONF_UPDATE_SUCCESS = "Configuration is updated successfully.";
var O_SUCCESS = "Success"
var O_SHOW_OSEFIREWALL_BADGE = "Show OSE Firewall Badge";
var O_BADGE_CSS_STYLE = "Badge CSS style";
var O_SUBSCRIPTION_USERNAME = "Name";
var O_SUBSCRIPTION_PASSWORD = "Password";
var O_PLS_ENTER_USERINFO = "Please enter your username/password";
// Added from 2.1.4
var O_DEBUG_MODE = "Detect errors in the website?";
// Added from 2.3.0
var O_SERVER_BACKUP_TYPE ="Backup Server";
var O_BACKUP_TYPE ="Backup Type";
var O_BACKUP_TO = "Backup To:";
var O_FILE_SIZE = "File Size";
var O_BACKUP = "Backup";
var O_BACKUP_PREFIX = "Backup File Prefix";
var O_FILE_BACKUP = "File Backup";
var O_IMPACT = "Impact";
var O_GOOGLE_2_VERIFICATION = "Google 2-Step Verification";
var O_SOCIAL_BOARD1 = "Like us? Tell your friend about us";
var O_SOCIAL_BOARD2 = "Visit & Like us";
var O_ADRULESETS = "Advanced Firewall Setting (See <a href ='http://www.centrora.com/centrora-tutorial/enabling-advance-firewall-setting/' target='_blank'>Tutorial Here</a>)";
var O_ADVS_PATTERNS = "Advanced Virus Patterns (<a href = 'http://www.centrora.com/centrora-premium/' target='_blank'>Premium Only</a>)";
var O_SOCIAL_SHARE = "Protect your website better? Choose Centrora";
var O_CONTINUE = "Continue";
var O_CONTINUE_SCAN = "Continue Scanning";
var O_BACKUP_FILE_COMPLETE = "BackUp files complete";
var O_UNINSTALL_TITLE = "Uninstall Centrora Security";
var O_UNINSTALL_CONFIRM = "Are you sure you want to uninstall Centrora Security?";
var O_NEWUSERNAME = "New username";
var O_NEWUSERNAME_NOTE = "Please mark down the new username for the administrator account as once it is changed, you will need to use the new user account to login in the future.";
var O_BLACKLIST_COUNTRY = "Blacklist Country";
var O_WHITELIST_COUNTRY = "Whitelist Country";
var DOWNLOAD_COUNTRY = "Download Country Database";
var O_SCAN_CLAMAV = "Scan files with <a href ='http://www.clamav.net' target = '_blank'>ClamAV</a>";
var CLAMAV_ACTIVATION_METHOD = "ClamAV Activation Method";
var CLAMAV_SOCKET_LOCATION = "Clam AV Socket path (if installed)";
var O_PATTERNS = "Patterns";
var O_PATTERN_ID = "Pattern ID";
var O_GET_RULES = "Retrieve Updated Advance Firewall Rules";
var LOAD_JOOMLA_DATA = "Load Joomla default variables";
var LOAD_JSOCIAL_DATA = "Load JomSocial default variables";
var LOAD_JOOMLA_CONFIRMATION = "Please confirm that you would like to load the Joomla whitelisted variable rules";
var O_MONITOR_COUNTRY = "Monitor Country";
var AUDIT_FREQ = "Audit Report Schedule";
var ATTACK_BLOCKING_THRESHOLD = "Attack blocking risk score threshold (default: 35)";
var O_SILENTLY_FILTER_ATTACK = "Silent Mode (Silently filter hacking values. Recommended for new users)";
var O_ADV_ANTI_HACKING_SCANNING_OPTIONS = "<b>Centrora Premium Service Options</b>";
var SILENT_MODE_BLOCK_MAX_ATTEMPTS = "Maximum attack attempts allowed for an IP in silent mode (default: 10)"
var O_SCHEDULE_AUDITING = "<b>Schedule Auditing Options</b>";
var O_CHANGEALL_COUNTRY = "Change All Countries";
var O_CHANGEALL_COUNTRY_STATUS = "What status would you like to change all countries to?";
var O_SYSTEM_FINETUNING = "<b>System Fine Tuning</b>";
var O_DISABLE_REGISTER_GLOBAL = "Disable PHP register_global directive";
var O_DISABLE_SAFE_MODE = "Disable PHP safe_mode directive";
var O_DISABLE_ALLOW_URL_FOPEN = "Disable PHP allow_url_fopen directive";
var O_DISABLE_DISPLAY_ERRORS = "Disable PHP display_errors directive";
var O_DISABLE_PHP_FUNCTIONS = "Disable PHP system functions";
var O_UPDATE_PATTERN = "Update virus patterns";
var O_SCHEDULE_VSSCAN = "Schedule Virus Scanning"
var O_IMPORT_IP_CSV = "Import IP from CSV";
var O_EXPORT_IP_CSV = "Export IP to CSV";
var O_EXPORT_IP_CONFIRM = "Export IP to CSV confirmation";
var O_EXPORT_IP_CONFIRM_DESC = "Please confirm that you would like to export all IP from the database";
var O_SCANNED_PATH = "Scanning Path";
var O_SCAN_SPECIFIC_FOLDER = "Scan specific folder";
var O_START_SCANNING = "Start scanning";
var O_BACKUP_DROPBOX = "Dropbox API Setting"; |
(function() {
var syncLoad = function(url) {
document.write('<' + 'script src="' + url + '">' + '<' + '/script>');
}
var scripts = document.getElementsByTagName('script');
var curScript = scripts[scripts.length - 1];
window.curMain = curScript.getAttribute('data-main')
var curURLParts = window.location.pathname.split('/');
while (curURLParts.pop() != 'tests-requirejs');
var testPath = curURLParts.join('/');
while (curURLParts.pop() != 'test');
var basePath = curURLParts.join('/');
curURLParts.pop();
var deepBasePath = curURLParts.join('/');
// load the es6 polyfill synchronously
syncLoad(deepBasePath + '/es6-module-loader/lib/es6-module-loader.js');
// then load jspm synchronously
syncLoad(basePath + '/loader.js');
// then wrap a dummy requirejs
syncLoad(testPath + '/requirejs-wrapper.js');
})(); |
/* eslint-disable max-lines */
const pkg = require( "../package.json" );
const buildUrl = account => {
let url = "";
if ( account.indexOf( "http://" ) !== 0 && account.indexOf( "https://" ) !== 0 ) {
url = `https://${ account }`;
// Assume leankit.com if no domain is specified
if ( account.indexOf( "." ) === -1 ) {
url += ".leankit.com";
}
} else {
url = account;
}
if ( url.indexOf( "/", account.length - 1 ) !== 0 ) {
url += "/";
}
return url;
};
const getUserAgent = () => {
return `leankit-node-client/${ pkg.version }`;
};
const getPropertyValue = ( obj, prop, def = null ) => {
for ( const k in obj ) {
if ( k.toLowerCase() === prop.toLowerCase() ) {
return obj[ k ];
}
}
return def;
};
const removeProperties = ( obj, props ) => {
for ( let i = 0; i < props.length; i++ ) {
for ( const k in obj ) {
if ( k.toLowerCase() === props[ i ].toLowerCase() ) {
delete obj[ k ];
}
}
}
};
const buildDefaultConfig = ( account, token, email, password, config ) => {
config = config || { headers: {} };
if ( !config.headers ) {
config.headers = {};
}
const userAgent = getPropertyValue( config.headers, "User-Agent", getUserAgent() );
removeProperties( config.headers, [ "User-Agent", "Content-Type", "Accept" ] );
const proxy = config.proxy || null;
const defaultHeaders = {
Accept: "application/json",
"Content-Type": "application/json",
"User-Agent": userAgent
};
const headers = Object.assign( {}, config.headers, defaultHeaders );
const auth = token ? { bearer: token } : { username: email, password };
const defaults = {
auth,
baseUrl: buildUrl( account ),
headers
};
if ( proxy ) {
defaults.proxy = proxy;
}
return defaults;
};
const checkLegacyPath = urlPath => {
return ( urlPath.startsWith( "api/" ) ) ? urlPath : `kanban/api/${ urlPath }`;
};
const mergeOptions = ( options, defaults ) => {
if ( options.headers ) {
options.headers.Accept = defaults.headers.Accept;
options.headers[ "User-Agent" ] = defaults.headers[ "User-Agent" ];
}
const config = Object.assign( {}, defaults, options );
if ( config.data ) {
if ( config.headers[ "Content-Type" ] === "application/json" ) {
config.body = JSON.stringify( config.data );
} else {
config.body = config.data;
}
delete config.data;
}
return config;
};
const parseBody = body => {
let parsed;
if ( typeof body === "string" && body !== "" ) {
try {
parsed = JSON.parse( body );
} catch ( e ) {
parsed = body;
}
} else {
parsed = body;
}
return parsed;
};
const streamResponse = ( request, cfg, stream ) => {
return new Promise( ( resolve, reject ) => {
const response = {};
request( cfg )
.on( "error", err => {
return reject( err );
} )
.on( "response", res => {
response.status = res.statusCode;
response.statusText = res.statusMessage;
response.data = "";
} )
.on( "end", () => {
if ( response.status < 200 || response.status >= 300 ) { // eslint-disable-line no-magic-numbers
return reject( response );
}
return resolve( response );
} )
.pipe( stream );
} );
};
const status = {
status200: 200,
status201: 201,
status300: 300
};
module.exports = {
buildUrl,
buildDefaultConfig,
getUserAgent,
getPropertyValue,
removeProperties,
checkLegacyPath,
parseBody,
streamResponse,
mergeOptions,
status
};
|
import { Map, Set, OrderedSet } from 'immutable';
export function removeFromSpace(state, sid, space) {
return state.updateIn(['sources', sid, 'spaces'],
(spaces = new OrderedSet()) => spaces.delete(space))
.updateIn(['spaces', space, 'sources'],
(sources = new Set()) => sources.delete(sid));
}
function updateSourceSpaces(state, sid, url) {
const oldurl = state.getIn(['sources', sid, 'url']) || url;
const spaces = (state.getIn(['sources', sid, 'spaces']) ||
new OrderedSet()).add(oldurl).add(url).delete(url);
switch (spaces.size) {
case 5:
return removeFromSpace(state.updateIn(['sources', sid],
(source = new Map()) =>
source.set('url', url).set('spaces', spaces)),
sid, spaces.first());
default:
return state.updateIn(['sources', sid],
(source = new Map()) =>
source.set('url', url).set('spaces', spaces));
}
}
export function addToSpace(state, sid, url) {
return updateSourceSpaces(state, sid, url)
.updateIn(['spaces', url, 'sources'],
(sources = new Set()) => sources.add(sid));
}
|
const config = require('../config');
class Bot {
checkDate(date, diff = 10800000) {
const now = new Date().valueOf();
const dateOf = new Date(date).valueOf();
return now - dateOf < diff;
}
isAdmin(id) {
return id === config.adminId;
}
async sendMessageWithDelay(api, message, chat_id) {
const action = !chat_id ? {
action: 'typing'
} : {
action: 'typing',
chat_id
};
let delay = 0;
if (message.text) {
const typeSpeed = 60/800;
if (message.text.length > 45) {
delay = 25*typeSpeed;
} else {
delay = message.text.length * typeSpeed;
}
}
await api.sendChatAction(action);
setTimeout(async () => {
await api.sendMessage(message);
}, delay * 1000)
}
}
module.exports = Bot;
|
{
data: (function() {
var ro = {};
ro.partname = 'Boozembly 2016 - final';
ro.prewarm = true;
ro.partlength = 27826;
ro.cameras = {
'pehucam': new THREE.PerspectiveCamera(45, global_engine.getAspectRatio(), 0.1, 10000)
};
ro.scenes = {};
ro.lights = {};
ro.objects = {};
ro.effects = {};
ro.composers = {};
ro.passes = {};
ro.rendertargets = {};
ro.renderpasses = {};
ro.scenes['pehu'] = (function(obj) {
var scene = new THREE.Scene();
var geometry = new THREE.PlaneBufferGeometry(1920 * 2, 1080 * 2, 10, 10);
var material = new THREE.MeshBasicMaterial({ color: 0xffffff });
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 0, 0);
scene.add(mesh);
geometry = new THREE.PlaneBufferGeometry(2048, 1024, 10, 10);
material = new THREE.MeshBasicMaterial({ color: 0xffffff, map: THREE.ImageUtils.loadTexture( image_pehu.src ), transparent: true });
mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 0, 500);
scene.add(mesh);
var directionallight = new THREE.DirectionalLight(0xffffff, 1);
directionallight.position.set(0, 0, 1);
scene.add(directionallight);
obj.lights['pehudirectional'] = directionallight;
scene.add(obj.cameras['pehucam']);
obj.cameras['pehucam'].position.z = 2000;
/* Fade to white -mesh */
var whitegeometry = new THREE.PlaneBufferGeometry(1920 * 2, 1080 * 2, 1, 1);
var whitematerial = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true });
var whitemesh = new THREE.Mesh(whitegeometry, whitematerial);
whitemesh.position.set(0, 0, 700);
whitemesh.material.opacity = 0.0;
scene.add(whitemesh);
obj.objects['whitemesh'] = whitemesh;
/**/
var rendertarget = new THREE.WebGLRenderTarget( global_engine.getWidth(), global_engine.getHeight(),
{ minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, alpha: true, autoClear: false});
var composer = new THREE.EffectComposer(global_engine.renderers['main'], rendertarget);
var renderpass = new THREE.RenderPass(scene, obj.cameras['pehucam']);
renderpass.renderToScreen = false;
composer.addPass(renderpass);
obj.composers['pehu'] = composer;
obj.rendertargets['pehu'] = rendertarget;
return scene;
}(ro));
ro.scenes['composer'] = (function(obj) {
var scene = new THREE.Scene();
var rendertarget = new THREE.WebGLRenderTarget(global_engine.getWidth(), global_engine.getHeight(),
{ minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, alpha: true, autoClear: false }
);
var composer = new THREE.EffectComposer(global_engine.renderers['main'], rendertarget);
var combinerpass = new THREE.ShaderPass(THREE.CopyAlphaTexture);
combinerpass.uniforms['tDiffuse1'].value = obj.composers['pehu'].renderTarget1.texture;
combinerpass.uniforms['tDiffuse2'].value = obj.composers['pehu'].renderTarget2.texture;
combinerpass.renderToScreen = true;
composer.addPass(combinerpass);
obj.rendertargets['maintarget'] = rendertarget;
obj.composers['composer'] = composer;
return scene;
}(ro));
ro.functions = {
updatePehu: function(pd, pt, gt) {
var whitemesh = pd.data.objects['whitemesh'];
if (pt < 8000) {
var fade = 1 - (pt / 8000)
whitemesh.material.opacity = fade;
whitemesh.material.color.setHex(0xffffff);
whitemesh.visible = true;
} else if (pt + 2000 > pd.data.partlength) {
var fade = 1 - (pd.data.partlength - pt) / 2000;
whitemesh.material.opacity = fade;
whitemesh.material.color.setHex(0x000000);
whitemesh.visible = true;
} else {
whitemesh.material.opacity = 0;
whitemesh.visible = false;
whitemesh.material.color.setHex(0xffffff);
}
}
}
ro.player = function(partdata, parttick, tick) {
this.functions.updatePehu(partdata, parttick, tick);
var dt = global_engine.clock.getDelta();
this.composers['pehu'].render(dt);
this.composers['composer'].render(dt);
}
return ro;
}())
}
|
define(["jquery", "suspend"], function($) {
$(".ico-btn").hover(
/** handlerin */
function(e) {
var $el = $(this);
$el.removeClass("jelly-animation-out").addClass("jelly-animation");
},
function(e) {
var $el = $(this);
$el.removeClass("jelly-animation").addClass("jelly-animation-out");
}
);
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.