code
stringlengths 2
1.05M
|
|---|
/*global js_beautify: true */
/*jshint node:true */
var SanityTest = require('./sanitytest'),
Urlencoded = require('../unpackers/urlencode_unpacker'),
js_beautify = require('../beautify').js_beautify,
run_beautifier_tests = require('./beautify-tests').run_beautifier_tests;
function node_beautifier_tests() {
var results = run_beautifier_tests(new SanityTest(), Urlencoded, js_beautify);
console.log(results.results_raw());
return results;
}
if (require.main === module) {
process.exit(node_beautifier_tests().get_exitcode());
}
exports.node_beautifier_tests = node_beautifier_tests;
|
var jsonfile = require('jsonfile');
var logger = require('../logger.js');
var middleware = require('swagger-express-middleware');
var recursive = require('recursive-readdir');
var DataStoreLoader = {};
module.exports = DataStoreLoader;
DataStoreLoader.load = function(myDB, baseDir) {
// Filter function
var ignoreFunc = function(file, stats) {
return stats.isFile() && !file.endsWith('.json');
};
// Scan through the /db directory for all *.json files and add them into the custom data store
recursive(baseDir, [ignoreFunc], function(err, files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var path = file.slice(baseDir.length, file.length - 5).replace(/\\/g, '/');
var data = jsonfile.readFileSync(file, 'utf8');
logger.debug(`Loading file: ${file}, and configured path to: ${path}`);
myDB.save(new middleware.Resource(path, data));
}
});
}
|
const React = require('react')
const ReactDOM = require('react-dom')
const App = require('./App')
ReactDOM.hydrate(React.createElement(App), document.getElementById('root'))
|
const onUpdatedProfileInfoSubscriptionsStub = [
{
type: 'email',
topic: 'News',
isSubscribed: true
},
{
type: 'email',
topic: 'Offers',
isSubscribed: false
},
{
type: 'sms',
isSubscribed: true
}
]
const onUpdatedProfileInfoStub = {
operation: 'UpdateProfile',
data: {
customer: {
authenticationTicket: 'xxxxx',
ids: {
bitrixId: 'user123'
},
firstName: 'John',
lastName: 'Dow',
email: 'test@driveback.ru',
mobilePhone: '79374134389',
customFields: {
source: 'Driveback',
city: 'Moscow',
b2b: true,
childrenNames: [
'Helen',
'Bob'
]
},
subscriptions: [
{
pointOfContact: 'Email',
topic: 'News',
isSubscribed: true
},
{
pointOfContact: 'Email',
topic: 'Offers',
isSubscribed: false
},
{
pointOfContact: 'Sms',
isSubscribed: true
}
]
}
}
}
export { onUpdatedProfileInfoSubscriptionsStub, onUpdatedProfileInfoStub }
|
'use strict';
var crayon = require('@ccheever/crayon');
function log() {
var prefix = crayon.gray('[') + crayon.gray('exp') + crayon.gray(']');
var args = [prefix].concat(Array.prototype.slice.call(arguments, 0));
console.error.apply(console, args);
}
log.error = function error() {
var prefix = crayon.red('[') + crayon.gray('exp') + crayon.red(']') + crayon.red.bold(' Error:');
var args = [prefix].concat(Array.prototype.slice.call(arguments, 0).map(function (x) {
return crayon.red(x);
}));
console.error.apply(console, args);
};
log.warn = function warn() {
var prefix = crayon.yellow('[') + crayon.gray('exp') + crayon.yellow(']');
var args = [prefix].concat(Array.prototype.slice.call(arguments, 0).map(function (x) {
return crayon.yellow(x);
}));
console.warn.apply(console, args);
};
log.gray = function () {
var prefix = '[exp]';
var args = [prefix].concat(Array.prototype.slice.call(arguments, 0));
crayon.gray.error.apply(crayon, args);
};
log.crayon = crayon;
module.exports = log;
//# sourceMappingURL=sourcemaps/log.js.map
|
var Bob = function() {
var isShouting = function(input) {
return input.toUpperCase() === input && input.toLowerCase() !== input;
};
var isQuestion = function(input) {
return input.charAt(input.length - 1) === '?';
};
var isSilent = function(input) {
return /^\s*$/.test(input);
};
this.hey = function(input) {
if (isSilent(input)) {
return 'Fine. Be that way!';
}
if (isShouting(input)) {
return 'Whoa, chill out!';
}
if (isQuestion(input)) {
return 'Sure.';
}
return 'Whatever.';
};
};
module.exports = Bob;
|
'use strict';
define(function () {
return function () {
return {
firebase : {
url : 'https://xxx.firebaseio.com/'
},
/*
* isLast() : gets if an index of an array is on the last index or not
*/
isLast : function (isLast) {
return (isLast);
},
/*
* getLength() : gets the length of given array
*/
getLength : function(arr) {
return (arr ? arr.length : 0);
}
};
}
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express = require("express");
const app = express();
app.use(express.static('../frontend'));
app.listen(3000, function () {
console.log('listening on port 3000');
});
//# sourceMappingURL=index.js.map
|
(function() {
'use strict';
/**
* Complex prototype for computation with complex numbers
*/
var Complex = function(real, imag) {
if (!(this instanceof Complex)) {
return new Complex(real, imag);
}
this.real = Number(real) || 0;
this.imag = Number(imag) || 0;
};
Complex.prototype.clone = function() {
return new Complex(this.real, this.imag);
};
Complex.toComplex = function(other) {
if (other instanceof Complex) {
return other;
} else {
return new Complex(Number(other) || 0, 0);
}
};
Complex.prototype.add = function(other) {
return this.clone().iadd(other);
};
Complex.prototype.iadd = function(other) {
other = Complex.toComplex(other);
this.real = this.real + other.real;
this.imag = this.imag + other.imag;
return this;
};
Complex.prototype.sub = function(other) {
return this.clone().isub(other);
};
Complex.prototype.isub = function(other) {
other = Complex.toComplex(other);
this.real = this.real - other.real;
this.imag = this.imag - other.imag;
return this;
};
Complex.prototype.mult = function(other) {
return this.clone().imult(other);
};
Complex.prototype.imult = function(other) {
other = Complex.toComplex(other);
var real = this.real * other.real - this.imag * other.imag,
imag = this.imag * other.real + this.real * other.imag;
this.real = real;
this.imag = imag;
return this;
};
Complex.prototype.div = function(other) {
return this.clone().idiv(other);
};
Complex.prototype.idiv = function(other) {
other = Complex.toComplex(other);
var denom = other.real * other.real + other.imag * other.imag,
real = (this.real * other.real + this.imag * other.imag) / denom,
imag = (this.imag * other.real - this.real * other.imag) / denom;
this.real = real;
this.imag = imag;
return this;
};
Complex.prototype.conjugate = function() {
return this.clone().iconjugate();
};
Complex.prototype.iconjugate = function() {
this.imag = -this.imag;
return this;
};
Complex.prototype.abs = function() {
return Math.sqrt(this.real * this.real + this.imag * this.imag);
};
Complex.prototype.pow = function(n) {
return this.clone().ipow(n);
};
Complex.prototype.ipow = function(n) {
var i, c;
n = Number(n) || 0;
if (n === 0) {
this.real = 1;
this.imag = 0;
} else if (n < 0) {
// Negative exponent
n = -n;
c = this.clone();
for (i = 1; i < n; i++) {
c.imult(this);
}
this.real = 1;
this.imag = 0;
this.idiv(c);
} else {
// Normal exponent
c = this.clone();
for (i = 1; i < n; i++) {
c.imult(this);
}
this.real = c.real;
this.imag = c.imag;
}
return this;
};
Complex.prototype.squared = function() {
return this.clone().ipow(2);
};
Complex.prototype.isquared = function() {
return this.ipow(2);
};
// Export library
module.exports = Complex;
})();
|
import React from "react";
import DocSection from "../../docs/DocSection";
import { wrapSection } from "../../../hocs/WrapSection";
const enhancer = wrapSection(
require.context("./examples", false, /.js$/),
require.context("!!raw-loader!./examples", false, /.js$/),
// eslint-disable-next-line import/no-webpack-loader-syntax
require("!!react-docgen-loader!../../../../modules/marker/MarkerIcon"),
);
function MarkerIconSection(props) {
return <DocSection {...props} name="<MarkerIcon />" />;
}
export default enhancer(MarkerIconSection);
|
function makeRequest(page,divid)
{
var http_request = getHttpRequest();
http_request.onreadystatechange = function() { handle_request(http_request,divid); };
http_request.open('GET', page, true);
http_request.send(null);
return false;
}
function handle_request(handle,divid)
{
if (handle.readyState != 4) {
document.getElementById(divid).innerHTML = 'Anropet misslyckades, kontakta oss om detta!';
return;
}
if (handle.status && handle.status != 200) {
document.getElementById(divid).innerHTML = 'Ett fel har uppstått. Felkod: ' + handle.status;
return;
}
document.getElementById(divid).innerHTML = handle.responseText;
}
//Returnerar ett XMLHttpRequest objekt
function getHttpRequest()
{
var handle = false;
if (window.XMLHttpRequest) { // Firefox, Opera, Safari
handle = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Internet Explorer
try {
handle = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
handle = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!handle) {
alert('Kan inte skapa ett XMLHTTP objekt');
return false;
}
return handle;
}
|
//inicializamos eventos y procesos desde el DOM
$(document).ready(function(){
IniciarEventos();}
);
function IniciarEventos(){
$('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
$('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
fechaactual('fecdesde')
fechaactual('fechasta')
reloadList(rlink)
$('#viewfaults').click(function(){
//call API changed state
reloadList(rlink)
})
$('#modalview').on('hidden.bs.modal', function () {
$('#content').empty();
$(this).data('bs.modal', null); //<---- empty() to clear the modal
})
}
function reloadList(link){
serialize=$('#filter').serialize()
$('#cargandodatos').show(1)
$.post(link,serialize,
function(data) {
$('#listfaultcars').html(data);
var divPaginationLinks = '#listfaultcars'+" .pagination a,.sort a";
$(divPaginationLinks).click(function(){
var thisHref = $(this).attr("href");
reloadList(thisHref);
//recarmamos el proceso de carga
return false;
});
}).always(function() {
$('#cargandodatos').hide(1)
});
}
function changestate(id){
if(typeof(id) != 'undefined'){
$.ajax({url:'/faultcars/faultcarschangedstatenj.json',
type:'post',
dataType:'json',
headers: {
'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S'
},
data:{id:id,state:1},
success: function(data){
$.each( data, function( key, val ) {
if(val.error != ''){
alert('Error: '+val.error)
}else{
$('#faultend'+id).hide(1)
}
});
}
})
}
}
function getubication(lat,lng){
$('#modalview').modal({
show: true,
remote: '/faultcars/getubicationmaps/'+lat+'/'+lng
});
return false
}
|
function OrbitCamera(basecam) {
this._cam = basecam;
this._viewpos = new THREE.Vector3(0.0,0.0,0.0);
this._theta = 0;
this._phi = 0;
this._rate = 0.05;
this._minradius = 0.1;
this._maxradius = 20.0;
this._radius = 5.0;
this._tarphi = 0.0;
this._tartheta = 0.0;
this._reftheta = 0.0;
this._tracked = false;
this._trackslope = 0.6;
this._tracktheta = 0.0;
}
function sphericalToCartesian(phi, theta, rad, offset) {
var y = Math.sin(phi) * rad;
var r2 = Math.cos(phi) * rad;
var x = Math.cos(theta) * r2;
var z = Math.sin(theta) * r2;
var ret = new THREE.Vector3(x, y, z);
if(offset) {
ret.add(offset);
}
return ret;
}
OrbitCamera.prototype.setTracking = function(trackstate) {
if(trackstate == true) {
this._tracked = true;
this._tracktheta = this._reftheta;
} else {
this._tracked = false;
this._viewpos.set(0,0,0);
}
};
OrbitCamera.prototype.updateTrack = function() {
var trackdist = -this._trackslope * this._radius;
this._tracktheta += ( this._reftheta - this._tracktheta ) * this._rate;
var viewx = Math.cos(this._tracktheta) * trackdist;
var viewz = Math.sin(this._tracktheta) * trackdist;
this._viewpos.set(viewx, 0.0, viewz);
};
OrbitCamera.prototype.updateCam = function() {
if(this._tracked) {
this.updateTrack();
}
this._theta += ( this._tartheta + this._reftheta - this._theta ) * this._rate;
this._phi += ( this._tarphi - this._phi ) * this._rate;
this._cam.position.copy(sphericalToCartesian(this._phi, this._theta, this._radius, this._viewpos));
this._cam.lookAt( this._viewpos );
};
OrbitCamera.prototype.updateSpherical = function(targettheta, targetphi) {
this._tarphi = targetphi;
this._tartheta = targettheta;
this.updateCam();
};
OrbitCamera.prototype.updateScreen = function(sx, sy, sw, sh) {
var phi = ((sy / sh) * 2.0 - 1.0) * Math.PI;
var theta = ((sx / sw) * 2.0 - 1.0) * Math.PI * 2.0;
this.updateSpherical(theta, phi);
};
OrbitCamera.prototype.updateZoomDelta = function(dzoom) {
this._radius = Math.max(this._minradius, Math.min(this._maxradius, this._radius + dzoom));
this.updateCam();
};
OrbitCamera.prototype.setRefTheta = function(reftheta) {
this._reftheta = reftheta;
};
OrbitCamera.prototype.updateScreenDelta = function(dx, dy, sw, sh) {
var dphi = ((dy / sh) * 1.0) * Math.PI;
var dtheta = ((dx / sw) * 1.0) * Math.PI * 2.0;
//console.log("sw: " + sw + ", sh: " + sh);
//console.log("dphi: " + dphi + ", dtheta: " + dtheta);
this._tartheta += dtheta;
this._tarphi = Math.max(-Math.PI/2.0, Math.min(Math.PI/2.0, this._tarphi + dphi));
//console.log("tphi: " + this._tarphi + ", ttheta: " + this._tartheta);
this.updateCam();
};
OrbitCamera.prototype.panScreenDelta = function(dx, dy, sw, sh) {
var du = (dx / sw) * 100.0;
var dv = (dy / sh) * 100.0;
var ct = Math.cos(this._theta);
var st = Math.sin(this._theta);
var dz = du * ct - dv * st;
var dx = -du * st - dv * ct;
this._viewpos.x += dx;
this._viewpos.z += dz;
this.updateCam();
};
OrbitCamera.prototype.resetViewPos = function() {
this._viewpos.set(0,0,0);
};
var ocam;
var mouseDownState = false;
var mouseX = 0, mouseY = 0;
var prevMouseX = 0, prevMouseY = 0;
var mouseDX = 0, mouseDY = 0;
var zoomButtonDown = false;
var zoomButtonKeycode = 16; // shift
var panButtonDown = false;
var panButtonKeycode = 17; // ctrl
function initOrbitCamera(rawcamera) {
ocam = new OrbitCamera(rawcamera);
document.addEventListener( 'mousedown', onCamMouseDown, false );
document.addEventListener( 'mouseup', onCamMouseUp, false );
document.addEventListener( 'mousemove', onCamDocumentMouseMove, false );
document.addEventListener( 'keydown', onCamDocumentKeyDown, false );
document.addEventListener( 'keyup', onCamDocumentKeyUp, false );
}
function updateCamera() {
mouseDX = mouseX - prevMouseX;
mouseDY = mouseY - prevMouseY;
prevMouseX = mouseX;
prevMouseY = mouseY;
if(mouseDownState == true) {
//console.log("Dx: " + mouseDX + ", Dy: " + mouseDY)
ocam.updateScreenDelta(mouseDX, mouseDY, windowX, windowY);
} else if(zoomButtonDown) {
ocam.updateZoomDelta(mouseDY / 10.0);
} else if(panButtonDown) {
ocam.panScreenDelta(mouseDX, mouseDY, windowX, windowY);
} else {
ocam.updateCam();
}
}
function onCamMouseDown() {
mouseDownState = true;
}
function onCamMouseUp() {
mouseDownState = false;
}
function onWindowResize() {
getSize();
camera.aspect = windowX / windowY;
camera.updateProjectionMatrix();
renderer.setSize( windowX, windowY );
}
function onCamDocumentKeyDown(event) {
if(event.keyCode == zoomButtonKeycode) {
zoomButtonDown = true;
}
if(event.keyCode == panButtonKeycode) {
panButtonDown = true;
}
}
function onCamDocumentKeyUp(event) {
if(event.keyCode == zoomButtonKeycode) {
zoomButtonDown = false;
}
if(event.keyCode == panButtonKeycode) {
panButtonDown = false;
}
}
function onCamDocumentMouseMove( event ) {
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
}
|
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as userInterfaceActions from '../actions/user_interface_actions';
import Dashboard from './dashboard';
const PortfolioApp = React.createClass({
render() {
return (
<Dashboard
{...this.props}/>
);
}
});
function mapStateToProps(state) {
return {
...state.mainReducer
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ ...userInterfaceActions }, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(PortfolioApp);
|
import { TICK, TOGGLE, CLEAR, RANDOM } from '../constants/ActionTypes';
import { makeGrid, makeBlankGrid } from '../lib/grid';
import { nextState, toggle } from '../lib/game';
const GRID_SIZE = 30;
const randomizer = (y, x) => Math.random(x + y) > 0.8;
const DEFAULT_STATE = makeGrid(randomizer, GRID_SIZE);
const clone = (xs) => xs.slice();
export default function grid(state = DEFAULT_STATE, action) {
switch (action.type) {
case TICK:
return nextState(state);
case TOGGLE:
return toggle(action.coordinates, action.current, clone(state));
case CLEAR:
return makeBlankGrid(GRID_SIZE, GRID_SIZE);
case RANDOM:
return makeGrid(randomizer, GRID_SIZE);
default:
return state;
}
}
|
'use strict';
module.exports.validateEmail = (email) => {
let re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
let valid = re.test(email);
let error = valid ? "" : "invalid e-mail";
return {
valid: valid,
value: email,
error : error
}
/*
NOTE:
The regular expression used here DOES NOT comply to the required standard.
In my book - however - this is good enough though. Mind that actual e-mail
validation is about people submitting an e-mail address that actually works
and that they have access to ... not about format.
Oh and yes, regex is not my strong suit ... I learn it, use it, don't use it
for a long time, forget it, need to learn it again ;)
*/
}
|
const path = require('path');
const docsConfig = require('./docs.config');
module.exports = Object.assign(
{},
docsConfig,
{
plugins: [],
devtool: 'module-source-map',
devServer: {
contentBase: path.resolve(__dirname, '../examples'),
stats: { colors: true },
},
},
);
|
/*
copy.js
===========
copies images and javascript folders to public
*/
var gulp = require('gulp')
var config = require('./config.json')
gulp.task('copy-assets', function () {
return gulp.src(['!' + config.paths.assets + 'sass{,/**/*}',
config.paths.assets + '/**'])
.pipe(gulp.dest(config.paths.public))
})
gulp.task('copy-documentation-assets', function () {
return gulp.src(['!' + config.paths.docsAssets + 'sass{,/**/*}',
config.paths.docsAssets + '/**'])
.pipe(gulp.dest(config.paths.public))
})
gulp.task('copy-assets-beta', function () {
return gulp.src(['!' + config.paths.assetsbeta + 'sass{,/**/*}',
config.paths.assetsbeta + '/**'])
.pipe(gulp.dest(config.paths.publicbeta))
})
gulp.task('copy-documentation-assets-beta', function () {
return gulp.src(['!' + config.paths.docsAssetsbeta + 'sass{,/**/*}',
config.paths.docsAssetsbeta + '/**'])
.pipe(gulp.dest(config.paths.publicbeta))
})
gulp.task('copy-assets-S1', function () {
return gulp.src(['!' + config.paths.assetsS1 + 'sass{,/**/*}',
config.paths.assetsS1 + '/**'])
.pipe(gulp.dest(config.paths.publicS1))
})
gulp.task('copy-documentation-assets-S1', function () {
return gulp.src(['!' + config.paths.docsAssetsS1 + 'sass{,/**/*}',
config.paths.docsAssetsS1 + '/**'])
.pipe(gulp.dest(config.paths.publicS1))
})
gulp.task('copy-assets-S2', function () {
return gulp.src(['!' + config.paths.assetsS2 + 'sass{,/**/*}',
config.paths.assetsS2 + '/**'])
.pipe(gulp.dest(config.paths.publicS2))
})
gulp.task('copy-documentation-assets-S2', function () {
return gulp.src(['!' + config.paths.docsAssetsS2 + 'sass{,/**/*}',
config.paths.docsAssetsS2 + '/**'])
.pipe(gulp.dest(config.paths.publicS2))
})
gulp.task('copy-assets-S3', function () {
return gulp.src(['!' + config.paths.assetsS3 + 'sass{,/**/*}',
config.paths.assetsS3 + '/**'])
.pipe(gulp.dest(config.paths.publicS3))
})
gulp.task('copy-documentation-assets-S3', function () {
return gulp.src(['!' + config.paths.docsAssetsS3 + 'sass{,/**/*}',
config.paths.docsAssetsS3 + '/**'])
.pipe(gulp.dest(config.paths.publicS3))
})
gulp.task('copy-assets-S4', function () {
return gulp.src(['!' + config.paths.assetsS4 + 'sass{,/**/*}',
config.paths.assetsS4 + '/**'])
.pipe(gulp.dest(config.paths.publicS4))
})
gulp.task('copy-documentation-assets-S4', function () {
return gulp.src(['!' + config.paths.docsAssetsS4 + 'sass{,/**/*}',
config.paths.docsAssetsS4 + '/**'])
.pipe(gulp.dest(config.paths.publicS4))
})
gulp.task('copy-assets-S5', function () {
return gulp.src(['!' + config.paths.assetsS5 + 'sass{,/**/*}',
config.paths.assetsS5 + '/**'])
.pipe(gulp.dest(config.paths.publicS5))
})
gulp.task('copy-documentation-assets-S5', function () {
return gulp.src(['!' + config.paths.docsAssetsS5 + 'sass{,/**/*}',
config.paths.docsAssetsS5 + '/**'])
.pipe(gulp.dest(config.paths.publicS5))
})
gulp.task('copy-assets-S6', function () {
return gulp.src(['!' + config.paths.assetsS6 + 'sass{,/**/*}',
config.paths.assetsS6 + '/**'])
.pipe(gulp.dest(config.paths.publicS6))
})
gulp.task('copy-documentation-assets-S6', function () {
return gulp.src(['!' + config.paths.docsAssetsS6 + 'sass{,/**/*}',
config.paths.docsAssetsS6 + '/**'])
.pipe(gulp.dest(config.paths.publicS6))
})
gulp.task('copy-assets-S7', function () {
return gulp.src(['!' + config.paths.assetsS7 + 'sass{,/**/*}',
config.paths.assetsS7 + '/**'])
.pipe(gulp.dest(config.paths.publicS7))
})
gulp.task('copy-documentation-assets-S7', function () {
return gulp.src(['!' + config.paths.docsAssetsS7 + 'sass{,/**/*}',
config.paths.docsAssetsS7 + '/**'])
.pipe(gulp.dest(config.paths.publicS7))
})
gulp.task('copy-assets-S8', function () {
return gulp.src(['!' + config.paths.assetsS8 + 'sass{,/**/*}',
config.paths.assetsS8 + '/**'])
.pipe(gulp.dest(config.paths.publicS8))
})
gulp.task('copy-documentation-assets-S8', function () {
return gulp.src(['!' + config.paths.docsAssetsS8 + 'sass{,/**/*}',
config.paths.docsAssetsS8 + '/**'])
.pipe(gulp.dest(config.paths.publicS8))
})
gulp.task('copy-assets-S9', function () {
return gulp.src(['!' + config.paths.assetsS9 + 'sass{,/**/*}',
config.paths.assetsS9 + '/**'])
.pipe(gulp.dest(config.paths.publicS9))
})
gulp.task('copy-documentation-assets-S9', function () {
return gulp.src(['!' + config.paths.docsAssetsS9 + 'sass{,/**/*}',
config.paths.docsAssetsS9 + '/**'])
.pipe(gulp.dest(config.paths.publicS9))
})
gulp.task('copy-assets-S10', function () {
return gulp.src(['!' + config.paths.assetsS10 + 'sass{,/**/*}',
config.paths.assetsS10 + '/**'])
.pipe(gulp.dest(config.paths.publicS10))
})
gulp.task('copy-documentation-assets-S10', function () {
return gulp.src(['!' + config.paths.docsAssetsS10 + 'sass{,/**/*}',
config.paths.docsAssetsS10 + '/**'])
.pipe(gulp.dest(config.paths.publicS10))
})
gulp.task('copy-assets-S11', function () {
return gulp.src(['!' + config.paths.assetsS11 + 'sass{,/**/*}',
config.paths.assetsS11 + '/**'])
.pipe(gulp.dest(config.paths.publicS11))
})
gulp.task('copy-documentation-assets-S11', function () {
return gulp.src(['!' + config.paths.docsAssetsS11 + 'sass{,/**/*}',
config.paths.docsAssetsS11 + '/**'])
.pipe(gulp.dest(config.paths.publicS11))
})
gulp.task('copy-assets-S19', function () {
return gulp.src(['!' + config.paths.assetsS19 + 'sass{,/**/*}',
config.paths.assetsS19 + '/**'])
.pipe(gulp.dest(config.paths.publicS19))
})
gulp.task('copy-documentation-assets-S19', function () {
return gulp.src(['!' + config.paths.docsAssetsS19 + 'sass{,/**/*}',
config.paths.docsAssetsS19 + '/**'])
.pipe(gulp.dest(config.paths.publicS19))
})
gulp.task('copy-assets-S20', function () {
return gulp.src(['!' + config.paths.assetsS20 + 'sass{,/**/*}',
config.paths.assetsS20 + '/**'])
.pipe(gulp.dest(config.paths.publicS20))
})
gulp.task('copy-documentation-assets-S20', function () {
return gulp.src(['!' + config.paths.docsAssetsS20 + 'sass{,/**/*}',
config.paths.docsAssetsS20 + '/**'])
.pipe(gulp.dest(config.paths.publicS20))
})
gulp.task('copy-assets-S23', function () {
return gulp.src(['!' + config.paths.assetsS23 + 'sass{,/**/*}',
config.paths.assetsS23 + '/**'])
.pipe(gulp.dest(config.paths.publicS23))
})
gulp.task('copy-documentation-assets-S23', function () {
return gulp.src(['!' + config.paths.docsAssetsS23 + 'sass{,/**/*}',
config.paths.docsAssetsS23 + '/**'])
.pipe(gulp.dest(config.paths.publicS23))
})
gulp.task('copy-assets-S25', function () {
return gulp.src(['!' + config.paths.assetsS25 + 'sass{,/**/*}',
config.paths.assetsS25 + '/**'])
.pipe(gulp.dest(config.paths.publicS25))
})
gulp.task('copy-documentation-assets-S25', function () {
return gulp.src(['!' + config.paths.docsAssetsS25 + 'sass{,/**/*}',
config.paths.docsAssetsS25 + '/**'])
.pipe(gulp.dest(config.paths.publicS25))
})
gulp.task('copy-assets-S26', function () {
return gulp.src(['!' + config.paths.assetsS26 + 'sass{,/**/*}',
config.paths.assetsS26 + '/**'])
.pipe(gulp.dest(config.paths.publicS26))
})
gulp.task('copy-documentation-assets-S26', function () {
return gulp.src(['!' + config.paths.docsAssetsS26 + 'sass{,/**/*}',
config.paths.docsAssetsS26 + '/**'])
.pipe(gulp.dest(config.paths.publicS26))
})
gulp.task('copy-assets-S31', function () {
return gulp.src(['!' + config.paths.assetsS31 + 'sass{,/**/*}',
config.paths.assetsS31 + '/**'])
.pipe(gulp.dest(config.paths.publicS31))
})
gulp.task('copy-documentation-assets-S31', function () {
return gulp.src(['!' + config.paths.docsAssetsS31 + 'sass{,/**/*}',
config.paths.docsAssetsS31 + '/**'])
.pipe(gulp.dest(config.paths.publicS31))
})
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const chalk_1 = require("chalk");
const command_1 = require("@ionic/cli-utils/lib/command");
const serve_1 = require("@ionic/cli-utils/lib/serve");
let DocsCommand = class DocsCommand extends command_1.Command {
run(inputs, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const { isSuperAgentError } = yield Promise.resolve().then(() => require('@ionic/cli-utils/guards'));
const { createRequest } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/http'));
const browser = options['browser'] ? String(options['browser']) : undefined;
const opn = yield Promise.resolve().then(() => require('opn'));
const docsHomepage = 'https://ionicframework.com/docs';
let url = docsHomepage;
const project = this.env.project.directory ? yield this.env.project.load() : undefined;
if (project) {
if (project.type === 'ionic1') {
url = 'https://ionicframework.com/docs/v1/';
}
else if (project.type === 'ionic-angular') {
url = 'https://ionicframework.com/docs/api'; // TODO: can know framework version, HEAD request, etc
}
}
try {
const { req } = yield createRequest(this.env.config, 'head', url);
yield req;
}
catch (e) {
if (isSuperAgentError(e)) {
if (e.response.status === 404) {
this.env.log.warn(`Docs not found for your specific version of Ionic. Directing you to latest docs.`);
opn(`${docsHomepage}/api`, { wait: false });
return;
}
}
throw e;
}
yield opn(url, { app: browser, wait: false });
this.env.log.ok('Launched Ionic docs in your browser!');
});
}
};
DocsCommand = tslib_1.__decorate([
command_1.CommandMetadata({
name: 'docs',
type: 'global',
description: 'Open the Ionic documentation website',
options: [
{
name: 'browser',
description: `Specifies the browser to use (${serve_1.BROWSERS.map(b => chalk_1.default.green(b)).join(', ')})`,
aliases: ['w'],
advanced: true,
},
],
})
], DocsCommand);
exports.DocsCommand = DocsCommand;
|
'use strict';
angular.module('simpleCharts', []);
|
/*
* grunt-fea-build
* https://github.com/bpletzer/FET-build-dep
*
* Copyright (c) 2013 Benedikt Pletzer
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Configuration to be run (and then tested).
fea_build: {
default_options: {
options: {
},
files: {
'tmp/default_options': ['test/fixtures/testing', 'test/fixtures/123'],
},
},
custom_options: {
options: {
separator: ': ',
punctuation: ' !!!',
},
files: {
'tmp/custom_options': ['test/fixtures/testing', 'test/fixtures/123'],
},
},
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'fea_build', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
// Generated by CoffeeScript 1.3.3
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
app.views.PostList = (function(_super) {
__extends(PostList, _super);
function PostList() {
this.render = __bind(this.render, this);
return PostList.__super__.constructor.apply(this, arguments);
}
PostList.prototype.el = function() {
return document.getElementById('content');
};
PostList.prototype.render = function() {
var $view, model, _i, _len, _ref, _results;
this.$el = $(this.el);
this.$el.html('');
_ref = this.model.models;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
model = _ref[_i];
$view = new app.views.Post[app.theme]({
model: model
}).render();
if ($view != null) {
_results.push($view.appendTo(this.el));
} else {
_results.push(void 0);
}
}
return _results;
};
return PostList;
})(Backbone.View);
}).call(this);
|
modules.define('component', ['inherit'], function (provide, inherit) {
/**
* Base component
* @implements IComponent
*/
provide(inherit({
_isStarted: false,
start: function () {
this._isStarted = true;
},
stop: function () {
this._isStarted = false;
},
isStarted: function () {
return this._isStarted;
}
}, {
getName: function () {}
}));
});
|
// For development only!!
// Add sample data to window object that used for initializing appendGrid.
window.myAppendGridInitData = [{
"uid": "d4c74a61-a24e-429f-9db0-3cf3aaa22425",
"name": "Monique Zebedee",
"company": "Welch LLC",
"country": "Japan",
"memberSince": "2012-02-18",
"orderPlaced": 111,
"level": "Bronze",
"isNPO": true
}, {
"uid": "afdf285d-da5c-4fa8-9225-201c858a173d",
"name": "Daryle McLaren",
"company": "Bogisich Group",
"country": "United States",
"memberSince": "2016-10-08",
"orderPlaced": 261,
"level": "Diamond",
"isNPO": false
}, {
"uid": "202a8afb-130b-476b-b415-c659f21a73e7",
"name": "Glori Spellecy",
"company": "Grady and Sons",
"country": "Germany",
"memberSince": "2014-07-28",
"orderPlaced": 282,
"level": "Gold",
"isNPO": false
}, {
"uid": "08c9adee-abdd-43d5-866d-ce540be19be8",
"name": "Blondy Boggis",
"company": "Eichmann, Parker and Herzog",
"country": "Malaysia",
"memberSince": "2010-08-17",
"orderPlaced": 308,
"level": "Platinum",
"isNPO": true
}, {
"uid": "57644023-cd0c-47ec-a556-fd8d4e21a4e7",
"name": "Batholomew Zecchii",
"company": "Corwin-Fahey",
"country": "Malaysia",
"memberSince": "2016-09-20",
"orderPlaced": 881,
"level": "Gold",
"isNPO": true
}, {
"uid": "38e08e8a-c7eb-41eb-9191-6bb2df1fd39b",
"name": "Paulie Poel",
"company": "MacGyver, Rohan and West",
"country": "United Kingdom",
"memberSince": "2016-12-26",
"orderPlaced": 387,
"level": "Silver",
"isNPO": false
}, {
"uid": "d7bf56d4-f955-4dca-b3db-b30eab590028",
"name": "Jessica Levett",
"company": "Lind, O'Kon and Hamill",
"country": "United States",
"memberSince": "2015-04-26",
"orderPlaced": 984,
"level": "Gold",
"isNPO": false
}, {
"uid": "b9075764-5228-4ca7-9435-7c362ce097e5",
"name": "Fonsie Spring",
"company": "McKenzie, Block and Wiegand",
"country": "Japan",
"memberSince": "2013-11-08",
"orderPlaced": 875,
"level": "Silver",
"isNPO": false
}];
|
const api = "http://127.0.0.1:3001/"
let token = localStorage.token
if (!token)
token = localStorage.token = Math.random().toString(36).substr(-8)
const headers = {
'Authorization': token,
'Content-Type': 'application/json',
'Accept': 'application/json'
};
export const getCategories = () => {
const url = api + "categories";
return fetch(url, {method: "GET", headers}).then(res => res.json())
};
export const getPostsByCategory = (categoryName) => {
const url = api + categoryName + "/posts";
return fetch(url, {method: "GET", headers}).then(res => res.json())
};
export const getPosts = () => {
const url = api + "posts";
return fetch(url, {method: "GET", headers}).then(res => res.json())
};
export const addPost = ({id, timestamp, title, body, author, category}) => {
const url = api + "posts";
let post = {id, timestamp, title, body, author, category};
return fetch(url, {method: "POST", headers, body: JSON.stringify(post)}).then(res => res.json())
};
export const getPostDetail = (postId) => {
const url = api + "posts/" + postId;
return fetch(url, {method: "GET", headers}).then(res => res.json())
};
export const upVotePost = (postId) => {
const url = api + "posts/" + postId;
return fetch(url, {
method: "POST", headers, body: JSON.stringify({option: "upVote"})
}).then(res => res.json())
};
export const downVotePost = (postId) => {
const url = api + "posts/" + postId;
return fetch(url, {
method: "POST", headers, body: JSON.stringify({option: "downVote"})
}).then(res => res.json())
};
export const updatePost = ({id, title, body}) => {
const url = api + "posts/" + id;
const post = {
title,
body
}
return fetch(url, {method: "PUT", headers, body: JSON.stringify(post)}).then(res => res.json())
};
export const deletePost = (postId) => {
const url = api + "posts/" + postId;
return fetch(url, {method: "DELETE", headers}).then(res => res.json())
};
export const getAllComentsByPost = (postId) => {
const url = api + "posts/" + postId + "/comments";
return fetch(url, {method: "GET", headers}).then(res => res.json())
};
export const addComment = ({id, timestamp, body, author, parentId}) => {
const url = api + "comments";
const comment = {id, timestamp, body, author, parentId};
return fetch(url, {method: "POST", headers, body: JSON.stringify(comment)}).then(res => res.json())
};
export const getCommentDetail = (commentId) => {
const url = api + "/comments/" + commentId;
return fetch(url, {method: "POST", headers}).then(res => res.json())
};
export const upVoteComment = (commentId) => {
const url = api + "comments/" + commentId;
return fetch(url, {
method: "POST", headers, body: JSON.stringify({option: "upVote"})
}).then(res => res.json())
};
export const downVoteComment = (commentId) => {
const url = api + "comments/" + commentId;
return fetch(url, {
method: "POST", headers, body: JSON.stringify({option: "downVote"})
}).then(res => res.json())
};
export const updateComment = ({id, timestamp, body}) => {
const url = api + "comments/" + id;
const comment = {timestamp, body};
return fetch(url, {method: "PUT", headers, body: JSON.stringify(comment)}).then(res => res.json())
};
export const deleteComment = (commentId) => {
const url = api + "comments/" + commentId;
return fetch(url, {method: "DELETE", headers}).then(res => res.json())
};
|
const fs = require("fs")
const dialog = require('./luis.js')
fs.readdirSync('bot/luis/matches').forEach(file => require('./matches/' + file))
module.exports = dialog
|
(function (tree) {
//
// A function call node.
//
tree.Call = function (name, args, index) {
this.name = name;
this.args = args;
this.index = index;
};
tree.Call.prototype = {
//
// When evaluating a function call,
// we either find the function in `tree.functions` [1],
// in which case we call it, passing the evaluated arguments,
// or we simply print it out as it appeared originally [2].
//
// The *functions.js* file contains the built-in functions.
//
// The reason why we evaluate the arguments, is in the case where
// we try to pass a variable to a function, like: `saturate(@color)`.
// The function should receive the value, not the variable.
//
eval: function (env) {
var args = this.args.map(function (a) { return a.eval(env) });
if (this.name in tree.functions) { // 1.
try {
return tree.functions[this.name].apply(tree.functions, args);
} catch (e) {
throw { type: e.type || "Runtime",
message: "error evaluating function `" + this.name + "`" +
(e.message ? ': ' + e.message : ''),
index: this.index };
}
} else { // 2.
return new(tree.Anonymous)(this.name +
"(" + args.map(function (a) { return a.toCSS() }).join(', ') + ")");
}
},
toCSS: function (env) {
return this.eval(env).toCSS();
}
};
})(require('../tree'));
|
export default function (q1, q2, precision = 1e-6) {
return (
Math.abs(q1[0] - q2[0]) <= precision &&
Math.abs(q1[1] - q2[1]) <= precision &&
Math.abs(q1[2] - q2[2]) <= precision &&
Math.abs(q1[3] - q2[3]) <= precision
);
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:c4eff6147e4aa3cd83b559adb30b75a42f984ca68528744b89729bb6f4fb4370
size 50687
|
'use strict';
const redirects = function (request, h) {
return h.redirect('/').takeover();
};
module.exports = redirects;
|
jQuery(function(a){a.datepicker.regional["en-AU"]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu",
"We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""};a.datepicker.setDefaults(a.datepicker.regional["en-AU"])});
|
const views = {
engines: {
pug: require('pug')
},
relativeTo: __dirname,
path: '../views'
};
module.exports = views;
|
(function(){
'use strict';
angular.module('playlistApp.track', [])
.directive('pbTrack', function(){
return {
restrict: 'E',
templateUrl: 'components/track/track.html',
scope: {
track: '=',
list: '=',
index: '='
},
controller: function($scope, UserData, PlayerData){
$scope.addTrack = function(track){
UserData.addToCollection(track);
};
$scope.playTrack = function(track){
PlayerData.setTrack(track, $scope.list, $scope.index);
};
$scope.minutes = Math.floor(Math.round($scope.track.duration / 1000) / 60);
$scope.seconds = Math.floor(Math.round($scope.track.duration / 1000) % 60);
$scope.formattedDuration = $scope.minutes + ':' + $scope.seconds;
},
link: function (scope, element, attrs) {
}
}
})
})();
|
import React from 'react';
import highlight from './highlight';
export default options => {
const {
loader,
isLanguageRegistered,
registerLanguage,
languageLoaders,
noAsyncLoadingLanguages
} = options;
class ReactAsyncHighlighter extends React.PureComponent {
static astGenerator = null;
static highlightInstance = highlight(null, {});
static astGeneratorPromise = null;
static languages = new Map();
static supportedLanguages =
options.supportedLanguages || Object.keys(languageLoaders || {});
static preload() {
return ReactAsyncHighlighter.loadAstGenerator();
}
static async loadLanguage(language) {
const languageLoader = languageLoaders[language];
if (typeof languageLoader === 'function') {
return languageLoader(ReactAsyncHighlighter.registerLanguage);
} else {
throw new Error(`Language ${language} not supported`);
}
}
static isSupportedLanguage(language) {
return (
ReactAsyncHighlighter.isRegistered(language) ||
typeof languageLoaders[language] === 'function'
);
}
static isRegistered = language => {
if (noAsyncLoadingLanguages) {
return true;
}
if (!registerLanguage) {
throw new Error(
"Current syntax highlighter doesn't support registration of languages"
);
}
if (!ReactAsyncHighlighter.astGenerator) {
// Ast generator not available yet, but language will be registered once it is.
return ReactAsyncHighlighter.languages.has(language);
}
return isLanguageRegistered(ReactAsyncHighlighter.astGenerator, language);
};
static registerLanguage = (name, language) => {
if (!registerLanguage) {
throw new Error(
"Current syntax highlighter doesn't support registration of languages"
);
}
if (ReactAsyncHighlighter.astGenerator) {
return registerLanguage(
ReactAsyncHighlighter.astGenerator,
name,
language
);
} else {
ReactAsyncHighlighter.languages.set(name, language);
}
};
static loadAstGenerator() {
ReactAsyncHighlighter.astGeneratorPromise = loader().then(
astGenerator => {
ReactAsyncHighlighter.astGenerator = astGenerator;
if (registerLanguage) {
ReactAsyncHighlighter.languages.forEach((language, name) =>
registerLanguage(astGenerator, name, language)
);
}
}
);
return ReactAsyncHighlighter.astGeneratorPromise;
}
componentDidUpdate() {
if (
!ReactAsyncHighlighter.isRegistered(this.props.language) &&
languageLoaders
) {
this.loadLanguage();
}
}
componentDidMount() {
if (!ReactAsyncHighlighter.astGeneratorPromise) {
ReactAsyncHighlighter.loadAstGenerator();
}
if (!ReactAsyncHighlighter.astGenerator) {
ReactAsyncHighlighter.astGeneratorPromise.then(() => {
this.forceUpdate();
});
}
if (
!ReactAsyncHighlighter.isRegistered(this.props.language) &&
languageLoaders
) {
this.loadLanguage();
}
}
loadLanguage() {
const { language } = this.props;
if (language === 'text') {
return;
}
ReactAsyncHighlighter.loadLanguage(language)
.then(() => {
return this.forceUpdate();
})
.catch(() => {});
}
normalizeLanguage(language) {
return ReactAsyncHighlighter.isSupportedLanguage(language)
? language
: 'text';
}
render() {
return (
<ReactAsyncHighlighter.highlightInstance
{...this.props}
language={this.normalizeLanguage(this.props.language)}
astGenerator={ReactAsyncHighlighter.astGenerator}
/>
);
}
}
return ReactAsyncHighlighter;
};
|
function validSlug(value) {
return /^([a-zA-Z0-9-]*)?$/i.test(value);
}
function addSlugValidation(inputSlugId){
var inputSlug = $vic('#' + inputSlugId);
displaySlugIcons(inputSlugId, inputSlug.val());
inputSlug.on('keyup', function(){
displaySlugIcons(inputSlugId, $vic(this).val());
});
}
function displaySlugIcons(inputSlugId, slug){
var correctSlugIcon = $vic('#' + inputSlugId + '-correct');
var notCorrectSlugIcon = $vic('#' + inputSlugId + '-not-correct');
if (slug != 'undefined' && slug != "") {
if (validSlug(slug)) {
correctSlugIcon.removeClass('vic-hidden');
notCorrectSlugIcon.addClass('vic-hidden');
}else{
correctSlugIcon.addClass('vic-hidden');
notCorrectSlugIcon.removeClass('vic-hidden');
};
}else{
correctSlugIcon.removeClass('vic-hidden');
notCorrectSlugIcon.addClass('vic-hidden');
};
}
|
var request = require('request');
var Q = require('q');
module.exports = (function () {
function FlickrAPI() {}
FlickrAPI.ENDPOINT = 'https://api.flickr.com/services/rest/';
FlickrAPI.APIKey = '7c8048f68c6cffcf51b58b17380a90f5';
FlickrAPI.Secret = 'fb5c317f514c35b4';
FlickrAPI.prototype.tags = {
getRelated: function (tag) {
var deferred = Q.defer();
var query = {
method: 'flickr.tags.getRelated',
api_key: FlickrAPI.APIKey,
tag: tag,
format: 'json',
nojsoncallback: 1
};
console.log('query', query);
request({
uri: FlickrAPI.ENDPOINT,
qs: query
}, function (error, response, body) {
console.log('got body: ', body);
if (body) {
deferred.resolve(JSON.parse(body));
} else {
deferred.reject('error!');
}
});
return deferred.promise;
}
};
return FlickrAPI;
}());
|
/**
* 把组件 MD 文档转为 hexo 最终渲染 MD,主要功能:
* 1、增加头部信息,用于渲染左侧多级菜单
* 2、把组件内的 jsdoc 注释转为 MD 追加到尾部,用于生成 API 文档
* 3、把 DEMO 代码实例化为组件
*
* author: Cody Chan <int64ago@gmail.com> 2017-02-08
*/
/* eslint no-param-reassign: 0 */
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const jsdoc2md = require('jsdoc-to-markdown');
// 分类的顺序跟下面保持一致,每个分类下的组件顺序不作保证
const CATES = [
{ cate: 'layout', name: '布局', startOrder: 100 },
{ cate: 'form', name: '表单', startOrder: 200 },
{ cate: 'notice', name: '通知', startOrder: 300 },
{ cate: 'navigation', name: '导航', startOrder: 400 },
{ cate: 'widget', name: '其它', startOrder: 500 },
];
const DOC_PATH = __dirname;
const COMPONENTS_PATH = path.join(__dirname, '../../src/js/components');
const COMPONENTS_DEST = path.join(DOC_PATH, 'components');
const getComponents = (cate) => {
const fullPath = path.join(COMPONENTS_PATH, cate);
return fs.readdirSync(fullPath).filter(f => fs.statSync(path.join(fullPath, f)).isDirectory());
};
const getDemoCode = (demo) => {
const rglMatch = /(```(xml|html))([\s\S]*?)(```)/g.exec(demo);
const jsMatch = /(```javascript)([\s\S]*?)(```)/g.exec(demo);
return {
rgl: rglMatch ? rglMatch[3] : '',
js: jsMatch ? jsMatch[2] : 'var component = new NEKUI.Component({template: template});',
};
};
const injectComponents = (md) => {
const demos = [];
const reg = /(<div class="grid-item" markdown="1">)([\s\S]*?)(</div>)/g;
let match = reg.exec(md);
while (match) {
demos.push(getDemoCode(match[2]));
match = reg.exec(md);
}
if (demos.length === 0) return md;
let demosScript = '\n\n<script>\nvar index = 0;\n';
demos.forEach((demo) => {
const tempJs = demo.js.replace(/`/gim, '\\`');
demosScript += `
(function(index) {
var template = NEKUI._.multiline(function(){/*
${demo.rgl}
*/});
${demo.js}
component.$inject(document.querySelectorAll('.m-example')[index]);
var gridItem = document.querySelectorAll('.grid-item')[index];
var codeDemo = document.createElement('div');
codeDemo.className = 'm-code';
var child = gridItem.childNodes;
child.forEach(function(item,index){
if(item.tagName == 'FIGURE'){
codeDemo.appendChild(item);
}
});
gridItem.appendChild(codeDemo);
var codeComponent = new DemoWrap({
data: {
htmlTpl: codeDemo.innerHTML,
htmlCode: \`${demo.rgl}\`,
jsCode: \`${tempJs}\`
}
});
codeDemo.innerHTML = '';
codeComponent.$inject(codeDemo);
})(index++);
`;
});
demosScript += '\n</script>\n';
return md + demosScript;
};
const partial = glob.sync(path.join(DOC_PATH, 'partials/**/*.hbs'));
const injectAPI = (md, source) => {
const docs = jsdoc2md.renderSync({
source,
'no-cache': true,
partial,
configure: path.join(__dirname, 'jsdoc.json'),
});
return `${md}\n# API\n${docs}`;
};
const doc = (isDev, callback) => {
// 其它文档
if (!isDev) {
const mds = glob.sync(path.join(DOC_PATH, '**/*.md'));
mds.forEach((md) => {
fs.writeFileSync(md, injectComponents(fs.readFileSync(md, 'utf8')));
});
}
// 组件文档
CATES.forEach((c) => {
const components = getComponents(c.cate).filter((comp) => {
// if (isDev && !/^KL(Sidebar|Modal|Draggable|Button|Loading|ImagePreview)$/.test(comp)) {
// return false;
// }
const mdPath = path.join(COMPONENTS_PATH, c.cate, comp, 'index.md');
if (fs.existsSync(mdPath)) return true;
return false;
});
components.forEach((comp, i) => {
const compPath = path.join(COMPONENTS_PATH, c.cate, comp);
const mdPath = path.join(compPath, 'index.md');
const jsPath = path.join(compPath, 'index.js');
const appendContent = `type: components\nname: ${comp}\ncate: ${c.name}\norder: ${c.startOrder + i}\n`;
let md = fs.readFileSync(mdPath, 'utf8');
// 插入文档头部信息
md = md.replace(/(^---)([\s\S]*?)(---)/g, `$1$2${appendContent}$3`);
// 插入 API 文档
if (fs.existsSync(jsPath)) {
md = injectAPI(md, fs.readFileSync(jsPath, 'utf8'));
}
// 插入实例化组件的脚本
md = injectComponents(md);
fs.writeFileSync(path.join(COMPONENTS_DEST, `${c.cate}_${comp}_.md`), md);
});
});
callback && callback();
};
module.exports = doc;
</int64ago@gmail.com>
|
var structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial =
[
[ "FloatAxial", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#addb3b8ac33094e21bd68f06c05af9ecf", null ],
[ "FloatAxial", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#a04a78a140b41b1220373d94fb91dab28", null ],
[ "ToFloatCubic", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#add3cd1669f683ed8aedc7926862ff265", null ],
[ "q", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#a302dfd83ed44787f6fcccd3bdfa76a02", null ],
[ "r", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#a2e3f908780aca1283e5f8793f9839279", null ]
];
|
import { withRouter } from 'next/router'
function useWithRouter (props) {
return <div>I use withRouter</div>
}
useWithRouter.getInitialProps = () => ({})
export default withRouter(useWithRouter)
|
import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH',
SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE',
SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE',
SET_ADMIN: 'SET_ADMIN',
};
export function setSearch(search) {
return {
type: ACTIONS.SET_ADMIN_SEARCH,
search
};
}
export function setCurrentPage(page) {
return {
type: ACTIONS.SET_ADMIN_CURRENT_PAGE,
page
};
}
export function setMaxPage(page) {
return {
type: ACTIONS.SET_ADMIN_MAX_PAGE,
page
};
}
export function setAdmin(admin) {
return {
type: ACTIONS.SET_ADMIN,
admin
};
}
export function getAdminSearch(search, page) {
return (dispatch) => {
return callApi(`admin?search=${search}&page=${page}`, 'get', '' ).then(res => {
dispatch(setAdmin(res.admin));
});
};
}
export function deleteAdmin(del) {
return () => {
return callApi('admin/delete', 'post', '', {del}).then(res => {
return res;
});
};
}
export function recoverAdmin(recover) {
return () => {
return callApi('admin/recover', 'post', '', {recover}).then(res => {
return res;
});
};
}
export function createAdmin(admin) {
return () => {
return callApi('admin', 'post', '', {admin}).then(res => {
return res.admin;
});
};
}
|
export default {
signupInitialState: {
success: false,
welcome: false,
errors: null,
fails: null
},
signinInitialState: {
success: false,
errors: null,
fails: null
},
passwordInitialState: {
message: null,
success: false,
errors: null,
fails: null,
resetMessage: null,
resetSuccess: false,
resetErrors: null,
resetFails: null
},
groupInitialState: {
error: null,
addUserErr: null,
addUserSuccess: false,
postMessageErr: null,
groupMessagesErr: null,
groupMessages: null,
groupViewMessage: null,
groupViewMessageErr: null,
groupUsersStore: null,
groupUsersError: null,
userGroupsStore: null,
userGroupsError: null,
boardMessagesStore: null,
boardMessagesError: null,
usersSearch: null,
usersSearchErr: null,
messageRead: false,
messageReadErr: null
}
};
|
define([
'utils/Debug',
'core/Config',
'core/PubSub',
'core/Hub',
'utils/Dom',
'backbone',
'views/PageView',
'views/ToDoCollectionView',
'collections/ToDoCollection',
'caches/TodoCollectionCache'
], function(
Debug,
Config,
PubSub,
Hub,
Dom,
Backbone,
PageView,
ToDoCollectionView,
ToDoCollection,
ToDoCollectionCache
) {
'use strict';
// To supress REST warnings.
Backbone.emulateHTTP = true;
var log = Debug.log,
moduleName = Config.moduleName,
event = Config.event;
/**
*
*/
return {
/**
*
*/
run : function() {
log('>>>bootstrap.run');
var toDos,
toDoCollectionView,
pageView,
root = window[Config.ROOT_NAMESPACE] = {};
Hub.initialize();
toDos = new ToDoCollection();
log('[bootstrap] created collection');
toDos.add(ToDoCollectionCache.getAll());
log('[bootstrap] populated collection');
toDoCollectionView = new ToDoCollectionView({collection : toDos});
Hub.register(moduleName.MAIN_COLLECTION_VIEW, toDoCollectionView);
log('[bootstrap] created collection view');
pageView = new PageView();
Hub.register(moduleName.MAIN_PAGE_VIEW, pageView);
log('[bootstrap] created page view');
PubSub.publish(event.BOOTSTRAP_COMPLETE);
root.hub = Hub;
log('<<<bootstrap.run');
}
};
});
|
module.exports = function(redis_client){
this.redis = redis_client;
this.init = {
kakao_rest_key: "653ef2a8cf89b38765bd83528f3c9012",
kakao_redirect: "http://localhost:3000/oauth"
};
this.MD5_SALT = {
kakao: "VERyStronGPassword:)forKakaO"
};
this.redis_key = {
user: "DWT:user:",
session: "DWT:session:"
};
this.session = {
time: 24*60*60
};
return this;
};
|
YUI.add('yui2-connection', function(Y) {
var YAHOO = Y.YUI2;
/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.1
*/
/**
* The Connection Manager provides a simplified interface to the XMLHttpRequest
* object. It handles cross-browser instantiantion of XMLHttpRequest, negotiates the
* interactive states and server response, returning the results to a pre-defined
* callback you create.
*
* @namespace YAHOO.util
* @module connection
* @requires yahoo
* @requires event
*/
/**
* The Connection Manager singleton provides methods for creating and managing
* asynchronous transactions.
*
* @class Connect
*/
YAHOO.util.Connect =
{
/**
* @description Array of MSFT ActiveX ids for XMLHttpRequest.
* @property _msxml_progid
* @private
* @static
* @type array
*/
_msxml_progid:[
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP'
],
/**
* @description Object literal of HTTP header(s)
* @property _http_header
* @private
* @static
* @type object
*/
_http_headers:{},
/**
* @description Determines if HTTP headers are set.
* @property _has_http_headers
* @private
* @static
* @type boolean
*/
_has_http_headers:false,
/**
* @description Determines if a default header of
* Content-Type of 'application/x-www-form-urlencoded'
* will be added to any client HTTP headers sent for POST
* transactions.
* @property _use_default_post_header
* @private
* @static
* @type boolean
*/
_use_default_post_header:true,
/**
* @description The default header used for POST transactions.
* @property _default_post_header
* @private
* @static
* @type boolean
*/
_default_post_header:'application/x-www-form-urlencoded; charset=UTF-8',
/**
* @description The default header used for transactions involving the
* use of HTML forms.
* @property _default_form_header
* @private
* @static
* @type boolean
*/
_default_form_header:'application/x-www-form-urlencoded',
/**
* @description Determines if a default header of
* 'X-Requested-With: XMLHttpRequest'
* will be added to each transaction.
* @property _use_default_xhr_header
* @private
* @static
* @type boolean
*/
_use_default_xhr_header:true,
/**
* @description The default header value for the label
* "X-Requested-With". This is sent with each
* transaction, by default, to identify the
* request as being made by YUI Connection Manager.
* @property _default_xhr_header
* @private
* @static
* @type boolean
*/
_default_xhr_header:'XMLHttpRequest',
/**
* @description Determines if custom, default headers
* are set for each transaction.
* @property _has_default_header
* @private
* @static
* @type boolean
*/
_has_default_headers:true,
/**
* @description Determines if custom, default headers
* are set for each transaction.
* @property _has_default_header
* @private
* @static
* @type boolean
*/
_default_headers:{},
/**
* @description Property modified by setForm() to determine if the data
* should be submitted as an HTML form.
* @property _isFormSubmit
* @private
* @static
* @type boolean
*/
_isFormSubmit:false,
/**
* @description Property modified by setForm() to determine if a file(s)
* upload is expected.
* @property _isFileUpload
* @private
* @static
* @type boolean
*/
_isFileUpload:false,
/**
* @description Property modified by setForm() to set a reference to the HTML
* form node if the desired action is file upload.
* @property _formNode
* @private
* @static
* @type object
*/
_formNode:null,
/**
* @description Property modified by setForm() to set the HTML form data
* for each transaction.
* @property _sFormData
* @private
* @static
* @type string
*/
_sFormData:null,
/**
* @description Collection of polling references to the polling mechanism in handleReadyState.
* @property _poll
* @private
* @static
* @type object
*/
_poll:{},
/**
* @description Queue of timeout values for each transaction callback with a defined timeout value.
* @property _timeOut
* @private
* @static
* @type object
*/
_timeOut:{},
/**
* @description The polling frequency, in milliseconds, for HandleReadyState.
* when attempting to determine a transaction's XHR readyState.
* The default is 50 milliseconds.
* @property _polling_interval
* @private
* @static
* @type int
*/
_polling_interval:50,
/**
* @description A transaction counter that increments the transaction id for each transaction.
* @property _transaction_id
* @private
* @static
* @type int
*/
_transaction_id:0,
/**
* @description Tracks the name-value pair of the "clicked" submit button if multiple submit
* buttons are present in an HTML form; and, if YAHOO.util.Event is available.
* @property _submitElementValue
* @private
* @static
* @type string
*/
_submitElementValue:null,
/**
* @description Determines whether YAHOO.util.Event is available and returns true or false.
* If true, an event listener is bound at the document level to trap click events that
* resolve to a target type of "Submit". This listener will enable setForm() to determine
* the clicked "Submit" value in a multi-Submit button, HTML form.
* @property _hasSubmitListener
* @private
* @static
*/
_hasSubmitListener:(function()
{
if(YAHOO.util.Event){
YAHOO.util.Event.addListener(
document,
'click',
function(e){
var obj = YAHOO.util.Event.getTarget(e);
if(obj.type && obj.type.toLowerCase() == 'submit'){
YAHOO.util.Connect._submitElementValue = encodeURIComponent(obj.name) + "=" + encodeURIComponent(obj.value);
}
});
return true;
}
return false;
})(),
/**
* @description Custom event that fires at the start of a transaction
* @property startEvent
* @private
* @static
* @type CustomEvent
*/
startEvent: new YAHOO.util.CustomEvent('start'),
/**
* @description Custom event that fires when a transaction response has completed.
* @property completeEvent
* @private
* @static
* @type CustomEvent
*/
completeEvent: new YAHOO.util.CustomEvent('complete'),
/**
* @description Custom event that fires when handleTransactionResponse() determines a
* response in the HTTP 2xx range.
* @property successEvent
* @private
* @static
* @type CustomEvent
*/
successEvent: new YAHOO.util.CustomEvent('success'),
/**
* @description Custom event that fires when handleTransactionResponse() determines a
* response in the HTTP 4xx/5xx range.
* @property failureEvent
* @private
* @static
* @type CustomEvent
*/
failureEvent: new YAHOO.util.CustomEvent('failure'),
/**
* @description Custom event that fires when handleTransactionResponse() determines a
* response in the HTTP 4xx/5xx range.
* @property failureEvent
* @private
* @static
* @type CustomEvent
*/
uploadEvent: new YAHOO.util.CustomEvent('upload'),
/**
* @description Custom event that fires when a transaction is successfully aborted.
* @property abortEvent
* @private
* @static
* @type CustomEvent
*/
abortEvent: new YAHOO.util.CustomEvent('abort'),
/**
* @description A reference table that maps callback custom events members to its specific
* event name.
* @property _customEvents
* @private
* @static
* @type object
*/
_customEvents:
{
onStart:['startEvent', 'start'],
onComplete:['completeEvent', 'complete'],
onSuccess:['successEvent', 'success'],
onFailure:['failureEvent', 'failure'],
onUpload:['uploadEvent', 'upload'],
onAbort:['abortEvent', 'abort']
},
/**
* @description Member to add an ActiveX id to the existing xml_progid array.
* In the event(unlikely) a new ActiveX id is introduced, it can be added
* without internal code modifications.
* @method setProgId
* @public
* @static
* @param {string} id The ActiveX id to be added to initialize the XHR object.
* @return void
*/
setProgId:function(id)
{
this._msxml_progid.unshift(id);
YAHOO.log('ActiveX Program Id ' + id + ' added to _msxml_progid.', 'info', 'Connection');
},
/**
* @description Member to override the default POST header.
* @method setDefaultPostHeader
* @public
* @static
* @param {boolean} b Set and use default header - true or false .
* @return void
*/
setDefaultPostHeader:function(b)
{
if(typeof b == 'string'){
this._default_post_header = b;
YAHOO.log('Default POST header set to ' + b, 'info', 'Connection');
}
else if(typeof b == 'boolean'){
this._use_default_post_header = b;
}
},
/**
* @description Member to override the default transaction header..
* @method setDefaultXhrHeader
* @public
* @static
* @param {boolean} b Set and use default header - true or false .
* @return void
*/
setDefaultXhrHeader:function(b)
{
if(typeof b == 'string'){
this._default_xhr_header = b;
YAHOO.log('Default XHR header set to ' + b, 'info', 'Connection');
}
else{
this._use_default_xhr_header = b;
}
},
/**
* @description Member to modify the default polling interval.
* @method setPollingInterval
* @public
* @static
* @param {int} i The polling interval in milliseconds.
* @return void
*/
setPollingInterval:function(i)
{
if(typeof i == 'number' && isFinite(i)){
this._polling_interval = i;
YAHOO.log('Default polling interval set to ' + i +'ms', 'info', 'Connection');
}
},
/**
* @description Instantiates a XMLHttpRequest object and returns an object with two properties:
* the XMLHttpRequest instance and the transaction id.
* @method createXhrObject
* @private
* @static
* @param {int} transactionId Property containing the transaction id for this transaction.
* @return object
*/
createXhrObject:function(transactionId)
{
var obj,http;
try
{
// Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
http = new XMLHttpRequest();
// Object literal with http and tId properties
obj = { conn:http, tId:transactionId };
YAHOO.log('XHR object created for transaction ' + transactionId, 'info', 'Connection');
}
catch(e)
{
for(var i=0; i<this._msxml_progid.length; ++i){
try
{
// Instantiates XMLHttpRequest for IE and assign to http
http = new ActiveXObject(this._msxml_progid[i]);
// Object literal with conn and tId properties
obj = { conn:http, tId:transactionId };
YAHOO.log('ActiveX XHR object created for transaction ' + transactionId, 'info', 'Connection');
break;
}
catch(e){}
}
}
finally
{
return obj;
}
},
/**
* @description This method is called by asyncRequest to create a
* valid connection object for the transaction. It also passes a
* transaction id and increments the transaction id counter.
* @method getConnectionObject
* @private
* @static
* @return {object}
*/
getConnectionObject:function(isFileUpload)
{
var o;
var tId = this._transaction_id;
try
{
if(!isFileUpload){
o = this.createXhrObject(tId);
}
else{
o = {};
o.tId = tId;
o.isUpload = true;
}
if(o){
this._transaction_id++;
}
}
catch(e){}
finally
{
return o;
}
},
/**
* @description Method for initiating an asynchronous request via the XHR object.
* @method asyncRequest
* @public
* @static
* @param {string} method HTTP transaction method
* @param {string} uri Fully qualified path of resource
* @param {callback} callback User-defined callback function or object
* @param {string} postData POST body
* @return {object} Returns the connection object
*/
asyncRequest:function(method, uri, callback, postData)
{
var o = (this._isFileUpload)?this.getConnectionObject(true):this.getConnectionObject();
var args = (callback && callback.argument)?callback.argument:null;
if(!o){
YAHOO.log('Unable to create connection object.', 'error', 'Connection');
return null;
}
else{
// Intialize any transaction-specific custom events, if provided.
if(callback && callback.customevents){
this.initCustomEvents(o, callback);
}
if(this._isFormSubmit){
if(this._isFileUpload){
this.uploadFile(o, callback, uri, postData);
return o;
}
// If the specified HTTP method is GET, setForm() will return an
// encoded string that is concatenated to the uri to
// create a querystring.
if(method.toUpperCase() == 'GET'){
if(this._sFormData.length !== 0){
// If the URI already contains a querystring, append an ampersand
// and then concatenate _sFormData to the URI.
uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
}
}
else if(method.toUpperCase() == 'POST'){
// If POST data exist in addition to the HTML form data,
// it will be concatenated to the form data.
postData = postData?this._sFormData + "&" + postData:this._sFormData;
}
}
if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){
// If callback.cache is defined and set to false, a
// timestamp value will be added to the querystring.
uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString();
}
o.conn.open(method, uri, true);
// Each transaction will automatically include a custom header of
// "X-Requested-With: XMLHttpRequest" to identify the request as
// having originated from Connection Manager.
if(this._use_default_xhr_header){
if(!this._default_headers['X-Requested-With']){
this.initHeader('X-Requested-With', this._default_xhr_header, true);
YAHOO.log('Initialize transaction header X-Request-Header to XMLHttpRequest.', 'info', 'Connection');
}
}
//If the transaction method is POST and the POST header value is set to true
//or a custom value, initalize the Content-Type header to this value.
if((method.toUpperCase() == 'POST' && this._use_default_post_header) && this._isFormSubmit === false){
this.initHeader('Content-Type', this._default_post_header);
YAHOO.log('Initialize header Content-Type to application/x-www-form-urlencoded; UTF-8 for POST transaction.', 'info', 'Connection');
}
//Initialize all default and custom HTTP headers,
if(this._has_default_headers || this._has_http_headers){
this.setHeader(o);
}
this.handleReadyState(o, callback);
o.conn.send(postData || null);
YAHOO.log('Transaction ' + o.tId + ' sent.', 'info', 'Connection');
// Reset the HTML form data and state properties as
// soon as the data are submitted.
if(this._isFormSubmit === true){
this.resetFormState();
}
// Fire global custom event -- startEvent
this.startEvent.fire(o, args);
if(o.startEvent){
// Fire transaction custom event -- startEvent
o.startEvent.fire(o, args);
}
return o;
}
},
/**
* @description This method creates and subscribes custom events,
* specific to each transaction
* @method initCustomEvents
* @private
* @static
* @param {object} o The connection object
* @param {callback} callback The user-defined callback object
* @return {void}
*/
initCustomEvents:function(o, callback)
{
// Enumerate through callback.customevents members and bind/subscribe
// events that match in the _customEvents table.
for(var prop in callback.customevents){
if(this._customEvents[prop][0]){
// Create the custom event
o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null);
YAHOO.log('Transaction-specific Custom Event ' + o[this._customEvents[prop][1]] + ' created.', 'info', 'Connection');
// Subscribe the custom event
o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]);
YAHOO.log('Transaction-specific Custom Event ' + o[this._customEvents[prop][1]] + ' subscribed.', 'info', 'Connection');
}
}
},
/**
* @description This method serves as a timer that polls the XHR object's readyState
* property during a transaction, instead of binding a callback to the
* onreadystatechange event. Upon readyState 4, handleTransactionResponse
* will process the response, and the timer will be cleared.
* @method handleReadyState
* @private
* @static
* @param {object} o The connection object
* @param {callback} callback The user-defined callback object
* @return {void}
*/
handleReadyState:function(o, callback)
{
var oConn = this;
var args = (callback && callback.argument)?callback.argument:null;
if(callback && callback.timeout){
this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
}
this._poll[o.tId] = window.setInterval(
function(){
if(o.conn && o.conn.readyState === 4){
// Clear the polling interval for the transaction
// and remove the reference from _poll.
window.clearInterval(oConn._poll[o.tId]);
delete oConn._poll[o.tId];
if(callback && callback.timeout){
window.clearTimeout(oConn._timeOut[o.tId]);
delete oConn._timeOut[o.tId];
}
// Fire global custom event -- completeEvent
oConn.completeEvent.fire(o, args);
if(o.completeEvent){
// Fire transaction custom event -- completeEvent
o.completeEvent.fire(o, args);
}
oConn.handleTransactionResponse(o, callback);
}
}
,this._polling_interval);
},
/**
* @description This method attempts to interpret the server response and
* determine whether the transaction was successful, or if an error or
* exception was encountered.
* @method handleTransactionResponse
* @private
* @static
* @param {object} o The connection object
* @param {object} callback The user-defined callback object
* @param {boolean} isAbort Determines if the transaction was terminated via abort().
* @return {void}
*/
handleTransactionResponse:function(o, callback, isAbort)
{
var httpStatus, responseObject;
var args = (callback && callback.argument)?callback.argument:null;
try
{
if(o.conn.status !== undefined && o.conn.status !== 0){
httpStatus = o.conn.status;
}
else{
httpStatus = 13030;
}
}
catch(e){
// 13030 is a custom code to indicate the condition -- in Mozilla/FF --
// when the XHR object's status and statusText properties are
// unavailable, and a query attempt throws an exception.
httpStatus = 13030;
}
if(httpStatus >= 200 && httpStatus < 300 || httpStatus === 1223){
responseObject = this.createResponseObject(o, args);
if(callback && callback.success){
if(!callback.scope){
callback.success(responseObject);
YAHOO.log('Success callback. HTTP code is ' + httpStatus, 'info', 'Connection');
}
else{
// If a scope property is defined, the callback will be fired from
// the context of the object.
callback.success.apply(callback.scope, [responseObject]);
YAHOO.log('Success callback with scope. HTTP code is ' + httpStatus, 'info', 'Connection');
}
}
// Fire global custom event -- successEvent
this.successEvent.fire(responseObject);
if(o.successEvent){
// Fire transaction custom event -- successEvent
o.successEvent.fire(responseObject);
}
}
else{
switch(httpStatus){
// The following cases are wininet.dll error codes that may be encountered.
case 12002: // Server timeout
case 12029: // 12029 to 12031 correspond to dropped connections.
case 12030:
case 12031:
case 12152: // Connection closed by server.
case 13030: // See above comments for variable status.
responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false));
if(callback && callback.failure){
if(!callback.scope){
callback.failure(responseObject);
YAHOO.log('Failure callback. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection');
}
else{
callback.failure.apply(callback.scope, [responseObject]);
YAHOO.log('Failure callback with scope. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection');
}
}
break;
default:
responseObject = this.createResponseObject(o, args);
if(callback && callback.failure){
if(!callback.scope){
callback.failure(responseObject);
YAHOO.log('Failure callback. HTTP status code is ' + httpStatus, 'warn', 'Connection');
}
else{
callback.failure.apply(callback.scope, [responseObject]);
YAHOO.log('Failure callback with scope. HTTP status code is ' + httpStatus, 'warn', 'Connection');
}
}
}
// Fire global custom event -- failureEvent
this.failureEvent.fire(responseObject);
if(o.failureEvent){
// Fire transaction custom event -- failureEvent
o.failureEvent.fire(responseObject);
}
}
this.releaseObject(o);
responseObject = null;
},
/**
* @description This method evaluates the server response, creates and returns the results via
* its properties. Success and failure cases will differ in the response
* object's property values.
* @method createResponseObject
* @private
* @static
* @param {object} o The connection object
* @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
* @return {object}
*/
createResponseObject:function(o, callbackArg)
{
var obj = {};
var headerObj = {};
try
{
var headerStr = o.conn.getAllResponseHeaders();
var header = headerStr.split('\n');
for(var i=0; i<header.length; i++){
var delimitPos = header[i].indexOf(':');
if(delimitPos != -1){
headerObj[header[i].substring(0,delimitPos)] = header[i].substring(delimitPos+2);
}
}
}
catch(e){}
obj.tId = o.tId;
// Normalize IE's response to HTTP 204 when Win error 1223.
obj.status = (o.conn.status == 1223)?204:o.conn.status;
// Normalize IE's statusText to "No Content" instead of "Unknown".
obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText;
obj.getResponseHeader = headerObj;
obj.getAllResponseHeaders = headerStr;
obj.responseText = o.conn.responseText;
obj.responseXML = o.conn.responseXML;
if(callbackArg){
obj.argument = callbackArg;
}
return obj;
},
/**
* @description If a transaction cannot be completed due to dropped or closed connections,
* there may be not be enough information to build a full response object.
* The failure callback will be fired and this specific condition can be identified
* by a status property value of 0.
*
* If an abort was successful, the status property will report a value of -1.
*
* @method createExceptionObject
* @private
* @static
* @param {int} tId The Transaction Id
* @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
* @param {boolean} isAbort Determines if the exception case is caused by a transaction abort
* @return {object}
*/
createExceptionObject:function(tId, callbackArg, isAbort)
{
var COMM_CODE = 0;
var COMM_ERROR = 'communication failure';
var ABORT_CODE = -1;
var ABORT_ERROR = 'transaction aborted';
var obj = {};
obj.tId = tId;
if(isAbort){
obj.status = ABORT_CODE;
obj.statusText = ABORT_ERROR;
}
else{
obj.status = COMM_CODE;
obj.statusText = COMM_ERROR;
}
if(callbackArg){
obj.argument = callbackArg;
}
return obj;
},
/**
* @description Method that initializes the custom HTTP headers for the each transaction.
* @method initHeader
* @public
* @static
* @param {string} label The HTTP header label
* @param {string} value The HTTP header value
* @param {string} isDefault Determines if the specific header is a default header
* automatically sent with each transaction.
* @return {void}
*/
initHeader:function(label, value, isDefault)
{
var headerObj = (isDefault)?this._default_headers:this._http_headers;
headerObj[label] = value;
if(isDefault){
this._has_default_headers = true;
}
else{
this._has_http_headers = true;
}
},
/**
* @description Accessor that sets the HTTP headers for each transaction.
* @method setHeader
* @private
* @static
* @param {object} o The connection object for the transaction.
* @return {void}
*/
setHeader:function(o)
{
if(this._has_default_headers){
for(var prop in this._default_headers){
if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){
o.conn.setRequestHeader(prop, this._default_headers[prop]);
YAHOO.log('Default HTTP header ' + prop + ' set with value of ' + this._default_headers[prop], 'info', 'Connection');
}
}
}
if(this._has_http_headers){
for(var prop in this._http_headers){
if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){
o.conn.setRequestHeader(prop, this._http_headers[prop]);
YAHOO.log('HTTP header ' + prop + ' set with value of ' + this._http_headers[prop], 'info', 'Connection');
}
}
delete this._http_headers;
this._http_headers = {};
this._has_http_headers = false;
}
},
/**
* @description Resets the default HTTP headers object
* @method resetDefaultHeaders
* @public
* @static
* @return {void}
*/
resetDefaultHeaders:function(){
delete this._default_headers;
this._default_headers = {};
this._has_default_headers = false;
},
/**
* @description This method assembles the form label and value pairs and
* constructs an encoded string.
* asyncRequest() will automatically initialize the transaction with a
* a HTTP header Content-Type of application/x-www-form-urlencoded.
* @method setForm
* @public
* @static
* @param {string || object} form id or name attribute, or form object.
* @param {boolean} optional enable file upload.
* @param {boolean} optional enable file upload over SSL in IE only.
* @return {string} string of the HTML form field name and value pairs..
*/
setForm:function(formId, isUpload, secureUri)
{
// reset the HTML form data and state properties
this.resetFormState();
var oForm;
if(typeof formId == 'string'){
// Determine if the argument is a form id or a form name.
// Note form name usage is deprecated, but supported
// here for backward compatibility.
oForm = (document.getElementById(formId) || document.forms[formId]);
}
else if(typeof formId == 'object'){
// Treat argument as an HTML form object.
oForm = formId;
}
else{
YAHOO.log('Unable to create form object ' + formId, 'warn', 'Connection');
return;
}
// If the isUpload argument is true, setForm will call createFrame to initialize
// an iframe as the form target.
//
// The argument secureURI is also required by IE in SSL environments
// where the secureURI string is a fully qualified HTTP path, used to set the source
// of the iframe, to a stub resource in the same domain.
if(isUpload){
// Create iframe in preparation for file upload.
var io = this.createFrame(secureUri?secureUri:null);
// Set form reference and file upload properties to true.
this._isFormSubmit = true;
this._isFileUpload = true;
this._formNode = oForm;
return;
}
var oElement, oName, oValue, oDisabled;
var hasSubmit = false;
// Iterate over the form elements collection to construct the
// label-value pairs.
for (var i=0; i<oForm.elements.length; i++){
oElement = oForm.elements[i];
oDisabled = oElement.disabled;
oName = oElement.name;
oValue = oElement.value;
// Do not submit fields that are disabled or
// do not have a name attribute value.
if(!oDisabled && oName)
{
switch(oElement.type)
{
case 'select-one':
case 'select-multiple':
for(var j=0; j<oElement.options.length; j++){
if(oElement.options[j].selected){
if(window.ActiveXObject){
this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].attributes['value'].specified?oElement.options[j].value:oElement.options[j].text) + '&';
}
else{
this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].hasAttribute('value')?oElement.options[j].value:oElement.options[j].text) + '&';
}
}
}
break;
case 'radio':
case 'checkbox':
if(oElement.checked){
this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
}
break;
case 'file':
// stub case as XMLHttpRequest will only send the file path as a string.
case undefined:
// stub case for fieldset element which returns undefined.
case 'reset':
// stub case for input type reset button.
case 'button':
// stub case for input type button elements.
break;
case 'submit':
if(hasSubmit === false){
if(this._hasSubmitListener && this._submitElementValue){
this._sFormData += this._submitElementValue + '&';
}
else{
this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
}
hasSubmit = true;
}
break;
default:
this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
}
}
}
this._isFormSubmit = true;
this._sFormData = this._sFormData.substr(0, this._sFormData.length - 1);
YAHOO.log('Form initialized for transaction. HTML form POST message is: ' + this._sFormData, 'info', 'Connection');
this.initHeader('Content-Type', this._default_form_header);
YAHOO.log('Initialize header Content-Type to application/x-www-form-urlencoded for setForm() transaction.', 'info', 'Connection');
return this._sFormData;
},
/**
* @description Resets HTML form properties when an HTML form or HTML form
* with file upload transaction is sent.
* @method resetFormState
* @private
* @static
* @return {void}
*/
resetFormState:function(){
this._isFormSubmit = false;
this._isFileUpload = false;
this._formNode = null;
this._sFormData = "";
},
/**
* @description Creates an iframe to be used for form file uploads. It is remove from the
* document upon completion of the upload transaction.
* @method createFrame
* @private
* @static
* @param {string} optional qualified path of iframe resource for SSL in IE.
* @return {void}
*/
createFrame:function(secureUri){
// IE does not allow the setting of id and name attributes as object
// properties via createElement(). A different iframe creation
// pattern is required for IE.
var frameId = 'yuiIO' + this._transaction_id;
var io;
if(window.ActiveXObject){
io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
// IE will throw a security exception in an SSL environment if the
// iframe source is undefined.
if(typeof secureUri == 'boolean'){
io.src = 'javascript:false';
}
else if(typeof secureURI == 'string'){
// Deprecated
io.src = secureUri;
}
}
else{
io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
YAHOO.log('File upload iframe created. Id is:' + frameId, 'info', 'Connection');
},
/**
* @description Parses the POST data and creates hidden form elements
* for each key-value, and appends them to the HTML form object.
* @method appendPostData
* @private
* @static
* @param {string} postData The HTTP POST data
* @return {array} formElements Collection of hidden fields.
*/
appendPostData:function(postData)
{
var formElements = [];
var postMessage = postData.split('&');
for(var i=0; i < postMessage.length; i++){
var delimitPos = postMessage[i].indexOf('=');
if(delimitPos != -1){
formElements[i] = document.createElement('input');
formElements[i].type = 'hidden';
formElements[i].name = postMessage[i].substring(0,delimitPos);
formElements[i].value = postMessage[i].substring(delimitPos+1);
this._formNode.appendChild(formElements[i]);
}
}
return formElements;
},
/**
* @description Uploads HTML form, inclusive of files/attachments, using the
* iframe created in createFrame to facilitate the transaction.
* @method uploadFile
* @private
* @static
* @param {int} id The transaction id.
* @param {object} callback User-defined callback object.
* @param {string} uri Fully qualified path of resource.
* @param {string} postData POST data to be submitted in addition to HTML form.
* @return {void}
*/
uploadFile:function(o, callback, uri, postData){
// Each iframe has an id prefix of "yuiIO" followed
// by the unique transaction id.
var oConn = this;
var frameId = 'yuiIO' + o.tId;
var uploadEncoding = 'multipart/form-data';
var io = document.getElementById(frameId);
var args = (callback && callback.argument)?callback.argument:null;
// Track original HTML form attribute values.
var rawFormAttributes =
{
action:this._formNode.getAttribute('action'),
method:this._formNode.getAttribute('method'),
target:this._formNode.getAttribute('target')
};
// Initialize the HTML form properties in case they are
// not defined in the HTML form.
this._formNode.setAttribute('action', uri);
this._formNode.setAttribute('method', 'POST');
this._formNode.setAttribute('target', frameId);
if(this._formNode.encoding){
// IE does not respect property enctype for HTML forms.
// Instead it uses the property - "encoding".
this._formNode.setAttribute('encoding', uploadEncoding);
}
else{
this._formNode.setAttribute('enctype', uploadEncoding);
}
if(postData){
var oElements = this.appendPostData(postData);
}
// Start file upload.
this._formNode.submit();
// Fire global custom event -- startEvent
this.startEvent.fire(o, args);
if(o.startEvent){
// Fire transaction custom event -- startEvent
o.startEvent.fire(o, args);
}
// Start polling if a callback is present and the timeout
// property has been defined.
if(callback && callback.timeout){
this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
}
// Remove HTML elements created by appendPostData
if(oElements && oElements.length > 0){
for(var i=0; i < oElements.length; i++){
this._formNode.removeChild(oElements[i]);
}
}
// Restore HTML form attributes to their original
// values prior to file upload.
for(var prop in rawFormAttributes){
if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
if(rawFormAttributes[prop]){
this._formNode.setAttribute(prop, rawFormAttributes[prop]);
}
else{
this._formNode.removeAttribute(prop);
}
}
}
// Reset HTML form state properties.
this.resetFormState();
// Create the upload callback handler that fires when the iframe
// receives the load event. Subsequently, the event handler is detached
// and the iframe removed from the document.
var uploadCallback = function()
{
if(callback && callback.timeout){
window.clearTimeout(oConn._timeOut[o.tId]);
delete oConn._timeOut[o.tId];
}
// Fire global custom event -- completeEvent
oConn.completeEvent.fire(o, args);
if(o.completeEvent){
// Fire transaction custom event -- completeEvent
o.completeEvent.fire(o, args);
}
var obj = {};
obj.tId = o.tId;
obj.argument = callback.argument;
try
{
// responseText and responseXML will be populated with the same data from the iframe.
// Since the HTTP headers cannot be read from the iframe
obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:io.contentWindow.document.documentElement.textContent;
obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}
catch(e){}
if(callback && callback.upload){
if(!callback.scope){
callback.upload(obj);
YAHOO.log('Upload callback.', 'info', 'Connection');
}
else{
callback.upload.apply(callback.scope, [obj]);
YAHOO.log('Upload callback with scope.', 'info', 'Connection');
}
}
// Fire global custom event -- uploadEvent
oConn.uploadEvent.fire(obj);
if(o.uploadEvent){
// Fire transaction custom event -- uploadEvent
o.uploadEvent.fire(obj);
}
YAHOO.util.Event.removeListener(io, "load", uploadCallback);
setTimeout(
function(){
document.body.removeChild(io);
oConn.releaseObject(o);
YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection');
}, 100);
};
// Bind the onload handler to the iframe to detect the file upload response.
YAHOO.util.Event.addListener(io, "load", uploadCallback);
},
/**
* @description Method to terminate a transaction, if it has not reached readyState 4.
* @method abort
* @public
* @static
* @param {object} o The connection object returned by asyncRequest.
* @param {object} callback User-defined callback object.
* @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout.
* @return {boolean}
*/
abort:function(o, callback, isTimeout)
{
var abortStatus;
var args = (callback && callback.argument)?callback.argument:null;
if(o && o.conn){
if(this.isCallInProgress(o)){
// Issue abort request
o.conn.abort();
window.clearInterval(this._poll[o.tId]);
delete this._poll[o.tId];
if(isTimeout){
window.clearTimeout(this._timeOut[o.tId]);
delete this._timeOut[o.tId];
}
abortStatus = true;
}
}
else if(o && o.isUpload === true){
var frameId = 'yuiIO' + o.tId;
var io = document.getElementById(frameId);
if(io){
// Remove all listeners on the iframe prior to
// its destruction.
YAHOO.util.Event.removeListener(io, "load");
// Destroy the iframe facilitating the transaction.
document.body.removeChild(io);
YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection');
if(isTimeout){
window.clearTimeout(this._timeOut[o.tId]);
delete this._timeOut[o.tId];
}
abortStatus = true;
}
}
else{
abortStatus = false;
}
if(abortStatus === true){
// Fire global custom event -- abortEvent
this.abortEvent.fire(o, args);
if(o.abortEvent){
// Fire transaction custom event -- abortEvent
o.abortEvent.fire(o, args);
}
this.handleTransactionResponse(o, callback, true);
YAHOO.log('Transaction ' + o.tId + ' aborted.', 'info', 'Connection');
}
return abortStatus;
},
/**
* @description Determines if the transaction is still being processed.
* @method isCallInProgress
* @public
* @static
* @param {object} o The connection object returned by asyncRequest
* @return {boolean}
*/
isCallInProgress:function(o)
{
// if the XHR object assigned to the transaction has not been dereferenced,
// then check its readyState status. Otherwise, return false.
if(o && o.conn){
return o.conn.readyState !== 4 && o.conn.readyState !== 0;
}
else if(o && o.isUpload === true){
var frameId = 'yuiIO' + o.tId;
return document.getElementById(frameId)?true:false;
}
else{
return false;
}
},
/**
* @description Dereference the XHR instance and the connection object after the transaction is completed.
* @method releaseObject
* @private
* @static
* @param {object} o The connection object
* @return {void}
*/
releaseObject:function(o)
{
if(o && o.conn){
//dereference the XHR instance.
o.conn = null;
YAHOO.log('Connection object for transaction ' + o.tId + ' destroyed.', 'info', 'Connection');
//dereference the connection object.
o = null;
}
}
};
YAHOO.register("connection", YAHOO.util.Connect, {version: "2.4.1", build: "742"});
}, '2.4.1' ,{"requires": ["yui2-yahoo", "yui2-event"]});
|
{
'type': 'game', // game or console
'name': 'Breakout',
'authors': [ 'Nolan Bushnell', 'Steve Bristow'],
'company': ['Atari, Inc'],
'year': '1976',
'date': '13-05-1976', // Day, Month, Year
'headline': 'Break blocs!',
'resume': [
'Breakout é um jogo eletrônico para Arcade desenvolvido',
'pela Atari, Inc. Influenciado pelo pong, seu objetivo',
'é destruir todos os blocos da parte de cima',
'com uma bola, sem deixá-la cair, controlando uma barra na',
'parte de baixo da tela. Uma curiosidade é que o protótipo',
'foi feito por Steve Jobs e Woz, mais tarde, fundadores da apple.'
].join(''),
'full_text': [
'Breakout é um jogo eletrônico para Arcade desenvolvido pela Atari,',
'Inc e lançado em 13 de maio de 1976. Foi idealizado por Nolan Bushnell',
'e Steve Bristow e influenciado pelo jogo de arcade de 1972 Pong, também da Atari.',
'O jogo foi convertido para os consoles e atualizado como Super Breakout.',
'Além disso, Breakout foi a base e inspiração para livros, ',
'jogos, e o computador Apple II. No jogo, uma camada de tijolos são alinhados no topo da tela.',
'A bola passa pela tela, rebatendo nas paredes laterais e superiores da tela.',
'Quando um tijolo é atingido, a bola rebate de volta e o tijolo é destruído.',
'O jogador perde uma vida quando a bola toca a parte inferior da tela.',
'Para prevenir que isso aconteça, o jogador move uma paleta para rebater a bola',
'para cima, mantendo-a no jogo. O breakout foi baseado no Pong, mudando apenas a mecânica do jogo'
].join(''),
'thumbnail': 'thumbnail_example.png',
'main_img': {'name': 'main_picture.png', 'caption': "Flyer Breakout"},
'images': [
{'name': 'picture1.png', 'caption': "Gameplay do Breakout"},
{'name': 'picture2.png', 'caption': "Arcade do Breakout"},
{'name': 'picture3.png', 'caption': "Cartucho para Atari 2600"}
],
'video_gameplay': [
{'url': 'https://www.youtube.com/watch?v=JRAPnuwnpRs', 'caption': "Um vídeo de gameplay do Breakout", 'type': "youtube"} // type: youtube or vimeo
],
'demos': [
{'url': 'http://www.atari2600.com.br/Atari/Roms/0154/Breakout', 'caption': "Um simulador de breakout"}
],
'references': [
{'url': 'http://en.wikipedia.org/wiki/Breakout_%28video_game%29', 'caption': "Wikipédia"}
{'url': 'http://pt.slideshare.net/gabrielalonso927/breakout-1976', 'caption': "Slides"}
]
}
|
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';
import { EasySearch } from 'meteor/easy:search'
import { _ } from 'meteor/underscore';
// 스키마 임포트.
import { EventSchema } from '/imports/schemas/event.js';
// 컬렉션 익스포트.
export const Events = new Mongo.Collection('events');
// 컬렉션에 스키마 어태치.
Events.attachSchema(EventSchema);
// 검색용 인덱스 설정.
export const EventsIndex = new EasySearch.Index({
engine: new EasySearch.MongoDB({
sort: function () {
return { createdAt: -1 };
},
selector: function (searchObject, options, aggregation) {
let selector = this.defaultConfiguration().selector(searchObject, options, aggregation),
groupFilter = options.search.props.groupFilter;
if (_.isString(groupFilter) && !_.isEmpty(groupFilter)) {
selector.group = groupFilter;
}
return selector;
}
}),
collection: Events,
fields: ['title', 'createdAt'],
defaultSearchOptions: {
limit: 10
},
permission: () => {
//console.log(Meteor.userId());
return true;
}
});
// 서버에서만 실행.
if (Meteor.isServer) {
// 퍼블리싱.
Meteor.publish('events', function publication() {
return Events.find();
});
};
Meteor.methods({
'events.insert'(event) {
// check arguments.
check(event, {
title: String,
text: String,
start: String,
end: String,
titleImage: String,
eventImage: String
});
// Insert.
Events.insert(event, { clean: false, validate: true, filter: false }, function(error, result) {
if (error) {
console.log("Error:", error);
return error;
}
});
},
'events.findOne'(id) {
// Find(1).
check(id, String);
Events.findOne(id);
},
'events.update'(id, event) {
// check arguments.
check(id, String);
check(event, {
title: String,
text: String,
start: String,
end: String,
titleImage: String,
eventImage: String
});
// Update.
Events.update(id, {$set: event}, { clean: false, validate: true, filter: false }, function(error, result) {
if (error) {
console.log("Error:", error);
}
});
},
'events.remove'(id) {
// Remove.
check(id, String);
Events.remove(id);
},
});
|
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PostcardSchema = new mongoose.Schema({
user: [{ type: Schema.ObjectId, ref: 'User' }],
candidate: [{ type: Schema.ObjectId, ref: 'Candidate' }],
message: String,
state: [{ type: Schema.ObjectId, ref: 'State' }],
price: Number,
from: {
name: String,
street_address: String,
city: String,
state: String,
zip: Number
},
payment_id : String
});
module.exports = mongoose.model('Postcard', PostcardSchema);
|
"use strict"
var MINUTE = 60000
var EventEmitter = require('events')
var format = require('python-format')
var WebSocketClient = require('websocket').client
var request = require('request')
function objectHas(object, key) {
return Object.prototype.hasOwnProperty.call(object, key)
}
function copySafely(target, configuration, keys) {
var added = 0
for (var key in configuration) {
if (!objectHas(configuration, key)) return
if (!objectHas(keys, key)) {
throw new TypeError(format("Unrecognized key '{}'", key))
}
target[key] = configuration[key]
added += 1
}
if (added !== Object.keys(keys).length) {
var message = format("Expected {} keys, got {}.", keys.size, added)
throw new TypeError(message)
}
}
function Showdown(configuration) {
this.queue = Promise.resolve()
copySafely(this, configuration, Showdown.keys)
}
Showdown.keys = {
server: true,
serverport: true,
serverid: true,
nickname: true,
password: true,
room: true
}
Showdown.commands = new Map([
['challstr', 'finalize'],
['c:', 'onChatMessage'],
])
Showdown.prototype = new EventEmitter
Showdown.prototype.connect = function connect() {
var connection = new WebSocketClient
connection.on('connectFailed', this.onConnectionFailure.bind(this))
connection.on('connect', this.onConnect.bind(this))
var connectionString = this.getConnectionString()
connection.connect(connectionString, [])
}
Showdown.prototype.getConnectionString = function getConnectionString() {
return format(
'ws://{}:{}/showdown/websocket',
this.server,
this.serverport
)
}
Showdown.prototype.onConnectionFailure = function onConnectionFailure(error) {
console.error('Error occured (%s), will connect in a minute', error)
setTimeout(this.connect.bind(this), MINUTE)
}
Showdown.prototype.onConnect = function onConnect(connection) {
this.connection = connection
var onConnectionFailure = this.onConnectionFailure.bind(this)
connection.on('error', onConnectionFailure)
connection.on('close', onConnectionFailure)
connection.on('message', this.onMessage.bind(this))
console.info('Connected to Showdown server')
}
Showdown.prototype.onMessage = function onMessage(message) {
if (message.type !== 'utf8') return
this.parseMessage(message.utf8Data)
}
Showdown.prototype.parseMessage = function parseMessage(message) {
console.log(message)
var parts = message.split('|')
if (Showdown.commands.has(parts[1])) {
this[Showdown.commands.get(parts[1])](parts)
}
}
Showdown.prototype.finalize = function finalize(parts) {
var id = parts[2]
var str = parts[3]
var nickname = this.nickname
var password = this.password
request.post(
format('https://play.pokemonshowdown.com/~~{}/action.php', this.serverid),
{
form: {
act: 'login',
challengekeyid: id,
challenge: str,
name: nickname,
pass: password
}
},
function finish(error, response, body) {
var result = JSON.parse(body.replace(/^]/, ""))
var assertion = result.assertion
var command = format('/trn {},0,{}', nickname, assertion)
this.report(command)
this.report('/join ' + this.room)
this.report('/away')
}.bind(this)
)
}
Showdown.prototype.onChatMessage = function onChatMessage(parts) {
this.emit('message', parts[3], parts.slice(4).join('|'))
}
Showdown.prototype.report = function report(message) {
this.queue = this.queue.then(() => {
this.connection.send(`${this.room}|${message}`)
return new Promise(resolve => {
setTimeout(resolve, 500)
})
})
}
module.exports = Showdown
|
var HOME = "app_dev.php/";
var first_time = 1;
var app_container = $("#backbone_container");
function showPrettyBackground()
{
$('<canvas class="blur" src='+canvasbg+' width="500" height="357">').appendTo( $('#container') );
$(".blur").each(function()
{
var element = this;
var img = new Image;
img.onload = function() {
t = new CanvasImage(element, this);
t.blur(5);
};
img.src = $(this).attr("src");
});
$('.blur').animate({
opacity: 0.7
}, 1000, function() {});
}
function firstTime()
{
$('#container').removeClass('hide');
setTimeout(showPrettyBackground, 200);
$('#html_container').animate({
opacity: 1
}, 300, function() {});
first_time = 0;
}
$(function()
{
var doc_width = $('#below_header').width();
var animeteLogoInterval = null;
var template = function(template, data) {
return _.template( $("#" + template).html(), data );
}
var animateLogo = function() {
$('.logo').animate({
'background-position-y': '26'
}, 1000, function() {
$('.logo').css('background-position-y', '0');
})
}
$(document).ajaxStop(function() {
$("html, body").animate({ scrollTop: 0 }, "fast");
});
$('#html_container').css('opacity', 0.1);
$('#html_container').html('');
window.App = {
Models: {},
Views: {},
Collections: {},
Router: {}
}
App.Models.Post = Backbone.Model.extend({
url: Routing.generate('blog_getarticles')
});
App.Collections.Posts = Backbone.Collection.extend({
model: App.Models.Post,
url: Routing.generate('blog_getarticles')
});
App.Views.Page = Backbone.View.extend({
initialize: function(options) {
this.options = options;
this.events = _.extend({}, App.Views.Page.prototype.events, this.events)
this.render();
},
events: {
'click a[data-href]': function(e) {
approuter.navigate( $(e.target).attr('href'), true );
e.preventDefault();
}
},
doStuffAfterFetch: function() {
if (first_time == 1) {
firstTime();
} else {
window.clearInterval(animeteLogoInterval);
$('#below_header').animate({
'margin-right': '0px',
'opacity': 1
}, 200);
}
}
});
App.Views.PostListSingle = App.Views.Page.extend({
template: template("article_list_single"),
render: function() {
this.$el.html( this.template({ article: this.model.toJSON() }));
return this;
}
})
App.Views.PostList = App.Views.Page.extend({
render: function()
{
var self = this;
var opt = {};
if (this.options.tag) {
opt.tag = this.options.tag;
}
self.options.collection.fetch({
data: $.param( opt ),
success: function()
{
self.$el.empty();
$('#comments_container').empty();
self.options.collection.each(function(post) {
var postView = new App.Views.PostListSingle({ model: post });
self.$el.append( postView.render().el );
});
self.doStuffAfterFetch();
}
});
}
})
App.Views.PostSingle = App.Views.Page.extend({
render: function()
{
var self = this;
self.options.model.fetch({
data: $.param({ id: this.options.id }),
success: function()
{
var article = template("article_single", { data: self.options.model.toJSON() } );
var comments = template("article_comments", { data: self.options.model.toJSON() } );
self.$el.html( article );
$('#comments_container').html( comments );
self.doStuffAfterFetch();
}
});
}
});
App.Router = Backbone.Router.extend({
initialize: function() {
this.bind("all", this.change)
},
change: function() {
if (!first_time) {
animateLogo();
animeteLogoInterval = setInterval(animateLogo, 1000);
$('#below_header').animate({
'margin-right': '30px',
'opacity': 0.5
}, 200);
}
},
routes: {
"app_dev.php/post/:id": "getPost",
"app_dev.php/tag/:id": "getPostsWithTag",
"*actions": "getIndex"
}
});
var approuter = new App.Router();
approuter.on('route:getIndex', function() {
new App.Views.PostList({ el: $("#html_container"), collection: new App.Collections.Posts });
});
approuter.on('route:getPostsWithTag', function(tag) {
new App.Views.PostList({ el: $("#html_container"), collection: new App.Collections.Posts, tag: tag });
});
approuter.on('route:getPost', function(link) {
new App.Views.PostSingle({ el: $("#html_container"), model: new App.Models.Post, id: link });
});
App.Views.Header = Backbone.View.extend({
el: '#header',
events: {
'click .logo': function(e) {
approuter.navigate( Routing.generate('blog_homepage'), true );
e.preventDefault();
}
}
})
new App.Views.Header;
Backbone.history.start({ pushState: true });
});
|
import * as Fathom from 'fathom-client';
function getSupport() {
window.open('https://github.com/gotdibbs/Dynamics-365-Toolkit/issues/', '_new');
Fathom.trackGoal('GFT1EFPR', 0);
}
export default {
action: getSupport,
key: 'get-support',
title: 'Get Support',
description: 'Takes you to a form to submit an issue or request.',
requiresForm: false
};
|
'use strict';
import Mraa from 'mraa';
import config from 'config';
import logger from './logger';
const Gate = function () {
const { port, time } = config.get('gate');
Mraa.init();
const pin = new Mraa.Gpio(port);
pin.dir(Mraa.DIR_OUT);
let timeout;
this.open = () => {
logger.info('requesting gate open');
pin.write(1);
clearTimeout(timeout);
timeout = setTimeout(this.close, time);
};
this.close = () => {
logger.info('requesting gate close');
pin.write(0);
};
};
export default Gate;
|
/**
* deck_info.js
*
*/
// Object literal which encapsulates: rating selectors
DeckInfoUI = {
deck:null,
table:null,
resultsTable:null,
RATING_MAP:new Array("unrated","easy","medium","hard"),
CARD_ID_INDEX:1,
'init':function() {
// Pass global deck JSON data
this.deck = new Deck(deckData, cardData, cardResultsData);
// Setup RTS
this.setupRts();
},
'setupRts':function() {
// Setup RTS elements on card list tab
this.table = $("div#cards_tab table.deck_table tr.card_row");
this.bindRts(this.table);
// Setup RTS elements on quiz results tab
this.resultsTable = $("div#results_tab table.deck_table tr.card_row");
this.bindRts(this.resultsTable);
},
// Function which binds an RTS element to rows in a table
'bindRts':function(table) {
if(!table) {
return;
}
// Set variable for scope within closure
var obj = this;
// For every row in the table add an RTS
table.each(function() {
// Get ID of card from class attribute
var cArr = ($(this).attr("class")).split(" ");
var idArr = cArr[obj.CARD_ID_INDEX].split("_");
var id = idArr[idArr.length-1];
// Insert widget into DOM
var elt = $("td.rts_col", this);
var rts = new RatingSelector(elt);
// Hide rts
var rtsElt = $("ul.rts", this);
rtsElt.css({display:"none"});
// Bind card to RTS widget
var c = obj.deck.getCard(id);
rts.setCard(c);
// Bind DOM rating field to widget
var ratingElt = $("span.rating", this);
rts.setRatingElt(ratingElt);
});
},
// Adds card counts to checkboxes
// Disables all checkboxes with '(0)' aka zero cards
'refreshCheckboxCounts':function() {
// Rating counts
var ratingCounts = this.deck.getRatingCounts();
// Set the total number of cards
var totalCards = this.deck.getNumCards();
var allCardsStr = "All (" + totalCards + ")";
$("div#category_select label[for=select_all_checkbox]").text(allCardsStr);
// Closure object
var obj = this;
// Disable checkboxes that have zero cards
$("div#category_select div.checkbox").each(function() {
// Get rating count for this label
var label = $("label", this);
var origLabelStr = label.text().split(" ")[0];
var ratingStr = origLabelStr.toLowerCase();
var rating = jQuery.inArray(ratingStr, obj.RATING_MAP);
var ratingCount = ratingCounts[rating];
var labelStr;
if(ratingCount > 0) {
labelStr = origLabelStr + " (" + ratingCount + ")";
label.text(labelStr);
$("input", this).removeAttr('disabled');
$("label", this).removeAttr('class');
$("input", this).attr('checked','checked'); // auto-select
// Uncheck previous if there is medium or hard
if(ratingStr == 'medium') {
$("input", $(this).prev()).attr('checked','');
}
if(ratingStr == 'hard') {
$("input", $(this).prev()).attr('checked','');
$("input", $(this).prev().prev()).attr('checked','');
}
}
else {
labelStr = origLabelStr + " (0)";
label.text(labelStr);
$("input", this).attr('disabled', true);
$("label", this).attr('class', 'disabled');
}
});
},
// On-click handler for selecting all checkboxes
'selectAllCheckboxes':function() {
var isChecked = $("input#select_all_checkbox").is(':checked');
$("div#category_select input[type='checkbox']:not(:disabled)").attr('checked', isChecked);
},
// Onclick handler for the 'Quiz' button
// Sets hidden field value to '1'
'setQuizMode':function() {
var trueVal = 1;
$("div#mode_select input#DeckIsQuizMode").val(trueVal);
},
// Onclick handler for the 'Learn' button
// Sets hidden field value to '0'
'setLearnMode':function() {
var falseVal = 0;
$("div#mode_select input#DeckIsQuizMode").val(falseVal);
},
// Onclick handler when Edit rating is clicked
'toggleRatingEdit':function(obj, isResultsTab) {
var editTxt = 'Edit Difficulties';
var updateTxt = 'Save Difficulties';
var modeEdit = true;
// Change 'Edit' text
var ctrlElt = $(obj);
var text = ctrlElt.text();
if(text == editTxt) {
ctrlElt.text(updateTxt);
}
else {
ctrlElt.text(editTxt);
modeEdit = false;
// Trigger save
this.deck.writeSession();
// Add card counts for each rating;
// Disable checkboxes for ratings with no cards
DeckInfoUI.refreshCheckboxCounts();
}
var table = this.table;
if(isResultsTab) {
table = this.resultsTable;
}
// Display/hide rating selectors
table.each(function() {
var elt = $("td.rts_col", this);
if(modeEdit) {
$("ul.rts",elt).css({display:""});
$("span.rating",elt).css({display:"none"});
}
else {
$("ul.rts",elt).css({display:"none"});
$("span.rating",elt).css({display:""});
}
});
}
} // End DeckInfoUI object
$(document).ready( function() {
// Toggle edit rating mode
DeckInfoUI.init();
// Add card counts for each rating;
// Disable checkboxes for ratings with no cards
DeckInfoUI.refreshCheckboxCounts();
// Round corners
//$("div#middle").corner();
//$("div#bottom").corner();
// Setup tabs
$("#bottom").tabs();
// Auto-select the review tab if present
$("#bottom").tabs('select',2);
// Set on-click handlers for quiz/learn mode
$("input#quiz_button").click(function() { DeckInfoUI.setQuizMode(); });
$("input#learn_button").click(function() { DeckInfoUI.setLearnMode(); });
// Set on-click handler for select 'All' checkbox
$("input#select_all_checkbox").click(function() { DeckInfoUI.selectAllCheckboxes(); });
// Set onclick for rating selector
$("div#cards_tab th.edit_rating button").click(function() { DeckInfoUI.toggleRatingEdit(this); });
$("div#results_tab th.edit_rating button").click(function() { DeckInfoUI.toggleRatingEdit(this, true); });
});
|
import Theme from '../../../src/utils/theme';
function getHighlightResult(
fillMode,
color,
isDark,
bgClass = '',
contentClass = '',
) {
let styles = {};
let classes = {};
if (bgClass) {
classes.class = bgClass;
}
if (contentClass) {
classes.contentClass = contentClass;
}
switch (fillMode) {
case 'none': {
styles = {
style: {
backgroundColor: isDark ? 'var(--gray-900)' : 'var(--white)',
border: '2px solid',
borderColor: isDark ? `var(--${color}-200)` : `var(--${color}-700)`,
borderRadius: 'var(--rounded-full)',
},
contentStyle: {
color: isDark ? `var(--${color}-100)` : `var(--${color}-900)`,
fontWeight: 'var(--font-bold)',
},
};
break;
}
case 'light': {
styles = {
style: {
backgroundColor: isDark
? `var(--${color}-800)`
: `var(--${color}-200)`,
opacity: isDark ? 0.75 : 1,
borderRadius: 'var(--rounded-full)',
},
contentStyle: {
color: isDark ? `var(--${color}-100)` : `var(--${color}-900)`,
fontWeight: 'var(--font-bold)',
},
};
break;
}
case 'solid': {
styles = {
style: {
backgroundColor: isDark
? `var(--${color}-500)`
: `var(--${color}-600)`,
borderRadius: 'var(--rounded-full)',
},
contentStyle: {
color: 'var(--white)',
fontWeight: 'var(--font-bold)',
},
};
break;
}
}
return {
fillMode,
color,
isDark,
...styles,
};
}
describe('Theme', () => {
const lightTheme = new Theme({ color: 'blue', isDark: false });
const darkTheme = new Theme({ color: 'red', isDark: true });
const themes = [lightTheme, darkTheme];
themes.forEach(theme => {
// Check highlight with `true`
it('should create highlight with `true`', () => {
const highlight = theme.normalizeHighlight(true);
const targets = {
base: 'light',
start: 'solid',
end: 'solid',
};
Object.entries(targets).forEach(([t, fillMode]) => {
expect(highlight[t]).toEqual(
getHighlightResult(fillMode, theme.color, theme.isDark),
);
});
});
// Check highlights with fill modes
const fillModes = ['none', 'light', 'solid'];
fillModes.forEach(fillMode => {
it('should create highlight with fillMode = ' + fillMode, () => {
const highlight = theme.normalizeHighlight({ fillMode });
['base', 'start', 'end'].forEach(t => {
expect(highlight[t]).toEqual(
getHighlightResult(fillMode, theme.color, theme.isDark),
);
});
});
});
// Check highlights with class
it('should create highlight with `class`', () => {
const config = {
class: 'highlight_class',
};
const highlight = theme.normalizeHighlight(config);
['base', 'start', 'end'].forEach(t => {
expect(highlight[t].class).toEqual(config.class);
});
});
// Check highlights with content class
it('should create highlight with `contentClass`', () => {
const config = {
contentClass: 'highlight_content_class',
};
const highlight = theme.normalizeHighlight(config);
['base', 'start', 'end'].forEach(t => {
expect(highlight[t].contentClass).toEqual(config.contentClass);
});
});
// Check highlights with `style`
it('should create highlight with `style`', () => {
const config = {
style: {
backgroundColor: '#fafafa',
opacity: 1,
pointerEvents: 'none',
},
};
const highlight = theme.normalizeHighlight(config);
['base', 'start', 'end'].forEach(t => {
Object.entries(config.style).forEach(([p, v]) => {
expect(highlight[t].style[p]).toEqual(v);
});
});
});
// Check highlights with `contentStyle`
it('should create highlight with `contentStyle`', () => {
const config = {
contentStyle: {
color: '#fafafa',
opacity: 0.5,
},
};
const highlight = theme.normalizeHighlight(config);
['base', 'start', 'end'].forEach(t => {
Object.entries(config.contentStyle).forEach(([p, v]) => {
expect(highlight[t].contentStyle[p]).toEqual(v);
});
});
});
// Check highlights with classes and styles
it('should create highlight with classes and styles', () => {
const config = {
class: 'highlight_class',
contentClass: 'highlight_content_class',
style: {
backgroundColor: '#fafafa',
opacity: 1,
pointerEvents: 'none',
},
contentStyle: {
color: '#fafafa',
opacity: 0.5,
},
};
const highlight = theme.normalizeHighlight(config);
['base', 'start', 'end'].forEach(t => {
expect(highlight[t].class).toEqual(config.class);
expect(highlight[t].contentClass).toEqual(config.contentClass);
Object.entries(config.style).forEach(([p, v]) => {
expect(highlight[t].style[p]).toEqual(v);
});
Object.entries(config.contentStyle).forEach(([p, v]) => {
expect(highlight[t].contentStyle[p]).toEqual(v);
});
});
});
});
});
|
var express = require('express'),
fs = require('fs'),
app = express();
var cors = require('cors');
var app = express();
app.use(cors());
var ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
app.get('http://quarkus-customer-service:8080/customers', function(req, res) {
res.send(res.json());
});
app.listen(8080, ip);
module.exports = app;
|
/**
* Select the text of an element.
*
* @param {htmlelement} $el - The element.
* @return {undefined} - Nothing.
*
* @resource [https://www.sanwebe.com/2014/04/select-all-text-in-element-on-click]
*/
var selection = function($el) {
// Clear any current selection.
selection.clear();
// Create the selection...
var sel, range;
if (window.getSelection && document.createRange) {
//Browser compatibility
sel = window.getSelection();
if (sel.toString() === "") {
//no text selection
window.setTimeout(function() {
range = document.createRange(); //range object
range.selectNodeContents($el); //sets Range
sel.removeAllRanges(); //remove all ranges from selection
sel.addRange(range); //add Range to a Selection.
}, 1);
}
} else if (document.selection) {
//older ie
sel = document.selection.createRange();
if (sel.text === "") {
//no text selection
range = document.body.createTextRange(); //Creates TextRange object
range.moveToElementText($el); //sets Range
range.select(); //make selection.
}
}
};
selection.clear = function() {
// First clear any current range selection.
// [https://stackoverflow.com/a/3171348]
var sel = window.getSelection
? window.getSelection()
: document.selection;
if (sel) {
if (sel.removeAllRanges) {
sel.removeAllRanges();
} else if (sel.empty) {
sel.empty();
}
}
};
|
import {throttle} from 'lodash'
// use like this within a react component:
// constructor(props){
// super(props)
// rerenderOnWindowResize(this)
// }
export default function rerenderOnWindowResize(that) {
that.updateDimensions = throttle(() => {
if (that.props.disabled) return
that.forceUpdate()
}, 250);
const componentDidMount = that.componentDidMount
const componentWillUnmount = that.componentWillUnmount
that.componentDidMount = (...args)=> {
componentDidMount && componentDidMount.bind(that)(...args)
window.addEventListener("resize", that.updateDimensions);
}
that.componentWillUnmount = (...args)=> {
componentWillUnmount && componentWillUnmount.bind(that)(...args)
window.removeEventListener("resize", that.updateDimensions);
}
}
|
/*
Get value at location described by dot notion path
*/
import pathway from './pathway'
export const get = (obj, path) => {
path = pathway.split(path)
path.some((key, i) => {
if (typeof obj !== 'object') throw Error(`Get path '${path.join('.')}' cannot navigate past key '${path[i - 1]}', '${path[i - 1]}' is non-object value '${obj}'.`)
obj = obj[key]
return Boolean(obj === undefined) // Stop navigating the path if we get to undefined value
})
return obj
}
export default get
|
var io = require('cheerio');
var reader = {
readPart: function(body, index) {
var $ = io.load(body);
var part = { };
var title = '';
var items = [];
$('#divMiddleList > div:nth-child(' + index + ')').each(function (index, object) {
title = $(object).find('span.brand').text();
});
$('#divMiddleList > div:nth-child(' + (++index) + ') > div.song_item').each(function (index, object) {
var image = $(object).find('div.song_item_img > a > img').attr('src') || $(object).find('div.song_item_img > img').attr('src');
var title = $(object).find('div.song_item_title > a').text();
var link = $(object).find('div.song_item_title > a').attr('href');
var artiste = $(object).find('div.song_item_artist > a').text();
var tag = $(object).find('div.song_item_tag > a').text();
var song = $(object).find('div.song_item_playa > div.playa').attr('rel') || '';
var item = {
'link': 'http://www.livingelectro.com/' + link,
'image': 'http://www.livingelectro.com/' + image,
'title': title,
'artiste': artiste,
'tag': tag,
'song': song
};
items.push(item);
});
part[title] = items;
return part;
},
readDownloadLink: function (body, completion) {
var $ = io.load(body);
$('div.song_download_link').each(function (index, object) {
var song = $(object).find('a').attr('href');
completion(song);
});
}
};
module.exports = reader;
|
import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import QueueAnim from 'rc-queue-anim';
const mWidthStyle = {
minWidth: '135px'
};
const Section1 = () => (
<div className="container-fluid with-maxwidth">
<article className="article">
<h2 className="article-title">Basic</h2>
<div className="box box-default">
<div className="box-body">
<div className="call-to-action cta-inline">
<div className="cta-inner">
<span className="cta-text">Download it now and get up and running in minutes</span>
<div className="cta-btn">
<RaisedButton style={mWidthStyle} label="Free Download" secondary />
</div>
</div>
</div>
</div>
</div>
</article>
</div>
);
const Section2 = () => (
<div>
<div className="container-fluid with-maxwidth">
<article className="article no-margin-bttom">
<h2 className="article-title">Full Width (Inline)</h2>
</article>
</div>
<div className="call-to-action cta-inline cta-full-width card-white">
<div className="cta-inner">
<span className="cta-text">Download it now and get up and running in minutes</span>
<div className="cta-btn">
<RaisedButton style={mWidthStyle} label="Free Download" secondary />
</div>
</div>
</div>
<div className="divider" />
</div>
);
const Section3 = () => (
<div>
<div className="container-fluid with-maxwidth">
<article className="article no-margin-bttom">
<h2 className="article-title">Full Width</h2>
</article>
</div>
<div className="call-to-action cta-full-width card-white">
<div className="cta-inner">
<span className="cta-text">Download it now and get up and running in minutes</span>
<div className="cta-btn">
<RaisedButton style={mWidthStyle} label="Free Download" secondary />
</div>
<div className="cta-muted">No spam! We promise, only the best stuff.</div>
</div>
</div>
<div className="divider" />
</div>
);
const Section4 = () => (
<div>
<div className="container-fluid with-maxwidth">
<article className="article no-margin-bttom">
<h2 className="article-title">Image Background</h2>
</article>
</div>
<div className="call-to-action cta-bg-img cta-full-width" style={{backgroundImage: 'url(assets/images-demo/covers/photo-1456374407032-6e4baf58fb62.jpg)'}}>
<div className="cta-inner">
<span className="cta-text">Download it now and get up and running in minutes</span>
<div className="cta-btn">
<RaisedButton style={mWidthStyle} label="Free Download" secondary />
</div>
<div className="cta-muted">No spam! We promise, only the best stuff.</div>
</div>
</div>
</div>
);
const CallToActions = () => (
<section className="chapter">
<QueueAnim type="bottom" className="ui-animate">
<div key="1"><Section1 /></div>
<div key="2"><Section2 /></div>
<div key="3"><Section3 /></div>
<div key="4"><Section4 /></div>
</QueueAnim>
</section>
);
module.exports = CallToActions;
|
/* ===================================================
* bootstrap-transition.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#transitions
* ===================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
* ======================================================= */
$(function () {
$.support.transition = (function () {
var transitionEnd = (function () {
var el = document.createElement('bootstrap')
, transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd'
, 'MozTransition' : 'transitionend'
, 'OTransition' : 'oTransitionEnd otransitionend'
, 'transition' : 'transitionend'
}
, name
for (name in transEndEventNames){
if (el.style[name] !== undefined) {
return transEndEventNames[name]
}
}
}())
return transitionEnd && {
end: transitionEnd
}
})()
})
}(window.jQuery);
/* ============================================================
* bootstrap-dropdown.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* DROPDOWN CLASS DEFINITION
* ========================= */
var toggle = '[data-toggle=dropdown]'
, Dropdown = function (element) {
var $el = $(element).on('click.dropdown.data-api', this.toggle)
$('html').on('click.dropdown.data-api', function () {
$el.parent().removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown
, toggle: function (e) {
var $this = $(this)
, $parent
, isActive
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
$parent.toggleClass('open')
$this.focus()
}
return false
}
, keydown: function (e) {
var $this
, $items
, $active
, $parent
, isActive
, index
if (!/(38|40|27)/.test(e.keyCode)) return
$this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) return $this.click()
$items = $('[role=menu] li:not(.divider) a', $parent)
if (!$items.length) return
index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items
.eq(index)
.focus()
}
}
function clearMenus() {
$(toggle).each(function () {
getParent($(this)).removeClass('open')
})
}
function getParent($this) {
var selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
return $parent
}
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
$.fn.dropdown = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
/* APPLY TO STANDARD DROPDOWN ELEMENTS
* =================================== */
$(document)
.on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus)
.on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.dropdown.data-api touchstart.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
.on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
}(window.jQuery);
/* =============================================================
* bootstrap-scrollspy.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#scrollspy
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ============================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* SCROLLSPY CLASS DEFINITION
* ========================== */
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
, $element = $(element).is('body') ? $(window) : $(element)
, href
this.options = $.extend({}, $.fn.scrollspy.defaults, options)
this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.$body = $('body')
this.refresh()
this.process()
}
ScrollSpy.prototype = {
constructor: ScrollSpy
, refresh: function () {
var self = this
, $targets
this.offsets = $([])
this.targets = $([])
$targets = this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
, href = $el.data('target') || $el.attr('href')
, $href = /^#\w/.test(href) && $(href)
return ( $href
&& $href.length
&& [[ $href.position().top, href ]] ) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
, process: function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
, scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
, maxScroll = scrollHeight - this.$scrollElement.height()
, offsets = this.offsets
, targets = this.targets
, activeTarget = this.activeTarget
, i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0])
&& this.activate ( i )
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate( targets[i] )
}
}
, activate: function (target) {
var active
, selector
this.activeTarget = target
$(this.selector)
.parent('.active')
.removeClass('active')
selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
active = $(selector)
.parent('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active.closest('li.dropdown').addClass('active')
}
active.trigger('activate')
}
}
/* SCROLLSPY PLUGIN DEFINITION
* =========================== */
$.fn.scrollspy = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('scrollspy')
, options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
/* SCROLLSPY DATA-API
* ================== */
$(window).on('load', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(window.jQuery);
/* ========================================================
* bootstrap-tab.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#tabs
* ========================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ======================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* TAB CLASS DEFINITION
* ==================== */
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype = {
constructor: Tab
, show: function () {
var $this = this.element
, $ul = $this.closest('ul:not(.dropdown-menu)')
, selector = $this.attr('data-target')
, previous
, $target
, e
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ( $this.parent('li').hasClass('active') ) return
previous = $ul.find('.active:last a')[0]
e = $.Event('show', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
$target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown'
, relatedTarget: previous
})
})
}
, activate: function ( element, container, callback) {
var $active = container.find('> .active')
, transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if ( element.parent('.dropdown-menu') ) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active.one($.support.transition.end, next) :
next()
$active.removeClass('in')
}
}
/* TAB PLUGIN DEFINITION
* ===================== */
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('tab')
if (!data) $this.data('tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
/* TAB DATA-API
* ============ */
$(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
$(this).tab('show')
})
}(window.jQuery);
/* ==========================================================
* bootstrap-alert.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#alerts
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* ALERT CLASS DEFINITION
* ====================== */
var dismiss = '[data-dismiss="alert"]'
, Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype.close = function (e) {
var $this = $(this)
, selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
e && e.preventDefault()
$parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent())
$parent.trigger(e = $.Event('close'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
$parent
.trigger('closed')
.remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent.on($.support.transition.end, removeElement) :
removeElement()
}
/* ALERT PLUGIN DEFINITION
* ======================= */
$.fn.alert = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('alert')
if (!data) $this.data('alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
/* ALERT DATA-API
* ============== */
$(document).on('click.alert.data-api', dismiss, Alert.prototype.close)
}(window.jQuery);
/* =============================================================
* bootstrap-collapse.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#collapse
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* COLLAPSE PUBLIC CLASS DEFINITION
* ================================ */
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.collapse.defaults, options)
if (this.options.parent) {
this.$parent = $(this.options.parent)
}
this.options.toggle && this.toggle()
}
Collapse.prototype = {
constructor: Collapse
, dimension: function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
, show: function () {
var dimension
, scroll
, actives
, hasData
if (this.transitioning) return
dimension = this.dimension()
scroll = $.camelCase(['scroll', dimension].join('-'))
actives = this.$parent && this.$parent.find('> .accordion-group > .in')
if (actives && actives.length) {
hasData = actives.data('collapse')
if (hasData && hasData.transitioning) return
actives.collapse('hide')
hasData || actives.data('collapse', null)
}
this.$element[dimension](0)
this.transition('addClass', $.Event('show'), 'shown')
$.support.transition && this.$element[dimension](this.$element[0][scroll])
}
, hide: function () {
var dimension
if (this.transitioning) return
dimension = this.dimension()
this.reset(this.$element[dimension]())
this.transition('removeClass', $.Event('hide'), 'hidden')
this.$element[dimension](0)
}
, reset: function (size) {
var dimension = this.dimension()
this.$element
.removeClass('collapse')
[dimension](size || 'auto')
[0].offsetWidth
this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')
return this
}
, transition: function (method, startEvent, completeEvent) {
var that = this
, complete = function () {
if (startEvent.type == 'show') that.reset()
that.transitioning = 0
that.$element.trigger(completeEvent)
}
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
this.transitioning = 1
this.$element[method]('in')
$.support.transition && this.$element.hasClass('collapse') ?
this.$element.one($.support.transition.end, complete) :
complete()
}
, toggle: function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
}
/* COLLAPSIBLE PLUGIN DEFINITION
* ============================== */
$.fn.collapse = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('collapse')
, options = typeof option == 'object' && option
if (!data) $this.data('collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.defaults = {
toggle: true
}
$.fn.collapse.Constructor = Collapse
/* COLLAPSIBLE DATA-API
* ==================== */
$(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
var $this = $(this), href
, target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
, option = $(target).data('collapse') ? 'toggle' : $this.data()
$this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
$(target).collapse(option)
})
}(window.jQuery);
/* ==========================================================
* bootstrap-carousel.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#carousel
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* CAROUSEL CLASS DEFINITION
* ========================= */
var Carousel = function (element, options) {
this.$element = $(element)
this.options = options
this.options.slide && this.slide(this.options.slide)
this.options.pause == 'hover' && this.$element
.on('mouseenter', $.proxy(this.pause, this))
.on('mouseleave', $.proxy(this.cycle, this))
}
Carousel.prototype = {
cycle: function (e) {
if (!e) this.paused = false
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
, to: function (pos) {
var $active = this.$element.find('.item.active')
, children = $active.parent().children()
, activePos = children.index($active)
, that = this
if (pos > (children.length - 1) || pos < 0) return
if (this.sliding) {
return this.$element.one('slid', function () {
that.to(pos)
})
}
if (activePos == pos) {
return this.pause().cycle()
}
return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos]))
}
, pause: function (e) {
if (!e) this.paused = true
if (this.$element.find('.next, .prev').length && $.support.transition.end) {
this.$element.trigger($.support.transition.end)
this.cycle()
}
clearInterval(this.interval)
this.interval = null
return this
}
, next: function () {
if (this.sliding) return
return this.slide('next')
}
, prev: function () {
if (this.sliding) return
return this.slide('prev')
}
, slide: function (type, next) {
var $active = this.$element.find('.item.active')
, $next = next || $active[type]()
, isCycling = this.interval
, direction = type == 'next' ? 'left' : 'right'
, fallback = type == 'next' ? 'first' : 'last'
, that = this
, e
this.sliding = true
isCycling && this.pause()
$next = $next.length ? $next : this.$element.find('.item')[fallback]()
e = $.Event('slide', {
relatedTarget: $next[0]
})
if ($next.hasClass('active')) return
if ($.support.transition && this.$element.hasClass('slide')) {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
this.$element.one($.support.transition.end, function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () { that.$element.trigger('slid') }, 0)
})
} else {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid')
}
isCycling && this.cycle()
return this
}
}
/* CAROUSEL PLUGIN DEFINITION
* ========================== */
$.fn.carousel = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('carousel')
, options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option)
, action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.cycle()
})
}
$.fn.carousel.defaults = {
interval: 5000
, pause: 'hover'
}
$.fn.carousel.Constructor = Carousel
/* CAROUSEL DATA-API
* ================= */
$(document).on('click.carousel.data-api', '[data-slide]', function (e) {
var $this = $(this), href
, $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
, options = $.extend({}, $target.data(), $this.data())
$target.carousel(options)
e.preventDefault()
})
}(window.jQuery);
|
'use strict';
const serverErrorCode = 500;
module.exports = function serverError (data) {
var req = this.req;
var res = this.res;
var sails = req._sails;
res.status(serverErrorCode);
if (data === undefined) {
sails.log.error('Sending empty 500 ("Server Error") response');
} else {
sails.log.error('Sending 500 ("Server Error") response: \n', data);
}
if (sails.config.environment === 'production') {
data = undefined;
}
return res.jsonx(data);
};
|
'use strict';
angular.module('gamePlatformServerApp')
.directive('navbar', () => ({
templateUrl: 'components/navbar/navbar.html',
restrict: 'E',
controller: 'NavbarController',
controllerAs: 'nav'
}));
|
import styles from './ModelHeader.css';
import React, { Component } from 'react';
export default class ModelHeader extends Component {
render() {
return <div className={styles.root}>
Complaints<br />by <b>Model</b>
</div>
}
}
|
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
import { IndexDependencies } from './dependenciesIndexClass.generated';
import { compareNaturalDependencies } from './dependenciesCompareNatural.generated';
import { sizeDependencies } from './dependenciesSize.generated';
import { subsetDependencies } from './dependenciesSubset.generated';
import { typedDependencies } from './dependenciesTyped.generated';
import { createSetIsSubset } from '../../factoriesAny.js';
export var setIsSubsetDependencies = {
IndexDependencies: IndexDependencies,
compareNaturalDependencies: compareNaturalDependencies,
sizeDependencies: sizeDependencies,
subsetDependencies: subsetDependencies,
typedDependencies: typedDependencies,
createSetIsSubset: createSetIsSubset
};
|
var structRT__TASK__INFO =
[
[ "name", "structRT__TASK__INFO.html#a3e5d47277ecea23aa3a5730e0b6b2d13", null ],
[ "pid", "structRT__TASK__INFO.html#a70c731ca5877ff4a6235fa81caa77798", null ],
[ "prio", "structRT__TASK__INFO.html#a632e09c1d8dabc29c020c828abf62ac6", null ],
[ "stat", "structRT__TASK__INFO.html#ae327f3dca3f2ae89c8aa5bd0033ed4b0", null ]
];
|
const React = require('react');
class DonationOptions extends React.Component {
constructor(props) {
super(props);
this.state = {selectedDonationOption: 'option1', btnActiveID: "donation-option-1"};
}
btnIsActive = (value) => {
return 'btn btn-primary ' + ((value===this.state.btnActiveID) ? 'active':'');
}
handleDonationOptionChange = (changeEvent) => {
this.setState({
selectedDonationOption: changeEvent.target.value,
btnActiveID: changeEvent.target.id
}, console.log(changeEvent.target.value))
}
render() {
return(
<div className="btn-group donation-buttons">
<div className="row">
<div className="col-xs-12 p-0">
<div className="col-xs-4">
<label className={this.btnIsActive("donation-option-1")}>
<input type="checkbox" name="options" className="donation-options" id="donation-option-1" value="option1" checked={this.state.selectedDonationOption === "option1"} onChange={this.handleDonationOptionChange}/>$25
</label>
</div>
<div className="col-xs-4">
<label className={this.btnIsActive("donation-option-2")}>
<input type="checkbox" name="options" className="donation-options" id="donation-option-2" value="option2" checked={this.state.selectedDonationOption === "option2"} onChange={this.handleDonationOptionChange}/>$50
</label>
</div>
<div className="col-xs-4">
<label className={this.btnIsActive("donation-option-3")}>
<input type="checkbox" name="options" className="donation-options" id="donation-option-3" value="option3" checked={this.state.selectedDonationOption === "option3"} onChange={this.handleDonationOptionChange}/>$100
</label>
</div>
</div>
</div>
</div>
)
}
}
export default DonationOptions;
|
var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var chalk = require('chalk');
_.str = require('underscore.string');
_.mixin(_.str.exports());
var ngParseModule = require('ng-parse-module');
exports.JS_MARKER = "<!-- Add New Component JS Above -->";
exports.LESS_MARKER = "/* Add Component LESS Above */";
exports.ROUTE_MARKER = "/* Add New Routes Above */";
exports.STATE_MARKER = "/* Add New States Above */";
exports.addToFile = function(filename, lineToAdd, beforeMarker){
try {
var fullPath = path.resolve(process.cwd(), filename);
var fileSrc = fs.readFileSync(fullPath,'utf8');
var indexOf = fileSrc.indexOf(beforeMarker);
var lineStart = fileSrc.substring(0,indexOf).lastIndexOf('\n') + 1;
var indent = fileSrc.substring(lineStart,indexOf);
fileSrc = fileSrc.substring(0, indexOf) + lineToAdd + "\n" + indent + fileSrc.substring(indexOf);
fs.writeFileSync(fullPath, fileSrc);
} catch(e) {
throw e;
}
};
exports.processTemplates = function(name, dir, type, that, defaultDir, configName, module){
if (!defaultDir) {
defaultDir = 'templates'
}
if (!configName) {
configName = type + 'Templates';
}
var templateDirectory = path.join(path.dirname(that.resolved), defaultDir);
if(that.config.get(configName)){
templateDirectory = path.join(process.cwd(), that.config.get(configName));
}
_.chain(fs.readdirSync(templateDirectory))
.filter(function(template){
return template[0] !== '.';
})
.each(function(template){
var customTemplateName = template.replace(type, name);
var templateFile = path.join(templateDirectory, template);
//create the file in respective folder
if (_(customTemplateName).endsWith('-spec.js') ||
_(customTemplateName).endsWith('_spec.js') ||
_(customTemplateName).endsWith('-test.js') ||
_(customTemplateName).endsWith('_test.js')) {
var testDirLocation = dir.replace('app', 'test/specs');
that.template(templateFile, path.join(testDirLocation, customTemplateName));
}else{
that.template(templateFile, path.join(dir, customTemplateName));
}
//inject the file reference into index.html/app.less/etc as appropriate
exports.inject(path.join(dir, customTemplateName), that, module);
});
};
exports.inject = function(filename, that, module) {
//special case to skip unit tests
if (_(filename).endsWith('-spec.js') ||
_(filename).endsWith('_spec.js') ||
_(filename).endsWith('-test.js') ||
_(filename).endsWith('_test.js')) {
return;
}
var ext = path.extname(filename);
if (ext[0] === '.') {
ext = ext.substring(1);
}
var config = that.config.get('inject')[ext];
if (config) {
var configFile = _.template(config.file)({module:path.basename(module.file, '.js')});
var injectFileRef = filename;
if (config.relativeToModule) {
configFile = path.join(path.dirname(module.file), configFile);
injectFileRef = path.relative(path.dirname(module.file), filename);
}
//Added by Tapas to add app folder in place
if(injectFileRef.indexOf('app\\') > -1){
injectFileRef = injectFileRef.replace('app\\', '');
}
if(injectFileRef.indexOf('app/') > -1){
injectFileRef = injectFileRef.replace('app/', '');
}
injectFileRef = injectFileRef.replace(/\\/g,'/');
var lineTemplate = _.template(config.template)({filename:injectFileRef});
exports.addToFile(configFile, lineTemplate, config.marker);
that.log.writeln(chalk.green(' updating') + ' %s', path.basename(configFile));
}
};
exports.injectRoute = function(moduleFile, uirouter, name, route, routeUrl, that){
//Added by Tapas to add app folder in place
if(routeUrl.indexOf('app\\') > -1){
routeUrl = routeUrl.replace('app\\', '');
}
if(routeUrl.indexOf('app/') > -1){
routeUrl = routeUrl.replace('app/', '');
}
routeUrl = routeUrl.replace(/\\/g,'/');
if (uirouter){
var code = '$stateProvider.state(\''+name+'\', {\n url: \''+route+'\',\n templateUrl: \''+routeUrl+'\'\n\t\t});';
exports.addToFile(moduleFile,code,exports.STATE_MARKER);
} else {
exports.addToFile(moduleFile,'$routeProvider.when(\''+route+'\',{templateUrl: \''+routeUrl+'\'});',exports.ROUTE_MARKER);
}
that.log.writeln(chalk.green(' updating') + ' %s',path.basename(moduleFile));
};
exports.getParentModule = function(dir){
//starting this dir, find the first module and return parsed results
if (fs.existsSync(dir)) {
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
if (path.extname(files[i]) !== '.js') {
continue;
}
var results = ngParseModule.parse(path.join(dir,files[i]));
if (results) {
return results;
}
}
}
if (fs.existsSync(path.join(dir,'.yo-rc.json'))) {
//if we're in the root of the project then bail
return;
}
return exports.getParentModule(path.join(dir,'..'));
};
exports.askForModule = function(type,that,cb){
var modules = that.config.get('modules');
var mainModule = ngParseModule.parse('app/app.js');
mainModule.primary = true;
if (!modules || modules.length === 0) {
cb.bind(that)(mainModule);
return;
}
var choices = _.pluck(modules, 'name');
//Tapas: commented as no need to show main app module in the list
//choices.unshift(mainModule.name + ' (Primary Application Module)');
var prompts = [
{
name:'module',
message:'Which module would you like to place the new ' + type + '?',
type: 'list',
choices: choices,
default: 0
}
];
that.prompt(prompts, function (props) {
var i = choices.indexOf(props.module);
var module = ngParseModule.parse(modules[i].file);
//Tapas: No more required as we are not allowing user to add anything to main module
/*if (i === 0) {
module = mainModule;
} else {
module = ngParseModule.parse(modules[i-1].file);
}*/
cb.bind(that)(module);
}.bind(that));
};
exports.askForDir = function(type, that, module, ownDir, cb){
that.module = module;
that.appname = module.name;
that.dir = path.dirname(module.file);
var configedDir = that.config.get(type + 'Directory');
if (!configedDir){
configedDir = '.';
}
var defaultDir = path.join(that.dir, configedDir,'/');
defaultDir = path.relative(process.cwd(), defaultDir);
if (ownDir) {
defaultDir = path.join(defaultDir, that.name);
}
defaultDir = path.join(defaultDir, '/');
var dirPrompt = [
{
name:'dir',
message:'Where would you like to create the '+type+' files?',
default: defaultDir,
validate: function(dir){
if (!module.primary) {
//ensure dir is in module dir or subdir of it
dir = path.resolve(dir);
if (path.relative(that.dir,dir).substring(0,2) === '..') {
return 'Files must be placed inside the module directory or a subdirectory of the module.'
}
}
return true;
}
}
];
var dirPromptCallback = function (props) {
that.dir = path.join(props.dir, '/');
var dirToCreate = that.dir;
if (ownDir){
dirToCreate = path.join(dirToCreate, '..');
}
if (!fs.existsSync(dirToCreate)) {
that.prompt([{
name:'isConfirmed',
type:'confirm',
message:chalk.cyan(dirToCreate) + ' does not exist. Create it?'
}],function(props){
if (props.isConfirmed){
cb();
} else {
that.prompt(dirPrompt, dirPromptCallback);
}
});
} else if (ownDir && fs.existsSync(that.dir)){
//if the dir exists and this type of thing generally is inside its own dir, confirm it
that.prompt([{
name:'isConfirmed',
type:'confirm',
message:chalk.cyan(that.dir) + ' already exists. Components of this type contain multiple files and are typically put inside directories of their own. Continue?'
}],function(props){
if (props.isConfirmed){
cb();
} else {
that.prompt(dirPrompt, dirPromptCallback);
}
});
} else {
cb();
}
};
that.prompt(dirPrompt, dirPromptCallback);
};
exports.askForModuleAndDir = function(type, that, ownDir, cb) {
exports.askForModule(type, that, function(module){
exports.askForDir(type, that, module, ownDir, cb);
});
};
exports.getNameArg = function(that,args){
if (args.length > 0){
that.name = args[0];
}
};
exports.addNamePrompt = function(that,prompts,type){
if (!that.name){
prompts.splice(0,0,{
name:'name',
message: 'Enter a name for the ' + type + '.',
validate: function(input){
return true;
}
});
}
}
|
import { ToggleTimerBar } from '../../Config/SpecificToggles';
import ToggleBotBar from '../../Config/Toggles/ToggleBotBar';
import UpdateBackground from './UpdateBackground';
/**
* This function disables and shows the bars created by CookieMonster when the game is "ascending"
* It is called by CM.Disp.Draw()
*/
export default function UpdateAscendState() {
if (Game.OnAscend) {
l('game').style.bottom = '0px';
if (Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.settings.BotBar === 1)
l('CMBotBar').style.display = 'none';
if (Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.settings.TimerBar === 1)
l('CMTimerBar').style.display = 'none';
} else {
ToggleBotBar();
ToggleTimerBar();
}
UpdateBackground();
}
|
var questions = [
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-1',
inputs: {
looptotal: 10
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-2',
inputs: {
looptotal: 9
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-3',
inputs: {
looptotal: 11
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-4',
inputs: {
looptotal: 59
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-5',
inputs: {
looptotal: 100
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-6',
inputs: {
looptotal: 110
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-7',
inputs: {
looptotal: 10400
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-8',
inputs: {
looptotal: 4
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-9',
inputs: {
looptotal: 6
}
},
{
question: 'How many times will the code inside the loop execute?',
inputGroup: 'question-10',
inputs: {
looptotal: 3
}
}
];
questions.forEach(function (item, i) {
questions[i].onStart = function () {
document.getElementById('looptotal').focus();
Prism.highlightElement(document.querySelector('.language-javascript'));
};
});
FormValidator(ActivityRunner(), questions);
|
/**
* @ngdoc directive
* @name barchart
* @module angular-graphael
* @description
* Creates a bar chart.
* @link http://g.raphaeljs.com/reference.html#Paper.barchart
*/
angular.module('angular-graphael').directive('barchart', function ($window, mapData) {
'use strict';
return {
restrict: 'E',
scope: {
width: '=',
height: '=',
x: '=',
y: '=',
options: '=',
values: '='
},
template: '<div></div>',
link: function (scope, element) {
// Right now we only care about watching if the data changes.
scope.$watch('values', function () {
var r,
// X coordinate
x = scope.x || 100,
// Y coordinate
y = scope.y || 100,
// Width
width = scope.width || 100,
// Height
height = scope.height || 100;
// If you don't remove the old chart, you're gonna have a bad time.
element[0].innerHTML = '';
// Set up the canvas
r = $window.Raphael(element[0]);
// Add the chart to the canvas with all of our options and data.
r.barchart(x, y, width, height, mapData(scope.values), scope.options);
});
}
};
});
|
var mongoose = require('mongoose'),
models = require('../models');
module.exports = function (config) {
mongoose.connect(config.db);
var db = mongoose.connection;
db.once('open', function (error) {
if (error) {
console.log('Database could not be opened: ' + error);
return;
}
console.log('Database up and running...')
});
db.on('error', function (error) {
console.log('Database error: ' + error);
});
models.user.seedInitialUsers();
};
|
import test from 'ava'
import sinon from 'sinon'
import pokeapiEndpoints from './'
test('pokeapi-endpoints', (t) => {
const results = [{
'name': 'berry',
'url': 'https://pokeapi.co/api/v2/berry/'
}, {
'name': 'berry-firmness',
'url': 'https://pokeapi.co/api/v2/berry-firmness/'
}, {
'name': 'berry-flavor',
'url': 'https://pokeapi.co/api/v2/berry-flavor/'
}, {
'name': 'contest-type',
'url': 'https://pokeapi.co/api/v2/contest-type/'
}, {
'name': 'contest-effect',
'url': 'https://pokeapi.co/api/v2/contest-effect/'
}, {
'name': 'super-contest-type',
'url': 'https://pokeapi.co/api/v2/super-contest-type/'
}, {
'name': 'encounter-method',
'url': 'https://pokeapi.co/api/v2/encounter-method/'
}, {
'name': 'encounter-condition',
'url': 'https://pokeapi.co/api/v2/encounter-condition/'
}, {
'name': 'encounter-method-value',
'url': 'https://pokeapi.co/api/v2/encounter-method-value/'
}, {
'name': 'evolution-chain',
'url': 'https://pokeapi.co/api/v2/evolution-chain/'
}, {
'name': 'evolution-trigger',
'url': 'https://pokeapi.co/api/v2/evolution-trigger/'
}, {
'name': 'generation',
'url': 'https://pokeapi.co/api/v2/generation/'
}, {
'name': 'pokedex',
'url': 'https://pokeapi.co/api/v2/pokedex/'
}, {
'name': 'version',
'url': 'https://pokeapi.co/api/v2/version/'
}, {
'name': 'version-group',
'url': 'https://pokeapi.co/api/v2/version-group/'
}, {
'name': 'item',
'url': 'https://pokeapi.co/api/v2/item/'
}, {
'name': 'item-attribute',
'url': 'https://pokeapi.co/api/v2/item-attribute/'
}, {
'name': 'item-category',
'url': 'https://pokeapi.co/api/v2/item-category/'
}, {
'name': 'item-fling-effect',
'url': 'https://pokeapi.co/api/v2/item-fling-effect/'
}, {
'name': 'item-pocket',
'url': 'https://pokeapi.co/api/v2/item-pocket/'
}, {
'name': 'machine',
'url': 'https://pokeapi.co/api/v2/machine/'
}, {
'name': 'move',
'url': 'https://pokeapi.co/api/v2/move/'
}, {
'name': 'move-ailment',
'url': 'https://pokeapi.co/api/v2/move-ailment/'
}, {
'name': 'move-battle-style',
'url': 'https://pokeapi.co/api/v2/move-battle-style/'
}, {
'name': 'move-category',
'url': 'https://pokeapi.co/api/v2/move-category/'
}, {
'name': 'move-damage-class',
'url': 'https://pokeapi.co/api/v2/move-damage-class/'
}, {
'name': 'move-learn-method',
'url': 'https://pokeapi.co/api/v2/move-learn-method/'
}, {
'name': 'move-target',
'url': 'https://pokeapi.co/api/v2/move-target/'
}, {
'name': 'location',
'url': 'https://pokeapi.co/api/v2/location/'
}, {
'name': 'location-area',
'url': 'https://pokeapi.co/api/v2/location-area/'
}, {
'name': 'pal-park-area',
'url': 'https://pokeapi.co/api/v2/pal-park-area/'
}, {
'name': 'region',
'url': 'https://pokeapi.co/api/v2/region/'
}, {
'name': 'ability',
'url': 'https://pokeapi.co/api/v2/ability/'
}, {
'name': 'characteristic',
'url': 'https://pokeapi.co/api/v2/characteristic/'
}, {
'name': 'egg-group',
'url': 'https://pokeapi.co/api/v2/egg-group/'
}, {
'name': 'gender',
'url': 'https://pokeapi.co/api/v2/gender/'
}, {
'name': 'growth-rate',
'url': 'https://pokeapi.co/api/v2/growth-rate/'
}, {
'name': 'nature',
'url': 'https://pokeapi.co/api/v2/nature/'
}, {
'name': 'pokeathlon-stat',
'url': 'https://pokeapi.co/api/v2/pokeathlon-stat/'
}, {
'name': 'pokemon',
'url': 'https://pokeapi.co/api/v2/pokemon/'
}, {
'name': 'pokemon-color',
'url': 'https://pokeapi.co/api/v2/pokemon-color/'
}, {
'name': 'pokemon-form',
'url': 'https://pokeapi.co/api/v2/pokemon-form/'
}, {
'name': 'pokemon-habitat',
'url': 'https://pokeapi.co/api/v2/pokemon-habitat/'
}, {
'name': 'pokemon-shape',
'url': 'https://pokeapi.co/api/v2/pokemon-shape/'
}, {
'name': 'pokemon-species',
'url': 'https://pokeapi.co/api/v2/pokemon-species/'
}, {
'name': 'stat',
'url': 'https://pokeapi.co/api/v2/stat/'
}, {
'name': 'type',
'url': 'https://pokeapi.co/api/v2/type/'
}, {
'name': 'language',
'url': 'https://pokeapi.co/api/v2/language/'
}]
const done = sinon.spy()
const context = { done }
pokeapiEndpoints(context)
t.true(done.calledOnce)
t.true(done.calledWithExactly())
t.deepEqual(context.res, { results })
})
|
'use strict';
(function() {
describe('HomeController', function() {
//Initialize global variables
var scope,
HomeController;
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
HomeController = $controller('HomeController', {
$scope: scope
});
}));
it('should expose the authentication service', function() {
expect(scope.authentication).toBeTruthy();
});
});
})();
|
/*
* StoryQuest 2
*
* Copyright (c) 2014 Questor GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
function modalYesNo(label, text, done) {
$("#modalYesNoDoYes, #modalYesNoDoNo").click(function(event) {
$("#modalYesNoDoYes").unbind("click");
$("#modalYesNoDoNo").unbind("click");
done($(event.target).is($("#modalYesNoDoYes"))?true:false);
});
$("#modalYesNoLabel").html(label);
$("#modalYesNoText").html(text);
$("#modalYesNo").modal();
}
function modalOk(label, text, done) {
$("#modalOkDoOk").click(function(event) {
$("#modalOkDoOk").unbind("click");
done();
});
$("#modalOkLabel").html(label);
$("#modalOkText").html(text);
$("#modalOk").modal();
}
function modalOkCancel(label, text, done) {
$("#modalOkCancelDoOk").click(function(event) {
$("#modalOkCancelDoOk").unbind("click");
$("#modalOkCancelDoCancel").unbind("click");
done($(event.target).is($("#modalOkCancelDoOk"))?true:false);
});
$("#modalOkCancelLabel").html(label);
$("#modalOkCancelText").html(text);
$("#modalOkCancel").modal();
}
function modalWarning(label, text) {
$("#modalWarningLabel").html(label);
$("#modalWarningText").html(text);
$("#modalWarning").modal();
}
function modalQR(link, projectId) {
$("#previewqr").empty();
$("#previewqr").qrcode({width: 200, height: 200, text: link});
$("#devmodeurl").attr("href", "/api/p/" + projectId + "/index.html");
$("#modalQR").modal();
}
function modalError(text) {
$("#modalWarningLabel").html("Error");
$("#modalWarningText").html(text);
$("#modalWarning").modal();
}
function modalWait(text) {
$("#modalWaitLabel").html(text);
$("#modalWait").modal();
return $("#modalWait");
}
|
import React from 'react'
import PropTypes from 'prop-types'
import Colors from '../constants/Colors'
import Styles from '../styles/PersonCreate'
import HeaderTitle from '../components/HeaderTitle'
import PersonCreateView from '../components/PersonCreateView'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as allActions from '../actions'
class PersonCreate extends React.Component {
static propTypes = {
createPerson: PropTypes.func.isRequired,
cleanPersonCreateResponse: PropTypes.func.isRequired,
creatingPerson: PropTypes.bool.isRequired,
errorCreatingPerson: PropTypes.bool.isRequired,
successCreatingPerson: PropTypes.bool.isRequired,
}
static route = {
navigationBar: {
title: 'Nuevo',
backgroundColor: Colors.white,
borderBottomWidth: 1,
renderTitle: () => (
<HeaderTitle title={'Crear'} />
),
},
}
createPerson = (person) => {
this.props.createPerson(person)
}
cleanPersonCreateResponse = () => {
this.props.cleanPersonCreateResponse()
}
render() {
return (
<PersonCreateView
styles={Styles}
creatingPerson={this.props.creatingPerson}
errorCreatingPerson={this.props.errorCreatingPerson}
successCreatingPerson={this.props.successCreatingPerson}
createPerson={this.createPerson}
cleanPersonCreateResponse={this.cleanPersonCreateResponse}
/>
)
}
}
function mapStateToProps (state) {
return {
creatingPerson: state.personCreate.creatingPerson,
errorCreatingPerson: state.personCreate.errorCreatingPerson,
successCreatingPerson: state.personCreate.successCreatingPerson,
}
}
function mapDispatchToProps (dispatch) {
const actions = bindActionCreators(allActions, dispatch)
return {
createPerson: actions.createPerson,
cleanPersonCreateResponse: actions.cleanPersonCreateResponse,
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(PersonCreate)
|
var mongoose = require('mongoose'),
Sync = require('sync'),
uniqueValidator = require('mongoose-unique-validator');
var studentAbsencesSchema = mongoose.Schema({
number: {
type: Number,
required: true,
unique: true,
match: /^\d{1,2}$/,
min: 1,
max: 30,
sprace: true
},
excused: {
type: Number,
min: 0,
max: 999
},
inexcused: {
type: String,
validate: /(^\d+$)|(^\d+\/\d+$)|(^\d+\s+\d+\/\d+$)/
},
allExcused: Number,
allInexcused: String,
averageExcused: Number,
averageInexcused: Number
});
var classAbsencesSchema = mongoose.Schema({
schoolClass: {
type: mongoose.Schema.ObjectId,
unique: true
},
absences: [studentAbsencesSchema]
});
var StudentAbsences = mongoose.model('StudentAbsences', studentAbsencesSchema);
var Absences = mongoose.model('Absences', classAbsencesSchema);
module.exports = {
seedSchoolClassAbsences: function(schoolClass, callback) {
var newSchoolClassAbsences = new Absences({
schoolClass: schoolClass,
absences: []
});
newSchoolClassAbsences.save(function(err, res) {
if (err) {
console.log('error seeding class absences: ' + err);
return;
}
console.log('absences for class seeded!' + res);
return callback();
});
},
seedUserAbsences: function(schoolClass, number, callback) {
Absences.update({
schoolClass: schoolClass,
}, {
$push: {
absences: {
number: parseInt(number),
excused: 0,
inexcused: '0'
}
}
}, function(err, absence) {
if (err) {
console.log('error seeding user absences: ' + err);
return;
}
console.log('absences for user seeded:');
console.log(absence);
return callback();
});
}
// seedInitialAbsences: function(schoolClass, callback) {
// // Absences.remove({}, function(err) {
// Absences.findOne({
// schoolClass: schoolClass
// }, function(err, absences) {
// if (err) {
// console.log('Absences were not seeded: ' + err);
// return callback();
// }
// if (absences) {
// console.log("absences: " + absences);
// }
// if (!absences) {
// Sync(function() {
// var arrToSave = [];
// for (var i = 0; i < 25; i++) {
// numberToCreate = i + 1;
// arrToSave[i] = {};
// arrToSave[i].number = numberToCreate;
// arrToSave[i].excused = 0;
// arrToSave[i].inexcused = '0';
// }
// return arrToSave;
// }, function(err, result) {
// console.log(result);
// Absences.create({
// schoolClass: schoolClass,
// absences: result
// }, function(err, result) {
// if (err) {
// console.log('Absences seeding err: ' + err);
// return callback();
// }
// console.log(result);
// console.log('Absences for schoolClass ' + schoolClass + ' seeded!');
// return callback();
// });
// });
// }
// });
// });
// }
};
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CodeZu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
var Client = require('../../../../client'), constants = Client.constants;
module.exports = Client.sub({
getCustomRouteSettings: Client.method({
method: constants.verbs.GET,
url: '{+tenantPod}api/commerce/settings/general/customroutes?responseFields={responseFields}'
}),
createCustomRouteSettings: Client.method({
method: constants.verbs.POST,
url: '{+tenantPod}api/commerce/settings/general/customroutes?responseFields={responseFields}'
}),
updateCustomRouteSettings: Client.method({
method: constants.verbs.PUT,
url: '{+tenantPod}api/commerce/settings/general/customroutes?responseFields={responseFields}'
}),
deleteCustomRouteSettings: Client.method({
method: constants.verbs.DELETE,
url: '{+tenantPod}api/commerce/settings/general/customroutes'
})
});
|
'use strict';
const BinaryTree = require('../index').BinaryTree,
assert = require('chai').assert;
describe('BinaryTree', () => {
let myBinaryTree = new BinaryTree('A');
myBinaryTree.addChild('B')
myBinaryTree.addChild('C')
myBinaryTree.addChild('D')
myBinaryTree.addChild('E')
myBinaryTree.addChild('F')
myBinaryTree.addChild('G')
myBinaryTree.addChild('H')
myBinaryTree.addChild('I')
myBinaryTree.addChild('J')
describe('BinaryTree Create', () => {
it('creating new BinaryTree, the root ID should be "VVVVVVVVVVVVVVVVVVVV"', () => {
assert.equal(myBinaryTree.__id, 'VVVVVVVVVVVVVVVVVVVV', 'makeId not working')
});
it('creating new BinaryTree, the right ID should be > "VVVVVVVVVVVVVVVVVVVV" and < for left', () => {
if (myBinaryTree.right) {
assert.isTrue(myBinaryTree.right.__id > myBinaryTree.__id)
}
if (myBinaryTree.left) {
assert.isTrue(myBinaryTree.left.__id < myBinaryTree.__id)
}
});
it('creating new BinaryTree should take a value', () => {
const myBinaryTree2 = new BinaryTree('Hello World');
assert.equal(myBinaryTree2.value, 'Hello World', 'creat new BinaryTree not working')
});
it('addChild should add grandchildren', () => {
assert.isTrue(myBinaryTree.containsVal('A'));
assert.isTrue(myBinaryTree.containsVal('C'));
assert.isTrue(myBinaryTree.containsVal('F'));
assert.isTrue(myBinaryTree.containsVal('H'));
});
});
describe('BinaryTree Lookup', () => {
it('containsVal should return true if value exists and false if not', () => {
assert.isTrue(myBinaryTree.containsVal('B'));
assert.isFalse(myBinaryTree.containsVal('K'));
});
it('containsId should return true if id exists and false if not', () => {
const testId1 = myBinaryTree.__id;
assert.isTrue(myBinaryTree.containsId(testId1));
if (myBinaryTree.left) {
const testId2 = myBinaryTree.left.__id;
assert.isTrue(myBinaryTree.containsId(testId2));
}
if (myBinaryTree.right) {
const testId3 = myBinaryTree.right.__id;
assert.isTrue(myBinaryTree.containsId(testId3));
}
assert.isFalse(myBinaryTree.containsId('fake_id'));
});
it('getId should return the id of a given value, or null if not found', () => {
const testId1 = myBinaryTree.__id;
assert.equal(myBinaryTree.getId('A'), testId1, 'getId not working')
assert.equal(myBinaryTree.getId('Not in BTree'), null, 'getId not working')
});
it('lookupId should return value at id, or null if not found', () => {
let testId1 = myBinaryTree.__id;
let testVal1 = myBinaryTree.value;
assert.equal(myBinaryTree.lookupId(testId1), testVal1, 'lookupId not working')
if (myBinaryTree.left) {
let testId2 = myBinaryTree.left.__id;
let testVal2 = myBinaryTree.left.value;
assert.equal(myBinaryTree.lookupId(testId2), testVal2, 'lookupId not working')
}
if (myBinaryTree.right) {
let testId3 = myBinaryTree.right.__id;
let testVal3 = myBinaryTree.right.value;
assert.equal(myBinaryTree.lookupId(testId3), testVal3, 'lookupId not working')
}
assert.equal(myBinaryTree.lookupId('fake_id'), null, 'lookupId not working')
});
it('countNodes should return the number of nodes', () => {
assert.equal(myBinaryTree.countNodes(), 10, 'countNodes not working')
});
});
describe('BinaryTree Update', () => {
let myBinaryTree3 = new BinaryTree('A');
myBinaryTree3.addChild('B')
myBinaryTree3.addChild('C')
myBinaryTree3.addChild('D')
myBinaryTree3.addChild('E')
myBinaryTree3.addChild('F')
myBinaryTree3.addChild('G')
myBinaryTree3.addChild('H')
myBinaryTree3.addChild('I')
myBinaryTree3.addChild('J')
it('updateId should update value at id, or null if not found', () => {
let testId1 = myBinaryTree3.__id;
myBinaryTree3.updateId(testId1, 'Hello World')
let testVal1 = myBinaryTree3.value;
assert.equal(myBinaryTree3.lookupId(testId1), testVal1, 'updateId not working')
if (myBinaryTree3.left) {
let testId2 = myBinaryTree3.left.__id;
myBinaryTree3.updateId(testId2, 'Foo bar')
let testVal2 = myBinaryTree3.left.value;
assert.equal(myBinaryTree3.lookupId(testId2), testVal2, 'updateId not working')
}
if (myBinaryTree3.right) {
let testId3 = myBinaryTree3.right.__id;
myBinaryTree3.updateId(testId3, 'Baz')
let testVal3 = myBinaryTree3.right.value;
assert.equal(myBinaryTree3.lookupId(testId3), testVal3, 'updateId not working')
}
assert.equal(myBinaryTree3.updateId('fake_id'), null, 'lookupId not working')
});
it('updateId should return updated value at id, or null if not found', () => {
let testId1 = myBinaryTree3.__id;
assert.equal(myBinaryTree3.updateId(testId1, 'Good Bye World'), 'Good Bye World', 'return for updateId not working')
});
});
describe('BinaryTree Delete', () => {
let myBinaryTree = new BinaryTree(0);
for (let i = 1; i < 10; i++) {
myBinaryTree.addChild(i);
}
it('deleteNode should return null if no id is passed in', () => {
assert.equal(myBinaryTree.deleteNode(), null, 'deleteNode with no id not working');
});
it('deleteNode should return null if there are no children and root id does not match', () => {
let myBinaryTree = new BinaryTree(0);
assert.equal(myBinaryTree.deleteNode('fake_id'), null, 'deleteNode with fake id not working');
});
it('deleteNode should reset root value to null if there are no children and root id does match', () => {
let myBinaryTree = new BinaryTree(0);
let rootId = myBinaryTree.__id;
myBinaryTree.deleteNode(rootId)
assert.equal(myBinaryTree.value, null, 'deleteNode with id and no children not working');
});
it('deleteNode should return original value that was deleted if there are no children and root id does match', () => {
let myBinaryTree = new BinaryTree(0);
let rootId = myBinaryTree.__id;
let deletedValue = myBinaryTree.deleteNode(rootId)
assert.equal(deletedValue, 0, 'deleteNode with id and no children not working');
});
it('deleteNode should delete leaf', () => {
const treeLength = myBinaryTree.mapIdToArray().length;
let firstLeaf;
const findLeaf = (node) => {
if (!node.left && !node.right) {
firstLeaf = node.__id;
return firstLeaf
}
if (node.left) {
findLeaf(node.left)
}
if (node.right) {
findLeaf(node.right)
}
}
findLeaf(myBinaryTree);
myBinaryTree.deleteNode(firstLeaf);
assert.isFalse(myBinaryTree.containsId(firstLeaf));
assert.equal(myBinaryTree.mapIdToArray().length, treeLength - 1, 'deleteNode at leaf not working')
});
it('deleteNode should delete a node with children, but keep the children', () => {
let myBinaryTree = new BinaryTree(0);
for (let i = 1; i < 10; i++) {
myBinaryTree.addChild(i);
}
const treeLength = myBinaryTree.mapIdToArray().length;
let nodesDeleted = 0;
if (myBinaryTree.left) {
if (myBinaryTree.left.left) {
nodesDeleted++;
var leftParent = myBinaryTree.left.__id
var leftChild = myBinaryTree.left.left.__id
myBinaryTree.deleteNode(leftParent);
assert.isFalse(myBinaryTree.containsId(leftParent));
assert.isTrue(myBinaryTree.containsId(leftChild));
assert.equal(myBinaryTree.mapIdToArray().length, treeLength - nodesDeleted, 'deleteNode at leaf not working')
}
}
if (myBinaryTree.right) {
if (myBinaryTree.right.right) {
nodesDeleted++;
var rightParent = myBinaryTree.right.__id
var rightChild = myBinaryTree.right.right.__id
myBinaryTree.deleteNode(rightParent);
assert.isFalse(myBinaryTree.containsId(rightParent));
assert.isTrue(myBinaryTree.containsId(rightChild));
assert.equal(myBinaryTree.mapIdToArray().length, treeLength - nodesDeleted, 'deleteNode at leaf not working')
}
}
});
it('deleteNode should replace the root, but keep the children', () => {
let myBinaryTree = new BinaryTree(0);
for (let i = 1; i < 10; i++) {
myBinaryTree.addChild(i);
}
const treeLength = myBinaryTree.mapIdToArray().length;
let nodesDeleted = 0;
var rootId = myBinaryTree.__id;
if (myBinaryTree.right) {
nodesDeleted++;
var rightChild = myBinaryTree.right.__id
myBinaryTree.deleteNode(rootId);
assert.isFalse(myBinaryTree.containsId(rootId));
assert.isTrue(myBinaryTree.containsId(rightChild));
assert.equal(myBinaryTree.mapIdToArray().length, treeLength - nodesDeleted, 'deleteNode at leaf not working')
}
});
});
describe('BinaryTree Helper Functions', () => {
let myBinaryTree = new BinaryTree(0);
for (let i = 1; i < 10; i++) {
myBinaryTree.addChild(i);
}
it('mapToArray should return an array of the values', () => {
const soln = [0,1,2,3,4,5,6,7,8,9];
let test = myBinaryTree.mapToArray();
test = test.sort((a, b) => a-b);
assert.deepEqual(soln, test);
});
it('mapToArray should return a sorted array with a callback invoked on each item', () => {
const soln = [0,2,4,6,8,10,12,14,16,18];
let test = myBinaryTree.mapToArray((val) => val * 2);
test = test.sort((a, b) => a-b);
assert.deepEqual(soln, test);
});
it('mapIdToArray should return a sorted array if ids', () => { // Test not done
const test = myBinaryTree.mapIdToArray();
assert.equal(myBinaryTree.countNodes(), test.length, 'mapIdToArray is not working');
});
it('filterToArray should return an array of items that pass callback predicate', () => {
const soln = [0,2,4,6,8];
let test = myBinaryTree.filterToArray((val) => val % 2 === 0);
test = test.sort((a, b) => a-b);
assert.deepEqual(soln, test);
});
let myBinaryTree1 = new BinaryTree(0);
for (let i = 1; i < 10; i++) {
myBinaryTree1.addChild(i);
}
myBinaryTree1.addChild(4)
myBinaryTree1.addChild(5)
myBinaryTree1.addChild(5)
it('removeDuplicates should remove nodes with duplicate values', () => {
let nodesBefore = myBinaryTree1.countNodes();
let test1 = myBinaryTree1.mapToArray();
test1 = test1.sort((a, b) => a-b);
let deletedNode = myBinaryTree1.removeDuplicates();
let test2 = myBinaryTree1.mapToArray();
test2 = test2.sort((a, b) => a-b);
let nodesAfter = myBinaryTree1.countNodes();
assert.equal(nodesBefore, nodesAfter + 3, 'removeDuplicates is not working');
assert.deepEqual(test2, [0,1,2,3,4,5,6,7,8,9]);
});
});
describe('BinaryTree Diagnostic Functions', () => {
let myBinaryTree = new BinaryTree(0);
for (let i = 1; i < 10000; i++) {
myBinaryTree.addChild(i);
}
it('deepestGeneration should return a number', () => { // Test not done
const test = myBinaryTree.deepestGeneration();
assert.isTrue(typeof test === 'number');
});
it('deepestGeneration should return the length of the deepest path', () => { // Test not done
const test = myBinaryTree.deepestGeneration();
assert.isTrue(test < 36);
});
});
});
|
'use strict'
const client = require('../octopus-client')
const getAll = async (take, skip) => {
const url = `/channels?${take ? `take=${take}` : ''}&${skip ? `skip=${skip}` : ''}`
return client.get(url)
}
module.exports = { getAll }
|
var app = angular.module('ui.grid.edit');
app.provider('uiGridEditDatepickerCustomTemplate', function() {
var template = false;
return {
set: function(_template_) {
template = _template_;
},
$get: function() {
return template;
}
}
});
app.directive('uiGridEditDatepicker', ['$timeout', '$document', 'uiGridConstants', 'uiGridEditConstants', 'uiGridEditDatepickerCustomTemplate', function($timeout, $document, uiGridConstants, uiGridEditConstants, uiGridEditDatepickerCustomTemplate) {
return {
template: function(element, attrs) {
var html = '<div class="datepicker-wrapper" ><input type="text" uib-datepicker-popup datepicker-options="datepickerOptions" datepicker-append-to-body="true" is-open="isOpen" ng-model="datePickerValue" ng-change="changeDate($event)" ng-keydown="editDate($event)" popup-placement="auto top"/></div>';
return uiGridEditDatepickerCustomTemplate || html;
},
require: ['?^uiGrid', '?^uiGridRenderContainer'],
scope: true,
compile: function() {
return {
pre: function($scope, $elm, $attrs) {
if ($attrs.datepickerOptions){
if ($scope.col.grid.appScope[$attrs.datepickerOptions]){
$scope.datepickerOptions = $scope.col.grid.appScope[$attrs.datepickerOptions];
}
}
},
post: function($scope, $elm, $attrs, controllers) {
var setCorrectPosition = function() {
var gridElement = $('.ui-grid-viewport');
var gridPosition = {
width: gridElement.outerWidth(),
height: gridElement.outerHeight(),
offset: gridElement.offset()
};
var cellElement = $($elm);
var cellPosition = {
width: cellElement.outerWidth(),
height: cellElement.outerHeight(),
offset: cellElement.offset()
};
var datepickerElement = $('body > .dropdown-menu, body > div > .dropdown-menu');
var datepickerPosition = {
width: datepickerElement.outerWidth(),
height: datepickerElement.outerHeight()
};
var setCorrectTopPositionInGrid = function() {
var topPosition;
var freePixelsOnBottom = gridPosition.height - (cellPosition.offset.top - gridPosition.offset.top) - cellPosition.height;
var freePixelsOnTop = gridPosition.height - freePixelsOnBottom - cellPosition.height;
var requiredPixels = (datepickerPosition.height - cellPosition.height) / 2;
if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop >= requiredPixels) {
topPosition = cellPosition.offset.top - requiredPixels + 10;
} else if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop < requiredPixels) {
topPosition = cellPosition.offset.top - freePixelsOnTop + 10;
} else {
topPosition = gridPosition.height - datepickerPosition.height + gridPosition.offset.top - 20;
}
return topPosition;
};
var setCorrectTopPositionInWindow = function() {
var topPosition;
var windowHeight = window.innerHeight - 10;
var freePixelsOnBottom = windowHeight - cellPosition.offset.top;
var freePixelsOnTop = windowHeight - freePixelsOnBottom - cellPosition.height;
var requiredPixels = (datepickerPosition.height - cellPosition.height) / 2;
if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop >= requiredPixels) {
topPosition = cellPosition.offset.top - requiredPixels;
} else if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop < requiredPixels) {
topPosition = cellPosition.offset.top - freePixelsOnTop;
} else {
topPosition = windowHeight - datepickerPosition.height - 10;
}
return topPosition;
};
var newOffsetValues = {};
var isFreeOnRight = (gridPosition.width - (cellPosition.offset.left - gridPosition.offset.left) - cellPosition.width) > datepickerPosition.width;
if (isFreeOnRight) {
newOffsetValues.left = cellPosition.offset.left + cellPosition.width;
} else {
newOffsetValues.left = cellPosition.offset.left - datepickerPosition.width;
}
if (datepickerPosition.height < gridPosition.height) {
newOffsetValues.top = setCorrectTopPositionInGrid();
} else {
newOffsetValues.top = setCorrectTopPositionInWindow();
}
datepickerElement.offset(newOffsetValues);
datepickerElement.css("visibility", "visible");
};
$timeout(function() {
setCorrectPosition();
}, 0);
$scope.datePickerValue = new Date($scope.row.entity[$scope.col.field]);
$scope.isOpen = true;
var uiGridCtrl = controllers[0];
var renderContainerCtrl = controllers[1];
var onWindowClick = function (evt) {
var classNamed = angular.element(evt.target).attr('class');
if (classNamed) {
var inDatepicker = (classNamed.indexOf('datepicker-calendar') > -1);
if (!inDatepicker && evt.target.nodeName !== "INPUT") {
$scope.stopEdit(evt);
}
}
else {
$scope.stopEdit(evt);
}
};
var onCellClick = function (evt) {
angular.element(document.querySelectorAll('.ui-grid-cell-contents')).off('click', onCellClick);
$scope.stopEdit(evt);
};
$scope.editDate = function(evt) {
if (evt.keyCode > 48){
$scope.datePickerValue = new Date($scope.row.entity[$scope.col.field]);
}
};
$scope.changeDate = function (evt) {
if (angular.isDate($scope.datePickerValue)) {
$scope.row.entity[$scope.col.field] = $scope.datePickerValue;
$scope.stopEdit(evt);
} else {
$scope.datePickerValue = new Date($scope.row.entity[$scope.col.field]);
}
};
$scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
if (uiGridCtrl.grid.api.cellNav) {
uiGridCtrl.grid.api.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) {
$scope.stopEdit();
});
} else {
angular.element(document.querySelectorAll('.ui-grid-cell-contents')).on('click', onCellClick);
}
angular.element(window).on('click', onWindowClick);
});
$scope.$on('$destroy', function () {
angular.element(window).off('click', onWindowClick);
$('body > .dropdown-menu, body > div > .dropdown-menu').remove();
});
$scope.stopEdit = function(evt) {
$scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
};
$elm.on('keydown', function(evt) {
switch (evt.keyCode) {
case uiGridConstants.keymap.ESC:
evt.stopPropagation();
$scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
break;
}
if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
$scope.stopEdit(evt);
}
} else {
switch (evt.keyCode) {
case uiGridConstants.keymap.ENTER:
case uiGridConstants.keymap.TAB:
evt.stopPropagation();
evt.preventDefault();
$scope.stopEdit(evt);
break;
}
}
return true;
});
}
};
}
};
}]);
|
'use strict';
module.exports = {
'rules': {
'accessor-pairs': 'off',
'array-bracket-spacing': [
'error',
'never'
],
'brace-style': [
'error',
'1tbs',
{
'allowSingleLine': false
}
],
'camelcase': [
'error',
{
'properties': 'always'
}
],
'comma-dangle': [
'error',
'never'
],
'comma-spacing': [
'error',
{
'after': true,
'before': false
}
],
'comma-style': [
2,
'last'
],
'complexity': [
'error',
7
],
'computed-property-spacing': [
'error',
'never'
],
'consistent-return': 'error',
'consistent-this': [
'error',
'self'
],
'curly': [
'error',
'all'
],
'default-case': 'error',
'dot-location': 'off',
'dot-notation': 'error',
'eol-last': 'error',
'eqeqeq': [
'error',
'smart'
],
'func-names': 'off',
'func-style': [
'error',
'expression'
],
'guard-for-in': 'error',
'handle-callback-err': [
'error',
'^(err|error)$'
],
'indent': [
'error',
2,
{
'SwitchCase': 1
}
],
'key-spacing': [
'off',
{
'align': 'value'
}
],
'keyword-spacing': [
'error',
{
'after': true,
'before': true,
'overrides': {}
}
],
'linebreak-style': [
'error',
'unix'
],
'lines-around-comment': 'off',
'max-len': ['error', { code: 200 }],
'max-nested-callbacks': [
'error',
3
],
'multiline-ternary': ['error', 'never'],
'new-cap': [
'error',
{
'capIsNew': true,
'newIsCap': true
}
],
'new-parens': 'error',
'newline-after-var': 'off',
'no-alert': 'error',
'no-array-constructor': 'error',
'no-caller': 'error',
'no-catch-shadow': 'error',
'no-cond-assign': [
'error',
'always'
],
'no-console': 'warn',
'no-constant-condition': 'error',
'no-continue': 'error',
'no-control-regex': 'error',
'no-debugger': 'error',
'no-delete-var': 'error',
'no-div-regex': 'error',
'no-dupe-args': 'error',
'no-dupe-keys': 'error',
'no-duplicate-case': 'error',
'no-else-return': 'error',
'no-empty': 'error',
'no-empty-character-class': 'error',
'no-eq-null': 'error',
'no-eval': 'error',
'no-ex-assign': 'error',
'no-extend-native': 'error',
'no-extra-bind': 'error',
'no-extra-boolean-cast': 'error',
'no-extra-semi': 'error',
'no-fallthrough': 'error',
'no-floating-decimal': 'error',
'no-func-assign': 'error',
'no-implied-eval': 'error',
'no-inline-comments': 'off',
'no-inner-declarations': 'error',
'no-invalid-regexp': 'error',
'no-irregular-whitespace': 'error',
'no-iterator': 'error',
'no-label-var': 'error',
'no-labels': 'error',
'no-lone-blocks': 'error',
'no-lonely-if': 2,
'no-loop-func': 2,
'no-mixed-requires': [
0,
true
],
'no-mixed-spaces-and-tabs': 2,
'no-multi-spaces': 2,
'no-multi-str': 2,
'no-multiple-empty-lines': [
2,
{
'max': 1
}
],
'no-native-reassign': 2,
'no-negated-in-lhs': 2,
'no-nested-ternary': 2,
'no-new': 2,
'no-new-func': 2,
'no-new-object': 2,
'no-new-require': 2,
'no-new-wrappers': 2,
'no-obj-calls': 2,
'no-octal': 2,
'no-octal-escape': 2,
'no-param-reassign': 2,
'no-path-concat': 2,
'no-process-env': 0,
'no-process-exit': 2,
'no-proto': 2,
'no-prototype-builtins': 2,
'no-redeclare': 2,
'no-regex-spaces': 2,
'no-restricted-modules': 0,
'no-return-assign': 2,
'no-script-url': 2,
'no-self-compare': 2,
'no-sequences': 2,
'no-shadow': 0,
'no-shadow-restricted-names': 2,
'no-spaced-func': 2,
'no-sparse-arrays': 2,
'no-sync': 2,
'no-ternary': 0,
'no-throw-literal': 2,
'no-trailing-spaces': 2,
'no-undef': 2,
'no-undef-init': 2,
'no-undefined': 0,
'no-underscore-dangle': 2,
'no-unneeded-ternary': 2,
'no-unreachable': 2,
'no-unused-expressions': 2,
'no-unused-vars': 'error',
'no-use-before-define': 2,
'no-var': 0,
'no-void': 2,
'no-warning-comments': [
2,
{
'location': 'anywhere',
'terms': [
'fixme',
'fuck',
'todo',
'xxx'
]
}
],
'no-with': 2,
'object-curly-spacing': [
2,
'always'
],
'object-shorthand': ['error', 'never'],
'one-var': 'off',
'operator-assignment': [
2,
'always'
],
'operator-linebreak': [
2,
'before'
],
'padded-blocks': [
0,
'always'
],
'prefer-arrow-callback': 2,
'prefer-const': 2,
'quotes': [
2,
'single'
],
'radix': 2,
'semi': [
'error',
'always'
],
'semi-spacing': [
2,
{
'after': true,
'before': false
}
],
'sort-imports': 0,
'sort-keys': 0,
'sort-vars': [
0,
{
'ignoreCase': true
}
],
'space-before-blocks': [
2,
'always'
],
'space-before-function-paren': [
2,
{
'anonymous': 'always',
'named': 'never'
}
],
'space-in-parens': [
2,
'never'
],
'space-infix-ops': [
2,
{
'int32Hint': false
}
],
'space-unary-ops': [
2,
{
'nonwords': false,
'words': true
}
],
'strict': [
2,
'global'
],
'use-isnan': 2,
'valid-jsdoc': 0,
'valid-typeof': 2,
'vars-on-top': 'off',
'wrap-iife': 2,
'wrap-regex': 2,
'yoda': [
2,
'never'
]
}
};
|
"use strict";
var helpers = require("../../helpers/helpers");
exports["Africa/Douala"] = {
"guess:by:offset" : helpers.makeTestGuess("Africa/Douala", { offset: true, expect: "Africa/Lagos" }),
"guess:by:abbr" : helpers.makeTestGuess("Africa/Douala", { abbr: true, expect: "Africa/Lagos" }),
"1905" : helpers.makeTestYear("Africa/Douala", [
["1905-06-30T23:46:24+00:00", "23:59:59", "LMT", -815 / 60],
["1905-06-30T23:46:25+00:00", "23:46:25", "GMT", 0]
]),
"1908" : helpers.makeTestYear("Africa/Douala", [
["1908-06-30T23:59:59+00:00", "23:59:59", "GMT", 0],
["1908-07-01T00:00:00+00:00", "00:13:35", "LMT", -815 / 60]
]),
"1913" : helpers.makeTestYear("Africa/Douala", [
["1913-12-31T23:46:24+00:00", "23:59:59", "LMT", -815 / 60],
["1913-12-31T23:46:25+00:00", "00:16:25", "+0030", -30]
]),
"1919" : helpers.makeTestYear("Africa/Douala", [
["1919-08-31T23:29:59+00:00", "23:59:59", "+0030", -30],
["1919-08-31T23:30:00+00:00", "00:30:00", "WAT", -60]
])
};
|
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename =require('gulp-rename');
var svgstore =require('gulp-svgstore');
var svgmin =require('gulp-svgmin');
var inject =require('gulp-inject');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
//maps: false,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
// .pipe(function() {
// return gulpif('*.less', less());
// })
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
//SVG fonts inject
gulp.task('svgicons', function () {
var svgs = gulp
.src('assets/icons/*.svg')
.pipe(rename({prefix: 'icon-'}))
.pipe(svgmin())
.pipe(svgstore({ inlineSvg: true }));
function fileContents (filePath, file) {
return file.contents.toString();
}
return gulp
.src('templates/svg-icons.php')
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest('templates'));
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
notify: {
styles: {
top: 'auto',
bottom: '0',
right: 'auto',
left: '0',
margin: '0px',
padding: '5px',
position: 'fixed',
fontSize: '10px',
zIndex: '9999',
borderRadius: '0px 5px 0px',
color: 'white',
textAlign: 'center',
display: 'block',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
}
},
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch([path.source + 'icons/**/*.svg'], ['svgicons']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images', 'svgicons'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
|
const path = require('path')
const BannerPlugin = require('webpack/lib/BannerPlugin')
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin')
const DefinePlugin = require('webpack/lib/DefinePlugin')
const OccurrenceOrderPlugin = require(
'webpack/lib/optimize/OccurrenceOrderPlugin')
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin')
const ProvidePlugin = require('webpack/lib/ProvidePlugin')
module.exports = function(buildTarget) {
const FILENAME = buildTarget.FILENAME
const DEV_BUILD = buildTarget.DEV_BUILD
const POLYFILL = buildTarget.POLYFILL
const SOURCEMAPS = !process.env.NO_SOURCEMAPS
return {
entry: {
horizon: POLYFILL ?
'./src/index-polyfill.js' :
'./src/index.js',
},
target: 'web',
output: {
path: path.resolve(__dirname, 'dist'),
filename: FILENAME,
library: 'Horizon', // window.Horizon if loaded by a script tag
libraryTarget: 'umd',
pathinfo: DEV_BUILD, // Add module filenames as comments in the bundle
devtoolModuleFilenameTemplate: DEV_BUILD ?
function(file) {
if (file.resourcePath.indexOf('webpack') >= 0) {
return `webpack:///${file.resourcePath}`
} else {
// Show correct paths in stack traces
return path.join('..', file.resourcePath)
.replace(/~/g, 'node_modules')
}
} :
null,
},
externals: [
function(context, request, callback) {
// Selected modules are not packaged into horizon.js. Webpack
// allows them to be required natively at runtime, either from
// filesystem (node) or window global.
if (!POLYFILL && /^rxjs\/?/.test(request)) {
callback(null, {
// If loaded via script tag, has to be at window.Rx when
// library loads
root: 'Rx',
// Otherwise imported via `require('rx')`
commonjs: 'rxjs',
commonjs2: 'rxjs',
amd: 'rxjs'
})
} else {
callback()
}
},
{ ws: 'commonjs ws' }
],
debug: DEV_BUILD,
devtool: SOURCEMAPS ? (DEV_BUILD ? 'source-map' : 'source-map') : false,
module: {
noParse: [
],
preLoaders: [],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
extends: path.resolve(__dirname, 'package.json'),
},
},
],
},
plugins: [
new BannerPlugin('__LICENSE__'),
// Possibility to replace constants such as `if (__DEV__)`
// and thus strip helpful warnings from production build:
new DefinePlugin({
'process.env.NODE_ENV': (DEV_BUILD ? 'development' : 'production'),
}),
new ProvidePlugin({
Promise: 'es6-promise',
}),
].concat(DEV_BUILD ? [] : [
new DedupePlugin(),
new OccurrenceOrderPlugin(),
new UglifyJsPlugin({
compress: {
screw_ie8: false,
warnings: false,
},
mangle: {
except: [],
},
}),
]),
node: {
// Don't include unneeded node libs in package
process: false,
fs: false,
__dirname: false,
__filename: false,
},
}
}
|
class MemorableClass {
static final ArrayList list = new ArrayList(100);
}
Calling String.intern() on lengthy String
String str=readString(); // read lengthy string any source db,textbox/jsp etc..
// This will place the string in memory pool from which you cant remove
str.intern();
(Unclosed) open streams ( file , network etc... )
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
...
...
} catch (Exception e) {
e.printStacktrace();
}
Unclosed connections
try {
Connection conn = ConnectionFactory.getConnection();
...
...
} catch (Exception e) {
e.printStacktrace();
}
|
import React, { PropTypes as T } from 'react';
import ReactModal2 from 'react-modal2';
export default class Modal extends React.Component {
static propTypes = {
children: T.node,
onClose: T.func.isRequired,
closeOnEsc: T.bool,
closeOnBackdropClick: T.bool,
};
static defaultProps = {
closeOnEsc: true,
closeOnBackdropClick: true,
onClose: () => {
},
};
constructor(props) {
super(props);
this.handleBackdropClick = this.handleBackdropClick.bind(this);
}
handleBackdropClick() {
const { onClose, closeOnBackdropClick } = this.props;
if (closeOnBackdropClick) {
onClose();
}
}
render() {
const {
onClose,
closeOnEsc,
closeOnBackdropClick,
children,
} = this.props;
return (
<ReactModal2
onClose={onClose}
closeOnEsc={closeOnEsc}
closeOnBackdropClick={closeOnBackdropClick}
backdropClassName="Modal"
modalClassName="Modal-content"
>
<div className="Modal-close" onClick={this.handleBackdropClick}>
{children}
</div>
</ReactModal2>
);
}
}
|
Thorax.templatePathPrefix = 'templates/';
var Application = window.Application = module.exports = new Thorax.Application(module.exports);
$(document).ready(function() {
$('body').append(Application.el);
Application.start({
pushState: false,
root: '/'
});
});
|
// methods
import curry from './curry';
// utils
import coalesceToArray from './_utils/coalesceToArray';
import isObject from './_utils/isObject';
/**
* @function takeObject
*
* @description
* get the first n number of items in an object
*
* @param {number} size the number of items to get from the end of the object
* @param {Object} object the object of items to get the first n items from
* @param {Array<string>} keys the keys of the object
* @return {Object} the first n number of items
*/
function takeObject(size, object, keys) {
let index = -1,
newObject = {},
key;
while (++index < size) {
key = keys[index];
newObject[key] = object[key];
}
return newObject;
}
/**
* @function takeArray
*
* @description
* get the first n number of items in an array
*
* @param {number} size the number of items to get from the end of the array
* @param {Array<*>} array the array of items to get the first n items from
* @return {Array<*>} the first n number of items
*/
function takeArray(size, array) {
return size > 0 ? array.slice(0, size) : [];
}
/**
* @function take
*
* @description
* get the first n number of items in a collection
*
* @param {number} size the number of items to get from the end of the collection
* @param {Array<*>|Object} collection the collection of items to get the first n items from
* @return {Array<*>|Object} the first n number of items
*/
export default curry(function take(size, collection) {
return isObject(collection)
? takeObject(size, collection, Object.keys(collection))
: takeArray(size, coalesceToArray(collection));
});
|
_gaq.push(['_trackPageview']);
// If awaiting activation
var waiting = false;
// If trusted exit, for exit confirmation
var trustedExit = false;
// Show game screens
function ActivateGame(){
waiting = false;
$(".box-wrap").css("background", "#fff");
$(".box-wait").hide();
$(".box-game .game-swf").attr("src", localStorage.absoluteswf);
$(".box-game").show();
$(".box-wrap").css("zoom", ((ConfigManager.api_gameScale || 100) / 100));
}
$(document).on("ready", function(){
// Initialize data managers
ConfigManager.load();
KC3Meta.init("../../../../data/");
KC3QuestManager.load();
// Apply interface configs
$(".box-wrap").css("margin-top", ConfigManager.api_margin+"px");
if(ConfigManager.api_bg_image === ""){
$("body").css("background", ConfigManager.api_bg_color);
}else{
$("body").css("background-image", "url("+ConfigManager.api_bg_image+")");
$("body").css("background-color", ConfigManager.api_bg_color);
$("body").css("background-size", ConfigManager.api_bg_size);
$("body").css("background-position", ConfigManager.api_bg_position);
$("body").css("background-repeat", "no-repeat");
}
$(".box-wait .api_txt").attr("title",KC3Meta.term("APIConcealExpl"));
// API link determines which screen to show
if(localStorage.absoluteswf){
$(".api_txt textarea").text(localStorage.absoluteswf);
$(".box-wait").show();
waiting = true;
}else{
$(".box-nolink").show();
}
// Update API Link
$(".api_submit").on('click', function(){
if($(".api_text").val().indexOf("mainD2.swf") > -1){
localStorage.absoluteswf = $(".api_text").val();
trustedExit = true;
window.location.reload();
}
});
// Forget API Link
$(".forget_btn").on('click', function(){
localStorage.absoluteswf = "";
trustedExit = true;
window.location.reload();
});
// Quick Play
$(".play_btn").on('click', function(){
ActivateGame();
});
// Disable Quick Play (must panel)
if(ConfigManager.api_mustPanel) {
$(".play_btn")
.off('click')
.text(KC3Meta.term("APIWaitToggle"))
.css('color','#f00')
.css('width','40%');
}
// Configure Refresh Toggle (using $(".game-refresh").trigger("click") is possible)
$(".game-refresh").on("click",function(){
switch($(this).text()) {
case("01"):
$(".game-swf").attr("src","about:blank").attr("src",localStorage.absoluteswf);
$(this).text("05");
break;
default:
$(this).text("0" + ($(this).text()-1));
break;
}
});
// Enable Refresh Toggle
if(ConfigManager.api_directRefresh) {
$(".game-refresh").css("display","flex");
}
// Exit confirmation
window.onbeforeunload = function(){
ConfigManager.load();
// added waiting condition should be ignored
if(ConfigManager.api_askExit==1 && !trustedExit && !waiting){
trustedExit = true;
setTimeout(function(){ trustedExit = false; }, 100);
return KC3Meta.term("UnwantedExit");
}
};
setInterval(function(){
window.focus();
}, 100);
});
$(document).on("keydown", function(event){
// F9: Screenshot
if(event.keyCode == 120){
(new KCScreenshot()).start("Auto", $(".box-wrap"));
return false;
}
// F10: Clear overlays
if(event.keyCode == 121){
interactions.clearOverlays({}, {}, function(){});
return false;
}
});
/* Invokable actions
-----------------------------------*/
var interactions = {
// Panel is opened, activate the game
activateGame :function(request, sender, response){
if(waiting){
ActivateGame();
response({success:true});
}else{
response({success:false});
}
},
// Quest page is opened, show overlays
questOverlay :function(request, sender, response){
// If translations enabled for API screen
if(!ConfigManager.api_translation){ response({success:false}); return true; }
KC3QuestManager.load();
$.each(request.questlist, function( index, QuestRaw ){
// console.log("showing quest",QuestRaw);
if( QuestRaw !=- 1 ){
var QuestBox = $("#factory .ol_quest_exist").clone().appendTo(".overlay_quests");
// Get quest data
var QuestData = KC3QuestManager.get( QuestRaw.api_no );
// Show meta, title and description
if( typeof QuestData.meta().available != "undefined" ){
$(".name", QuestBox).text( QuestData.meta().name );
$(".desc", QuestBox).text( QuestData.meta().desc );
if(ConfigManager.api_tracking){
$(".tracking", QuestBox).html( QuestData.outputHtml() );
}else{
$(".tracking", QuestBox).hide();
}
// Special Bw1 case multiple requirements
if( QuestRaw.api_no == 214 ){
$(".tracking", QuestBox).addClass("small");
}
}else{
QuestBox.css({ visibility: "hidden" });
}
}
});
response({success:true});
},
// Quest Progress Notification
questProgress :function(request, sender, response){
response({success:true});
},
// In-game record screen translation
recordOverlay :function(request, sender, response){
// app.Dom.applyRecordOverlay(request.record);
response({success:true});
},
// Remove HTML overlays
clearOverlays :function(request, sender, response){
console.log("clearing overlays");
// app.Dom.clearOverlays();
$(".overlay_quests").html("");
$(".overlay_record").hide();
response({success:true});
},
// Screenshot triggered, capture the visible tab
screenshot :function(request, sender, response){
// ~Please rewrite the screenshot script
(new KCScreenshot()).start(request.playerName, $(".box-wrap"));
response({success:true});
},
// Fit screen
fitScreen :function(request, sender, response){
var GameScale = ((ConfigManager.api_gameScale || 100) / 100);
// Get browser zoon level for the page
chrome.tabs.getZoom(null, function(ZoomFactor){
// Resize the window
chrome.windows.getCurrent(function(wind){
chrome.windows.update(wind.id, {
width: Math.ceil(800*GameScale*ZoomFactor) + (wind.width- Math.ceil($(window).width()*ZoomFactor) ),
height: Math.ceil(480*GameScale*ZoomFactor) + (wind.height- Math.ceil($(window).height()*ZoomFactor) )
});
});
});
},
// Dummy action
dummy :function(request, sender, response){
}
};
/* Listen to messaging triggers
-----------------------------------*/
chrome.runtime.onMessage.addListener(function(request, sender, response){
// If request is for this script
if((request.identifier||"") == "kc3_gamescreen"){
// If action requested is supported
if(typeof interactions[request.action] !== "undefined"){
// Execute the action
interactions[request.action](request, sender, response);
return true;
}
}
});
|
import { all } from 'redux-saga/effects';
import { actionCreator, asyncActionCreators, createAxiosSaga } from './utils';
import { appName } from '../config';
/**
* Constants
* */
export const moduleName = 'main';
const prefix = `${appName}/${moduleName}`;
export const CONST_EXAMPLE = `${prefix}/CONST_EXAMPLE`;
/**
* Reducer
* */
export default (state = {}, action) => {
const { type } = action;
switch (type) {
default:
return state;
}
};
/**
* Selectors
* */
/**
* Action Creators
* */
export const exampleAction = actionCreator(CONST_EXAMPLE);
export const exampleAsyncAction = asyncActionCreators(CONST_EXAMPLE);
/**
* Sagas
* */
export const exampleSaga = createAxiosSaga(exampleAsyncAction);
export const saga = function*() {
yield all([exampleSaga()]);
};
|
/**
* @jest-environment jsdom
*/
/* eslint import/extensions: [0, {}] */
/* eslint import/no-unresolved: [0, {}] */
import DOMRouter from 'core/DOMRouter';
describe('DOMRouter', () => {
test('can trigger the right controller using data attributes on the <body> tag', async () => {
const testController01 = {
init: jest.fn(),
doSomething: jest.fn(),
doSomethingElse: jest.fn(),
};
const testController02 = { init: jest.fn(), doSomethingElseAgain: jest.fn() };
const controllers = { test01: () => testController01, test02: () => testController02 };
const router = new DOMRouter(controllers);
// Set up our document body
document.body.setAttribute('data-controller', 'test01');
document.body.setAttribute('data-action', 'doSomething');
await router.init();
expect(testController01.init).toHaveBeenCalled();
expect(testController01.doSomething).toHaveBeenCalled();
expect(testController01.doSomethingElse).not.toHaveBeenCalled();
expect(testController02.init).not.toHaveBeenCalled();
expect(testController02.doSomethingElseAgain).not.toHaveBeenCalled();
});
});
|
const cliConfig = require('./cli-config');
const path = require('path');
const chalk = require('chalk');
const program = require('commander');
const commands = require('./commands');
const {common} = require('./utils');
const dependencyManager = common.getDependencyManager(process.cwd());
const packageVersion = common.getPackageVersion();
const npmVersion = commands.check.version({dependencyManager, package: `${cliConfig.CLI_NAME}`});
program
.version(chalk.green(packageVersion));
program
.command('v')
.description(`Provides the current ${cliConfig.CLI_NAME} version`)
.action(() => {
console.log(chalk.green(packageVersion));
checkVersion();
});
program
.command('docs')
.description(`Redirects you to ${cliConfig.CLI_NAME}\'s documentation`)
.action(() => {
commands.docs.run({url: cliConfig.CLI_DOCUMENT_URL});
checkVersion();
});
program
.command('new [name]')
.description('Creates new project')
.option('--style <style>', 'What cascading style to use in your project')
.option('--router', 'Includes react-router library in your project')
.option('--redux', 'Includes redux, react-redux and react-redux-router libraries in your project')
.option('--skip-dependencies', 'Skips the installation of the project\'s yarn or npm dependencies')
.action((name, options) => {
console.log(chalk.green(`Creating new project "${name || path.basename(process.cwd())}"...`));
commands.new.project(Object.assign({},
{name, version: packageVersion}, {cmd: options}), (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`${data}`));
checkVersion();
});
});
program
.command('generate <type> <name>')
.description('Creates new component for project or library')
.alias('g')
.option('--redux', 'Includes redux actions and reducers for a component')
.action((type, name, options) => {
if (!common.readLocalConfig(process.cwd()))
return checkIfReactXtructProject();
if (type.toLowerCase() === 'container') {
console.log(chalk.green(`Generating container component "${name}"...`));
commands.generate.container(Object.assign({}, {type, name}, {
cmd: options,
path: process.cwd()
}), (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`${data}`));
checkVersion();
});
} else {
console.log(chalk.green(`Generating component "${name}"...`));
commands.generate.component(Object.assign({}, {type, name}, {
cmd: options,
path: process.cwd()
}), (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`${data}`));
checkVersion();
});
}
});
program
.command('build')
.description('Builds project or library')
.alias('b')
.option('-e, --environment <env>', 'Which environment to build')
.action((options) => {
if (!common.readLocalConfig(process.cwd()))
return checkIfReactXtructProject();
commands.build.run(Object.assign({}, {cmd: options}), (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`Build done successful!`));
checkVersion();
});
});
program
.command('serve')
.description('Serves project or library')
.option('-p, --port <port>', 'Which port to use to serve')
.alias('s')
.alias('server')
.alias('start')
.action((options) => {
if (!common.readLocalConfig(process.cwd()))
return checkIfReactXtructProject();
commands.serve.run(Object.assign({}, {cmd: options}), (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`${data}`));
checkVersion();
});
});
program
.command('lint')
.description('Lints the project or library')
.alias('l')
.action((options) => {
if (!common.readLocalConfig(process.cwd()))
return checkIfReactXtructProject();
commands.lint.run(options, (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`Lint execution done!`));
checkVersion();
});
});
program
.command('test')
.description('Test the project or library')
.alias('t')
.option('-w, --watch', 'Test will watch any file changes')
.option('-c, --coverage', 'Test will provide test coverage')
.action((options) => {
if (!common.readLocalConfig(process.cwd()))
return checkIfReactXtructProject();
commands.test.run(options, (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`Test execution done!`));
checkVersion();
});
});
program
.command('eject')
.description(`Ejects the project from within the ${cliConfig.CLI_NAME} cli, this action is irreversible!`)
.action((keyValue, options) => {
if (!common.readLocalConfig(process.cwd()))
return checkIfReactXtructProject();
console.log(chalk.green(`Ejecting project "${path.basename(process.cwd())}"...`));
commands.eject.run({
project: common.readLocalConfig(process.cwd()),
version: packageVersion
}, (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`Ejection done successful!`));
checkVersion();
});
});
program
.command('set <keyValue>')
.description('Sets config key-values for the project or library')
.option('-g, --global', 'To make the key-value global')
.action((keyValue, options) => {
commands.set.run(Object.assign({}, {keyValue}, {cmd: options}), (error, data) => {
if (error)
return console.log(chalk.red(`${error}`));
console.log(chalk.green(`${data}`));
checkVersion();
});
});
program
.command('system')
.description('Gets your system information for troubleshooting')
.action(() => {
console.log(chalk.green(`System Info:\n${common.getSystemInfo()}`));
checkVersion();
});
program
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
function checkVersion() {
let npmv = parseInt(npmVersion.replace(/\./g, ''));
let pkgv = parseInt(packageVersion.replace(/\./g, ''));
if (npmv > pkgv) {
console.log(`\n${chalk.yellow(`***** New ${cliConfig.CLI_NAME} version ${npmVersion}!`)} - ${chalk.green('Please install the new version via npm or yarn.\n')}`);
} else if (npmVersion === 'NVA' || packageVersion === 'NPVA') {
console.log(`\n${chalk.yellow(`New ${cliConfig.CLI_NAME} could not find a npm or yarn version. Make sure you have npm or yarn installed!\n`)}`);
}
}
function checkIfReactXtructProject() {
console.log(chalk.red(`Directory is not a ${cliConfig.CLI_NAME} project.`) +
chalk.red('\nRun') + chalk.green(` ${cliConfig.CLI_COMMAND} new project`) + chalk.red(' or ') +
chalk.green(`${cliConfig.CLI_COMMAND} new project NAME`) +
chalk.red(` to create an ${cliConfig.CLI_NAME} project or cd to a ${cliConfig.CLI_NAME} project`));
checkVersion();
}
|
/* global chrome: true */
(function() {
if (window.onbeforeunload !== null) {
chrome.extension.sendRequest({ url: document.documentURI, type: "onbeforeunload", sessionID: "", message: "Site has redefined window.onbeforeunload with " + window.onbeforeunload.toString() }, function(response) {} );
}
}());
|
'use strict';
//使用应用名和依赖定义主模块
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// 启动HTML location模式
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider',
function ($locationProvider, $httpProvider) {
// hashPrefix(前缀): {string}
// Hashbang URLs的前缀 (在Hashbang模式中或者低级浏览器中使用)
// default: '!'
$locationProvider.html5Mode(true).hashPrefix('!');
//添加一个https请求的一个拦截器,当请求返回一定的特殊错误码的时候直接做特殊处理
$httpProvider.interceptors.push('authInterceptor');
}
]);
//run方法会在注入器初始化完成之后运行
angular.module(ApplicationConfiguration.applicationModuleName).run(function ($rootScope, $state, Authentication) {
// 在state改变前检查权限
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (toState.data && toState.data.roles && toState.data.roles.length > 0) {
var allowed = false;
toState.data.roles.forEach(function (role) {
if (Authentication.user.roles !== undefined && Authentication.user.roles.indexOf(role) !== -1) {
allowed = true;
return true;
}
});
if (!allowed) {
event.preventDefault();
if (Authentication.user !== undefined && typeof Authentication.user === 'object') {
$state.go('forbidden');
} else {
$state.go('authentication.signin').then(function () {
//保存要去的状态和参数,当登录之后可以继续
storePreviousState(toState, toParams);
});
}
}
}
});
// 监听路由改变事件来保存历史State
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
storePreviousState(fromState, fromParams);
});
// 保存历史State
function storePreviousState(state, params) {
// only store this state if it shouldn't be ignored
if (!state.data || !state.data.ignoreState) {
$state.previous = {
state: state,
params: params,
href: $state.href(state, params)
};
}
}
});
//定义启动application的初始化方法
angular.element(document).ready(function () {
//Fixing facebook bug with redirect
if (window.location.hash && window.location.hash === '#_=_') {
if (window.history && history.pushState) {
window.history.pushState('', document.title, window.location.pathname);
} else {
// Prevent scrolling by storing the page's current scroll offset
var scroll = {
top: document.body.scrollTop,
left: document.body.scrollLeft
};
window.location.hash = '';
// Restore the scroll offset, should be flicker free
document.body.scrollTop = scroll.top;
document.body.scrollLeft = scroll.left;
}
}
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
|
'use strict';
//Hostels service used to communicate Hostels REST endpoints
angular.module('hostels').factory('Hostels', ['$resource',
function($resource) {
return $resource('hostels/:hostelId', { hostelId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
module.exports = {
'ios' : {
parser : './src/metadata/ios_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-ios.git',
version: '3.1.0'
},
'android' : {
parser : './src/metadata/android_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git',
version: '3.1.0'
},
'wp7' : {
parser : './src/metadata/wp7_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git',
version: '3.1.0'
},
'wp8' : {
parser : './src/metadata/wp8_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git',
version: '3.1.0'
},
'blackberry10' : {
parser : './src/metadata/blackberry10_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-blackberry.git',
version: '3.1.0'
},
'www':{
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-app-hello-world.git',
version: '3.1.0'
},
'firefoxos':{
parser: './src/metadata/firefoxos_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-firefoxos.git',
version: '3.1.0'
},
'windows8':{
parser: './src/metadata/windows8_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-windows.git',
version: '3.1.0'
}
};
var addModuleProperty = require('./src/util').addModuleProperty;
Object.keys(module.exports).forEach(function(key) {
var obj = module.exports[key];
if (obj.parser) {
addModuleProperty(module, 'parser', obj.parser, false, obj);
}
});
|
var StartLayer_root = null;
var StartLayer = cc.Layer.extend({
rootnode:null,
PushBg:null,
TextFieldName:null,
ButtonCertain:null,
PanelNickName:null,
ctor:function () {
this._super();
StartLayer_root = this;
var size = cc.winSize;
this.rootnode = ccs.load(res.StartLayer_json).node;
this.addChild(this.rootnode);
StartLayer_root.PanelNickName = ccui.helper.seekWidgetByName(StartLayer_root.rootnode, "PanelNickName");
StartLayer_root.TextFieldName = ccui.helper.seekWidgetByName(StartLayer_root.rootnode, "TextFieldName");
StartLayer_root.ButtonCertain = this.rootnode.getChildByName("ButtonCertain");
StartLayer_root.ButtonCertain.addTouchEventListener(this.onBackClick);
return true;
},
onBackClick:function(sender,type)
{
console.log("333");
var buttonName = sender.getName();
switch(type)
{
case ccui.Widget.TOUCH_ENDED:
if (buttonName == "ButtonCertain")
{
console.log("11111111111111");
UserData.NickName = StartLayer_root.TextFieldName.getString();
MainScene_root.popLayer();
}
break;
}
}
});
|
import { Random } from 'meteor/random';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';
FlowRouter.route('/', {
name: 'home',
action() {
BlazeLayout.render('layout', { main: 'home' });
},
});
FlowRouter.route('/bailout', {
name: 'home-bailout',
action() {
BlazeLayout.render('layout', { main: 'homeBailout' });
},
});
FlowRouter.route('/ir', {
name: 'home-ir',
action() {
BlazeLayout.render('layout', { main: 'homeIr' });
},
});
FlowRouter.route('/new', {
name: 'create',
action() {
BlazeLayout.render('layout', { main: 'new' });
},
});
FlowRouter.route('/admin', {
name: 'adminActions',
action() {
BlazeLayout.render('layout', { main: 'adminActions' });
},
});
FlowRouter.route('/admin/list', {
name: 'adminList',
action() {
BlazeLayout.render('layout', { main: 'adminList' });
},
});
FlowRouter.route('/job/new', {
name: 'jobCreate',
triggersEnter: [(context, redirect) => {
redirect(`/job/${Random.id()}`);
}],
});
FlowRouter.route('/job/:_publicId', {
name: 'jobHome',
action({ _publicId }) {
Meteor.call('job:getOrCreate', { _publicId }, () => BlazeLayout.render('layout', { main: 'jobHome' }));
},
});
FlowRouter.route('/ir/new', {
name: 'irjobCreate',
triggersEnter: [(context, redirect) => {
redirect(`/ir/${Random.id()}`);
}],
});
FlowRouter.route('/irhydra', {
name: 'irhydraRedirect',
action() {
const root = process.env.ROOT_URL || 'localhost:3000';
const path = FlowRouter.current().path;
document.location.assign(`${root}/${path}`);
window.location.reload();
return;
},
});
FlowRouter.route('/ir/:_publicId', {
name: 'irjobHome',
action({ _publicId }) {
Meteor.call('irjob:getOrCreate', { _publicId }, () => BlazeLayout.render('layout', { main: 'irjobHome' }));
},
});
|
/**
* Simple link handler. Registers after template expansions, as an
* asynchronous transform.
*
* TODO: keep round-trip information in meta tag or the like
*/
'use strict';
var coreutil = require('util');
var defines = require('../parser.defines.js');
var PegTokenizer = require('../tokenizer.js').PegTokenizer;
var WikitextConstants = require('../../config/WikitextConstants.js').WikitextConstants;
var Sanitizer = require('./Sanitizer.js').Sanitizer;
var Util = require('../../utils/Util.js').Util;
var TokenHandler = require('./TokenHandler.js');
var DU = require('../../utils/DOMUtils.js').DOMUtils;
var JSUtils = require('../../utils/jsutils.js').JSUtils;
// define some constructor shortcuts
var KV = defines.KV;
var EOFTk = defines.EOFTk;
var TagTk = defines.TagTk;
var SelfclosingTagTk = defines.SelfclosingTagTk;
var EndTagTk = defines.EndTagTk;
var lastItem = JSUtils.lastItem;
/**
* @class
* @extends TokenHandler
* @constructor
*/
function WikiLinkHandler() {
TokenHandler.apply(this, arguments);
}
coreutil.inherits(WikiLinkHandler, TokenHandler);
WikiLinkHandler.prototype.rank = 1.15; // after AttributeExpander
WikiLinkHandler.prototype.init = function() {
// Handle redirects first (since they used to emit additional link tokens)
this.manager.addTransform(this.onRedirect.bind(this),
'WikiLinkHandler:onRedirect', this.rank, 'tag', 'mw:redirect');
// Now handle regular wikilinks.
this.manager.addTransform(this.onWikiLink.bind(this),
'WikiLinkHandler:onWikiLink', this.rank + 0.001, 'tag', 'wikilink');
// Create a new peg parser for image options.
if (!this.urlParser) {
// Actually the regular tokenizer, but we'll call it with the
// url rule only.
WikiLinkHandler.prototype.urlParser = new PegTokenizer(this.env);
}
};
/**
* Normalize and analyze a wikilink target.
*
* Returns an object containing
* - href: the expanded target string
* - hrefSrc: the original target wikitext
* - title: a title object *or*
* language: an interwikiInfo object *or*
* interwiki: an interwikiInfo object
* - localprefix: set if the link had a localinterwiki prefix (or prefixes)
* - fromColonEscapedText: target was colon-escaped ([[:en:foo]])
* - prefix: the original namespace or language/interwiki prefix without a
* colon escape
*
* @return {Object} The target info
*/
WikiLinkHandler.prototype.getWikiLinkTargetInfo = function(token) {
var hrefInfo = Util.lookupKV(token.attribs, 'href');
var info = {
href: Util.tokensToString(hrefInfo.v),
hrefSrc: hrefInfo.vsrc,
};
var env = this.manager.env;
if (/^:/.test(info.href)) {
info.fromColonEscapedText = true;
// remove the colon escape
info.href = info.href.substr(1);
}
// strip ./ prefixes
info.href = info.href.replace(/^(?:\.\/)+/, '');
var hrefBits = info.href.match(/^([^:]+):(.*)$/);
var title = env.resolveTitle(Util.decodeURI(info.href));
if (hrefBits) {
var nsPrefix = hrefBits[1];
info.prefix = nsPrefix;
var nnn = Util.normalizeNamespaceName(nsPrefix.trim());
var interwikiInfo = env.conf.wiki.interwikiMap.get(nnn);
// check for interwiki / language links
// SSS FIXME: Use a map for namespaceIds!
var ns = env.conf.wiki.namespaceIds.hasOwnProperty(nnn) ? env.conf.wiki.namespaceIds[nnn] : undefined;
// also check for url to protect against [[constructor:foo]]
if (ns !== undefined) {
info.title = env.makeTitleFromURLDecodedStr(title);
} else if (interwikiInfo && interwikiInfo.localinterwiki !== undefined) {
if (hrefBits[2] === '') {
// Empty title => main page (T66167)
info.title = env.makeTitleFromURLDecodedStr(env.conf.wiki.mainpage);
} else {
info.href = hrefBits[2];
// Recurse!
var hrefKV = new KV
('href', (/:/.test(info.href) ? ':' : '') + info.href);
hrefKV.vsrc = info.hrefSrc;
info = this.getWikiLinkTargetInfo
(new TagTk('a', [hrefKV], token.dataAttribs));
info.localprefix = nsPrefix +
(info.localprefix ? (':' + info.localprefix) : '');
}
} else if (interwikiInfo && interwikiInfo.url) {
info.href = hrefBits[2];
// Interwiki or language link? If no language info, or if it starts
// with an explicit ':' (like [[:en:Foo]]), it's not a language link.
if (info.fromColonEscapedText ||
(interwikiInfo.language === undefined && interwikiInfo.extralanglink === undefined)) {
// An interwiki link.
info.interwiki = interwikiInfo;
} else {
// A language link.
info.language = interwikiInfo;
}
} else {
info.title = env.makeTitleFromURLDecodedStr(title);
}
} else {
info.title = env.makeTitleFromURLDecodedStr(title);
}
return info;
};
/**
* Handle mw:redirect tokens.
*/
WikiLinkHandler.prototype.onRedirect = function(token, frame, cb) {
// Avoid duplicating the link-processing code by invoking the
// standard onWikiLink handler on the embedded link, intercepting
// the generated tokens using the callback mechanism, reading
// the href from the result, and then creating a
// <link rel="mw:PageProp/redirect"> token from it.
var rlink = new SelfclosingTagTk('link', Util.clone(token.attribs), Util.clone(token.dataAttribs));
var wikiLinkTk = rlink.dataAttribs.linkTk;
rlink.setAttribute('rel', 'mw:PageProp/redirect');
// Remove the nested wikiLinkTk token and the cloned href attribute
rlink.dataAttribs.linkTk = undefined;
rlink.removeAttribute('href');
// Transfer href attribute back to wikiLinkTk, since it may have been
// template-expanded in the pipeline prior to this point.
wikiLinkTk.attribs = Util.clone(token.attribs);
// Set "redirect" attribute on the wikilink token to indicate that
// image and category links should be handled as plain links.
wikiLinkTk.setAttribute('redirect', 'true');
// Render the wikilink (including interwiki links, etc) then collect
// the resulting href and transfer it to rlink.
this.onWikiLink(wikiLinkTk, frame, function(r) {
var isValid = r && r.tokens && r.tokens[0] &&
/^(a|link)$/.test(r.tokens[0].name);
if (isValid) {
var da = r.tokens[0].dataAttribs;
rlink.addNormalizedAttribute('href', da.a.href, da.sa.href);
cb ({ tokens: [rlink] });
} else {
// Bail! Emit tokens as if they were parsed as a list item:
// #REDIRECT....
var src = rlink.dataAttribs.src;
var tsr = rlink.dataAttribs.tsr;
var srcMatch = /^([^#]*)(#)/.exec(src);
var ntokens = srcMatch[1].length ? [ srcMatch[1] ] : [];
var hashPos = tsr[0] + srcMatch[1].length;
var li = new TagTk('listItem', [], { tsr: [hashPos, hashPos + 1] });
li.bullets = [ '#' ];
ntokens.push(li);
ntokens.push(src.slice(srcMatch[0].length));
cb ({ tokens: ntokens.concat(r.tokens) });
}
});
};
/**
* Handle a mw:WikiLink token.
*/
WikiLinkHandler.prototype.onWikiLink = function(token, frame, cb) {
var env = this.manager.env;
// move out
var attribs = token.attribs;
var redirect = Util.lookup(attribs, 'redirect');
var target;
try {
target = this.getWikiLinkTargetInfo(token);
} catch (e) {
// Invalid title
target = null;
}
// First check if the expanded href contains a pipe.
if (target && /[|]/.test(target.href)) {
// It does. This 'href' was templated and also returned other
// parameters separated by a pipe. We don't have any sane way to
// handle such a construct currently, so prevent people from editing
// it.
// TODO: add useful debugging info for editors ('if you would like to
// make this content editable, then fix template X..')
// TODO: also check other parameters for pipes!
cb ({ tokens: Util.placeholder(null, token.dataAttribs) });
return;
}
if (!target || !env.isValidLinkTarget(token.getAttribute("href"))) {
var tokens = ["[["];
if (/mw:ExpandedAttrs/.test(token.getAttribute("typeof"))) {
var dataMW = JSON.parse(token.getAttribute("data-mw")).attribs;
var html;
for (var i = 0; i < dataMW.length; i++) {
if (dataMW[i][0].txt === "href") {
html = dataMW[i][1].html;
break;
}
}
// Since we are splicing off '[[' and ']]' from the incoming token,
// adjust TSR of the DOM-fragment by 2 each on both end.
var tsr = token.dataAttribs && token.dataAttribs.tsr;
if (tsr && typeof (tsr[0]) === 'number' && typeof (tsr[1]) === 'number') {
tsr = [tsr[0] + 2, tsr[1] - 2];
} else {
tsr = null;
}
tokens = tokens.concat(DU.buildDOMFragmentTokens(env, token, html, null, {noPWrapping: true, tsr: tsr}));
} else {
// FIXME: Duplicate work
tokens[0] += Util.tokensToString(token.getAttribute("href"));
}
// Append rest of the attributes
token.attribs.forEach(function(a) {
if (a.k === "mw:maybeContent") {
tokens = tokens.concat("|", a.v);
}
});
tokens.push("]]");
cb({tokens: tokens});
return;
}
// Ok, it looks like we have a sane href. Figure out which handler to use.
var handler = this.getWikiLinkHandler(token, target, redirect);
// and call it.
handler(token, frame, cb, target);
};
/**
* Figure out which handler to use to render a given WikiLink token. Override
* this method to add new handlers or swap out existing handlers based on the
* target structure.
*/
WikiLinkHandler.prototype.getWikiLinkHandler = function(token, target, isRedirect) {
var title = target.title;
if (title) {
if (!target.fromColonEscapedText && !isRedirect) {
if (title.getNamespace().isFile()) {
// Render as a file.
return this.renderFile.bind(this);
} else if (title.getNamespace().isCategory()) {
// Render as a category membership.
return this.renderCategory.bind(this);
}
}
// Colon-escaped or non-file/category links. Render as plain wiki
// links.
return this.renderWikiLink.bind(this);
// language and interwiki links
} else {
if (target.interwiki) {
return this.renderInterwikiLink.bind(this);
} else if (target.language) {
var noLanguageLinks = this.env.page.title.getNamespace().isATalkNamespace() ||
!this.env.conf.wiki.interwikimagic;
if (noLanguageLinks) {
target.interwiki = target.language;
return this.renderInterwikiLink.bind(this);
} else {
return this.renderLanguageLink.bind(this);
}
}
}
// Neither a title, nor a language or interwiki. Should not happen.
throw new Error("Unknown link type");
};
/* ------------------------------------------------------------
* This (overloaded) function does three different things:
* - Extracts link text from attrs (when k === "mw:maybeContent").
* As a performance micro-opt, only does if asked to (getLinkText)
* - Updates existing rdfa type with an additional rdf-type,
* if one is provided (rdfaType)
* - Collates about, typeof, and linkAttrs into a new attr. array
* ------------------------------------------------------------ */
function buildLinkAttrs(attrs, getLinkText, rdfaType, linkAttrs) {
var newAttrs = [];
var linkTextKVs = [];
var about;
// In one pass through the attribute array, fetch about, typeof, and linkText
//
// about && typeof are usually at the end of the array if at all present
for (var i = 0, l = attrs.length; i < l; i++) {
var kv = attrs[i];
var k = kv.k;
var v = kv.v;
// link-text attrs have the key "maybeContent"
if (getLinkText && k === "mw:maybeContent") {
linkTextKVs.push(kv);
} else if (k.constructor === String && k) {
if (k.trim() === "typeof") {
rdfaType = rdfaType ? rdfaType + " " + v : v;
} else if (k.trim() === "about") {
about = v;
} else if (k.trim() === "data-mw") {
newAttrs.push(kv);
}
}
}
if (rdfaType) {
newAttrs.push(new KV('typeof', rdfaType));
}
if (about) {
newAttrs.push(new KV('about', about));
}
if (linkAttrs) {
newAttrs = newAttrs.concat(linkAttrs);
}
return {
attribs: newAttrs,
contentKVs: linkTextKVs,
hasRdfaType: rdfaType !== null,
};
}
/**
* Generic wiki link attribute setup on a passed-in new token based on the
* wikilink token and target. As a side effect, this method also extracts the
* link content tokens and returns them.
*
* @return {Array} Content tokens
*/
WikiLinkHandler.prototype.addLinkAttributesAndGetContent = function(newTk, token, target, buildDOMFragment) {
var attribs = token.attribs;
var dataAttribs = token.dataAttribs;
var newAttrData = buildLinkAttrs(attribs, true, null, [new KV('rel', 'mw:WikiLink')]);
var content = newAttrData.contentKVs;
var env = this.manager.env;
// Set attribs and dataAttribs
newTk.attribs = newAttrData.attribs;
newTk.dataAttribs = Util.clone(dataAttribs);
newTk.dataAttribs.src = undefined; // clear src string since we can serialize this
// Note: Link tails are handled on the DOM in handleLinkNeighbours, so no
// need to handle them here.
if (content.length > 0) {
newTk.dataAttribs.stx = 'piped';
var out = [];
// re-join content bits
for (var i = 0, l = content.length; i < l ; i++) {
var toks = content[i].v;
// since this is already a link, strip autolinks from content
if (!Array.isArray(toks)) { toks = [ toks ]; }
toks = toks.filter(function(t) { return t !== ''; });
toks = toks.map(function(t, j) {
if (t.constructor === TagTk && t.name === 'a') {
if (toks[j + 1] && toks[j + 1].constructor === EndTagTk &&
toks[j + 1].name === 'a') {
// autonumbered links in the stream get rendered
// as an <a> tag with no content -- but these ought
// to be treated as plaintext since we don't allow
// nested links.
return '[' + t.getAttribute('href') + ']';
}
return ''; // suppress <a>
}
if (t.constructor === EndTagTk && t.name === 'a') {
return ''; // suppress </a>
}
return t;
});
toks = toks.filter(function(t) { return t !== ''; });
out = out.concat(toks);
if (i < l - 1) {
out.push('|');
}
}
if (buildDOMFragment) {
// content = [part 0, .. part l-1]
// offsets = [start(part-0), end(part l-1)]
var offsets = dataAttribs.tsr ? [content[0].srcOffsets[0], content[l - 1].srcOffsets[1]] : null;
content = [ Util.getDOMFragmentToken(out, offsets, {noPWrapping: true, noPre: true, token: token}) ];
} else {
content = out;
}
} else {
newTk.dataAttribs.stx = 'simple';
var morecontent = Util.decodeURI(target.href);
// Strip leading colon
morecontent = morecontent.replace(/^:/, '');
// Try to match labeling in core
if (env.conf.wiki.namespacesWithSubpages[env.page.ns]) {
// subpage links with a trailing slash get the trailing slashes stripped.
// See https://gerrit.wikimedia.org/r/173431
var match = morecontent.match(/^((\.\.\/)+|\/)(?!\.\.\/)(.*?[^\/])\/+$/);
if (match) {
morecontent = match[3];
} else if (/^\.\.\//.test(morecontent)) {
morecontent = env.resolveTitle(morecontent);
}
}
// for interwiki links, include the interwiki prefix in the link text
if (target.interwiki) {
morecontent = target.prefix + ':' + morecontent;
}
// for local links, include the local prefix in the link text
if (target.localprefix) {
morecontent = target.localprefix + ':' + morecontent;
}
content = [ morecontent ];
}
return content;
};
/**
* Render a plain wiki link.
*/
WikiLinkHandler.prototype.renderWikiLink = function(token, frame, cb, target) {
var newTk = new TagTk('a');
var content = this.addLinkAttributesAndGetContent(newTk, token, target, true);
newTk.addNormalizedAttribute('href', this.env.makeLink(target.title), target.hrefSrc);
// Add title unless it's just a fragment
if (target.href[0] !== '#') {
newTk.setAttribute('title', target.title.getPrefixedDBKey().replace(/_/g, " "));
}
cb({tokens: [newTk].concat(content, [new EndTagTk('a')])});
};
/**
* Render a category 'link'. Categories are really page properties, and are
* normally rendered in a box at the bottom of an article.
*/
WikiLinkHandler.prototype.renderCategory = function(token, frame, cb, target) {
var tokens = [];
var newTk = new SelfclosingTagTk('link');
var content = this.addLinkAttributesAndGetContent(newTk, token, target);
var env = this.manager.env;
// Change the rel to be mw:PageProp/Category
Util.lookupKV(newTk.attribs, 'rel').v = 'mw:PageProp/Category';
var strContent = Util.tokensToString(content);
var saniContent = Util.sanitizeTitleURI(strContent).replace(/#/g, '%23');
newTk.addNormalizedAttribute('href', env.makeLink(target.title), target.hrefSrc);
// Change the href to include the sort key, if any (but don't update the rt info)
if (strContent && strContent !== '' && strContent !== target.href) {
var hrefkv = Util.lookupKV(newTk.attribs, 'href');
hrefkv.v += '#';
hrefkv.v += saniContent;
}
tokens.push(newTk);
if (content.length === 1) {
cb({tokens: tokens});
} else {
// Deal with sort keys that come from generated content (transclusions, etc.)
cb({ async: true });
var inVals = [ { "txt": "mw:sortKey" }, { "html": content } ];
Util.expandValuesToDOM(
this.manager.env,
this.manager.frame,
inVals,
this.options.wrapTemplates,
function(_, outVals) {
var dataMW = newTk.getAttribute("data-mw");
if (dataMW) {
dataMW = JSON.parse(dataMW);
dataMW.attribs.push(outVals);
} else {
dataMW = { attribs: [outVals] };
}
// Mark token as having expanded attrs
newTk.addAttribute("about", env.newAboutId());
newTk.addSpaceSeparatedAttribute("typeof", "mw:ExpandedAttrs");
newTk.addAttribute("data-mw", JSON.stringify(dataMW));
cb({ tokens: tokens });
}
);
}
};
/**
* Render a language link. Those normally appear in the list of alternate
* languages for an article in the sidebar, so are really a page property.
*/
WikiLinkHandler.prototype.renderLanguageLink = function(token, frame, cb, target) {
// The prefix is listed in the interwiki map
var newTk = new SelfclosingTagTk('link', [], token.dataAttribs);
this.addLinkAttributesAndGetContent(newTk, token, target);
// add title attribute giving the presentation name of the
// "extra language link"
if (target.language.extralanglink !== undefined &&
target.language.linktext) {
newTk.addNormalizedAttribute('title', target.language.linktext);
}
// We set an absolute link to the article in the other wiki/language
var absHref = target.language.url.replace("$1", target.href);
if (target.language.protorel !== undefined) {
absHref = absHref.replace(/^https?:/, '');
}
newTk.addNormalizedAttribute('href', Util.sanitizeURI(absHref), target.hrefSrc);
// Change the rel to be mw:PageProp/Language
Util.lookupKV(newTk.attribs, 'rel').v = 'mw:PageProp/Language';
cb({tokens: [newTk]});
};
/**
* Render an interwiki link.
*/
WikiLinkHandler.prototype.renderInterwikiLink = function(token, frame, cb, target) {
// The prefix is listed in the interwiki map
var tokens = [];
var newTk = new TagTk('a', [], token.dataAttribs);
var content = this.addLinkAttributesAndGetContent(newTk, token, target, true);
// We set an absolute link to the article in the other wiki/language
var absHref = target.interwiki.url.replace("$1", target.href);
if (target.interwiki.protorel !== undefined) {
absHref = absHref.replace(/^https?:/, '');
}
newTk.addNormalizedAttribute('href', Util.sanitizeURI(absHref), target.hrefSrc);
// Change the rel to be mw:ExtLink
Util.lookupKV(newTk.attribs, 'rel').v = 'mw:ExtLink';
// Remember that this was using wikitext syntax though
newTk.dataAttribs.isIW = true;
// Add title unless it's just a fragment (and trim off fragment)
// (The normalization here is similar to what Title#getPrefixedDBKey() does.)
if (target.href[0] !== "#") {
var titleAttr =
target.interwiki.prefix + ':' +
Util.decodeURI
(target.href.replace(/#[\s\S]*/, '').replace(/_/g, ' '));
newTk.setAttribute("title", titleAttr);
}
tokens.push(newTk);
tokens = tokens.concat(content,
[new EndTagTk('a')]);
cb({tokens: tokens});
};
/**
* Extract the dimensions for an image
*/
function handleSize(info) {
var width, height;
if (info.height) {
height = info.height;
}
if (info.width) {
width = info.width;
}
if (info.thumburl && info.thumbheight) {
height = info.thumbheight;
}
if (info.thumburl && info.thumbwidth) {
width = info.thumbwidth;
}
return {
height: height,
width: width,
};
}
/**
* Get the format for an image.
*/
function getFormat(opts) {
if (opts.manualthumb) {
return "thumbnail";
}
return opts.format && opts.format.v;
}
/**
* Get the style and class lists for an image's wrapper element
*
* @private
* @param {Object} opts The option hash from renderFile
* @return {Object}
* @return {boolean} return.isInline Whether the image is inline after handling options
* @return {boolean} return.isFloat Whether the image is floated after handling options
* @return {Array} return.classes The list of classes for the wrapper
* @return {Array} return.styles The list of styles for the wrapper
*/
function getWrapperInfo(opts) {
var format = getFormat(opts);
var isInline = !(format === 'thumbnail' || format === 'framed');
var wrapperStyles = [];
var wrapperClasses = [];
var halign = (opts.format && opts.format.v === 'framed') ? 'right' : null;
var valign = 'middle';
var isFloat = false;
if (!opts.size.src) {
wrapperClasses.push('mw-default-size');
}
if (opts.border) {
wrapperClasses.push('mw-image-border');
}
if (opts.halign) {
halign = opts.halign.v;
}
var halignOpt = opts.halign && opts.halign.v;
switch (halign) {
case 'none':
// PHP parser wraps in <div class="floatnone">
isInline = false;
if (halignOpt === 'none') {
wrapperClasses.push('mw-halign-none');
}
break;
case 'center':
// PHP parser wraps in <div class="center"><div class="floatnone">
isInline = false;
wrapperStyles.push('text-align: center;');
if (halignOpt === 'center') {
wrapperClasses.push('mw-halign-center');
}
break;
case 'left':
// PHP parser wraps in <div class="floatleft">
isInline = false;
isFloat = true;
wrapperStyles.push('float: left;');
if (halignOpt === 'left') {
wrapperClasses.push('mw-halign-left');
}
break;
case 'right':
// PHP parser wraps in <div class="floatright">
isInline = false;
isFloat = true;
// XXX: remove inline style
wrapperStyles.push('float: right;');
if (halignOpt === 'right') {
wrapperClasses.push('mw-halign-right');
}
break;
}
if (opts.valign) {
valign = opts.valign.v;
}
if (isInline && !isFloat) {
wrapperStyles.push('vertical-align: ' + valign.replace(/_/, '-') + ';');
}
// always have to add these valign classes (not just when inline)
// otherwise how can we know whether the user has removed them in VE?
if (isInline || true) {
var valignOpt = opts.valign && opts.valign.v;
switch (valignOpt) {
case 'middle':
wrapperClasses.push('mw-valign-middle');
break;
case 'baseline':
wrapperClasses.push('mw-valign-baseline');
break;
case 'sub':
wrapperClasses.push('mw-valign-sub');
break;
case 'super':
wrapperClasses.push('mw-valign-super');
break;
case 'top':
wrapperClasses.push('mw-valign-top');
break;
case 'text_top':
wrapperClasses.push('mw-valign-text-top');
break;
case 'bottom':
wrapperClasses.push('mw-valign-bottom');
break;
case 'text_bottom':
wrapperClasses.push('mw-valign-text-bottom');
break;
}
} else {
wrapperStyles.push('display: block;');
}
return { // jscs:ignore jsDoc
styles: wrapperStyles,
classes: wrapperClasses,
isInline: isInline,
isFloat: isFloat,
};
}
/**
* Abstract way to get the path for an image given an info object
*
* @private
* @param {Object} info
* @param {string|null} info.thumburl The URL for a thumbnail
* @param {string} info.url The base URL for the image
*/
function getPath(info) {
var path = '';
if (info.thumburl) {
path = info.thumburl;
} else if (info.url) {
path = info.url;
}
return path.replace(/^https?:\/\//, '//');
}
/**
* Determine the name of an option
* Returns an object of form
* {
* ck: Canonical key for the image option
* v: Value of the option
* ak: Aliased key for the image option - includes "$1" for placeholder
* s: Whether it's a simple option or one with a value
* }
*/
function getOptionInfo(optStr, env) {
var oText = optStr.trim();
var lowerOText = oText.toLowerCase();
var getOption = env.conf.wiki.getMagicPatternMatcher(
WikitextConstants.Image.PrefixOptions);
// oText contains the localized name of this option. the
// canonical option names (from mediawiki upstream) are in
// English and contain an 'img_' prefix. We drop the
// prefix before stuffing them in data-parsoid in order to
// save space (that's shortCanonicalOption)
var canonicalOption = (env.conf.wiki.magicWords[oText] ||
env.conf.wiki.magicWords[lowerOText] ||
('img_' + lowerOText));
var shortCanonicalOption = canonicalOption.replace(/^img_/, '');
// 'imgOption' is the key we'd put in opts; it names the 'group'
// for the option, and doesn't have an img_ prefix.
var imgOption = WikitextConstants.Image.SimpleOptions.get(canonicalOption);
var bits = getOption(optStr.trim());
var normalizedBit0 = bits ? bits.k.trim().toLowerCase() : null;
var key = bits ? WikitextConstants.Image.PrefixOptions.get(normalizedBit0) : null;
if (imgOption && key === null) {
return {
ck: imgOption,
v: shortCanonicalOption,
ak: optStr,
s: true,
};
} else {
// bits.a has the localized name for the prefix option
// (with $1 as a placeholder for the value, which is in bits.v)
// 'normalizedBit0' is the canonical English option name
// (from mediawiki upstream) with an img_ prefix.
// 'key' is the parsoid 'group' for the option; it doesn't
// have an img_ prefix (it's the key we'd put in opts)
if (bits && key) {
shortCanonicalOption = normalizedBit0.replace(/^img_/, '');
// map short canonical name to the localized version used
return {
ck: shortCanonicalOption,
v: bits.v,
ak: optStr,
s: false,
};
} else {
return null;
}
}
}
/**
* Make option token streams into a stringy thing that we can recognize.
*
* @param {Array} tstream
* @param {string} prefix Anything that came before this part of the recursive call stack
* @return {string|null}
*/
function stringifyOptionTokens(tstream, prefix, env) {
var tokenType, tkHref, nextResult, optInfo, skipToEndOf;
var resultStr = '';
prefix = prefix || '';
for (var i = 0; i < tstream.length; i++) {
var currentToken = tstream[i];
if (skipToEndOf) {
if (currentToken.name === skipToEndOf && currentToken.constructor === EndTagTk) {
skipToEndOf = undefined;
}
continue;
}
if (currentToken.constructor === String) {
resultStr += currentToken;
} else if (Array.isArray(currentToken)) {
nextResult = stringifyOptionTokens(currentToken, prefix + resultStr, env);
if (nextResult === null) {
return null;
}
resultStr += nextResult;
} else if (currentToken.constructor !== EndTagTk) {
// This is actually a token
if (currentToken.name === 'span' && currentToken.getAttribute('typeof') === 'mw:Nowiki') {
// if this is a nowiki, we must be in a caption
return null;
}
if (currentToken.name === 'a') {
if (optInfo === undefined) {
optInfo = getOptionInfo(prefix + resultStr, env);
if (optInfo === null) {
// An <a> tag before a valid option?
// This is most likely a caption.
optInfo = undefined;
return null;
}
}
// link and alt options are whitelisted for accepting arbitrary
// wikitext (even though only strings are supported in reality)
// SSS FIXME: Is this actually true of all options rather than
// just link and alt?
if (optInfo.ck === 'link' || optInfo.ck === 'alt') {
tokenType = Util.lookup(currentToken.attribs, 'rel');
tkHref = Util.lookup(currentToken.attribs, 'href');
// Reset the optInfo since we're changing the nature of it
optInfo = undefined;
// Figure out the proper string to put here and break.
if (tokenType === 'mw:ExtLink' &&
currentToken.dataAttribs.stx === 'url') {
// Add the URL
resultStr += tkHref;
// Tell our loop to skip to the end of this tag
skipToEndOf = 'a';
} else if (tokenType === 'mw:WikiLink') {
// Nothing to do -- the link content will be
// captured by walking the rest of the tokens.
} else {
// There shouldn't be any other kind of link...
// This is likely a caption.
return null;
}
} else {
// Why would there be an a tag without a link?
return null;
}
}
}
}
return resultStr;
}
// Set up the actual image structure, attributes etc
WikiLinkHandler.prototype.handleImage = function(opts, info, dataMw) {
var img = new SelfclosingTagTk('img', []);
if ('alt' in opts) {
img.addNormalizedAttribute('alt', opts.alt.v, opts.alt.src);
}
img.addNormalizedAttribute('resource', this.env.makeLink(opts.title.v), opts.title.src);
img.addAttribute('src', getPath(info));
if (opts.lang) {
img.addNormalizedAttribute('lang', opts.lang.v, opts.lang.src);
}
// T110692: The batching API seems to return these as strings.
// Till that is fixed, let us make sure these are numbers.
info.height = Number(info.height);
info.width = Number(info.width);
if (!dataMw.errors) {
// Add (read-only) information about original file size (T64881)
img.addAttribute('data-file-width', String(info.width));
img.addAttribute('data-file-height', String(info.height));
img.addAttribute('data-file-type', info.mediatype && info.mediatype.toLowerCase());
}
var mustRender;
if (info.mustRender !== undefined) {
mustRender = info.mustRender;
} else {
mustRender = info.mediatype !== 'BITMAP';
}
var size = handleSize(info);
// Handle client-side upscaling (including 'border')
if (info.height && info.width) {
// Calculate the scaling ratio from the user-specified width and height
var ratio = null;
if (opts.size.v.height) {
ratio = opts.size.v.height / info.height;
}
if (opts.size.v.width) {
var r = opts.size.v.width / info.width;
ratio = (ratio === null || r < ratio) ? r : ratio;
}
if (ratio !== null && ratio > 1) {
// If the user requested upscaling, then this is denied in the thumbnail
// and frameless format, except for files with mustRender.
var format = getFormat(opts);
if (!mustRender && (format === 'thumbnail' || format === 'frameless')) {
// Upscaling denied
size.height = info.height;
size.width = info.width;
} else {
// Upscaling allowed
// In the batch API, these will already be correct, but the non-batch
// API returns the source width and height whenever client-side scaling
// is requested.
if (!this.env.conf.parsoid.useBatchAPI) {
size.height = Math.round(info.height * ratio);
size.width = Math.round(info.width * ratio);
}
}
}
// Handle "responsive" images, i.e. srcset
if (info.responsiveUrls) {
var density;
var candidates = [];
for (density in info.responsiveUrls) {
candidates.push(
info.responsiveUrls[density].replace(/^https?:\/\//, '//') +
' ' + density + 'x');
}
if (candidates.length > 0) {
img.addAttribute('srcset', candidates.join(', '));
}
}
}
if (size.height) {
img.addNormalizedAttribute('height', String(size.height));
}
if (size.width) {
img.addNormalizedAttribute('width', String(size.width));
}
return {
rdfaType: 'mw:Image',
elt: img,
hasLink: (opts.link === undefined || opts.link && opts.link.v !== ''),
};
};
// Handle a response to an (image|video)info API request.
WikiLinkHandler.prototype.handleInfo = function(cb, token, title, opts, optSources, err, data) {
// FIXME: Not doing this till we fix up wt2html error handling
//
// Bump resource use
// this.manager.env.bumpParserResourceUse('image');
var info;
var errs = [];
if (!err && data) {
if (this.env.conf.parsoid.useBatchAPI) {
info = data.batchResponse;
} else {
var ns = data.imgns;
// `useVideoInfo` is for legacy requests; batching returns thumbdata.
var prop = this.env.conf.wiki.useVideoInfo ? 'videoinfo' : 'imageinfo';
// title is guaranteed to be not null here
var image = data.pages[ns + ':' + title.getKey()];
if (!image || !image[prop] || !image[prop][0] ||
// Fallback to adding mw:Error
(image.missing !== undefined && image.known === undefined)) {
info = false;
} else {
info = image[prop][0];
}
}
}
// FIXME: Make sure our filename is never of the form
// 'File:foo.png|Some caption', as is the case for example in
// [[:de:Portal:Thüringen]]. The href is likely templated where
// the expansion includes the pipe and caption. We don't currently
// handle that case and pass the full string including the pipe to
// the API. The API in turn interprets the pipe as two separate
// titles and returns two results for each side of the pipe. The
// full 'filename' does not match any of them, so image is then
// undefined here. So for now (as a workaround) check if we
// actually have an image to work with instead of crashing.
if (!info) {
// Use sane defaults.
info = {
url: './Special:FilePath/' + (title ? Util.sanitizeTitleURI(title.getKey()) : ''),
// Preserve width and height from the wikitext options
// even if the image is non-existent.
width: opts.size.v.width || 220,
height: opts.size.v.height || opts.size.v.width || 220,
};
// Set appropriate error info
if (title && (err || !data)) {
errs.push({"key": "api-error", "message": err || "Empty API info"});
} else if (opts.manualthumb !== undefined) {
errs.push({
"key": "missing-thumbnail",
"message": "This thumbnail does not exist.",
// Additional error info for clients that could fix the error.
"params": {
"name": opts.manualthumb.v,
},
});
} else {
errs.push({"key": "missing-image", "message": "This image does not exist." });
}
} else if (info.hasOwnProperty('thumberror')) {
errs.push({ key: 'thumb-error', 'message': info.thumberror });
}
var dataMwAttr = token.getAttribute('data-mw');
var dataMw = dataMwAttr ? JSON.parse(dataMwAttr) : {};
// Add error info to data-mw
if (errs.length > 0) {
if (Array.isArray(dataMw.errors)) {
errs = dataMw.errors.concat(errs);
}
dataMw.errors = errs;
}
var o;
switch (info.mediatype && info.mediatype.toLowerCase()) {
default:
o = this.handleImage(opts, info, dataMw);
}
var iContainerName = o.hasLink ? 'a' : 'span';
var innerContain = new TagTk(iContainerName, []);
var innerContainClose = new EndTagTk(iContainerName);
if (o.hasLink) {
if (opts.link) {
// FIXME: handle tokens here!
if (this.urlParser.tokenizeURL(opts.link.v)) {
// an external link!
innerContain.addAttribute('href', opts.link.v, opts.link.src);
} else if (opts.link.v) {
var link = this.env.makeTitleFromText(opts.link.v, undefined, true);
if (link !== null) {
innerContain.addNormalizedAttribute('href', this.env.makeLink(link), opts.link.src);
} else {
// Treat same as if opts.link weren't present
innerContain.addNormalizedAttribute('href', this.env.makeLink(opts.title.v), opts.title.src);
// but maybe consider it a caption
var pos = token.dataAttribs.optList.reduce(function(prv, cur, ind) {
return cur.ck === 'link' ? ind : prv;
}, 0);
if (!opts.caption || opts.caption.pos < pos) {
opts.link.v = opts.link.src;
opts.caption = opts.link;
}
}
}
// No href if link= was specified
} else {
innerContain.addNormalizedAttribute('href', this.env.makeLink(opts.title.v), opts.title.src);
}
}
var wrapperInfo = getWrapperInfo(opts);
var wrapperClasses = wrapperInfo.classes;
var useFigure = wrapperInfo.isInline !== true;
var containerName = useFigure ? 'figure' : 'span';
var container = new TagTk(containerName, [], Util.clone(token.dataAttribs));
var dataAttribs = container.dataAttribs;
var containerClose = new EndTagTk(containerName);
if (!dataAttribs.uneditable) {
dataAttribs.src = undefined;
}
if (opts['class']) {
wrapperClasses = wrapperClasses.concat(opts['class'].v.split(' '));
}
if (wrapperClasses.length) {
container.addAttribute('class', wrapperClasses.join(' '));
}
// FIXME: We don't really want to add inline styles, as people
// will start to depend on them otherwise.
// if (wrapperStyles.length) {
// container.addAttribute( 'style', wrapperStyles.join( ' ' ) );
// }
var rdfaType = o.rdfaType;
var format = getFormat(opts);
// Add mw:Error to the RDFa type.
// Prepend since rdfaType is updated with /<format> further down.
if (errs.length > 0) {
rdfaType = "mw:Error " + rdfaType;
}
// If the format is something we *recognize*, add the subtype
switch (format) {
case 'thumbnail':
rdfaType += '/Thumb';
break;
case 'framed':
rdfaType += '/Frame';
break;
case 'frameless':
rdfaType += '/Frameless';
break;
}
// Tell VE that it shouldn't try to edit this
if (dataAttribs.uneditable) {
rdfaType += " mw:Placeholder";
}
// Set typeof and transfer existing typeof over as well
container.addAttribute("typeof", rdfaType);
var type = token.getAttribute("typeof");
if (type) {
container.addSpaceSeparatedAttribute("typeof", type);
}
var tokens = [container, innerContain].concat(o.elt, innerContainClose);
var manager = this.manager;
var setupDataMW = function(obj, captionDOM) {
if (opts.caption !== undefined) {
if (useFigure) {
tokens = tokens.concat([
new TagTk('figcaption'),
Util.getDOMFragmentToken(
opts.caption.v, opts.caption.srcOffsets, {
noPWrapping: true, noPre: true, token: token,
}),
new EndTagTk('figcaption'),
]);
} else if (!captionDOM) {
if (!Array.isArray(opts.caption.v)) {
opts.caption.v = [ opts.caption.v ];
}
// Parse the caption asynchronously.
return Util.processContentInPipeline(
manager.env, manager.frame,
opts.caption.v.concat([new EOFTk()]), {
pipelineType: "tokens/x-mediawiki/expanded",
pipelineOpts: {
noPWrapping: true, noPre: true, token: token,
},
srcOffsets: opts.caption.srcOffsets,
documentCB: function(doc) {
// Async goto: return to top of function
// with the parsed caption in `captionDOM`
setupDataMW(obj, doc);
},
});
} else {
// Use parsed DOM given in `captionDOM`
obj.caption = DU.ppToXML(captionDOM.body, { innerXML: true });
}
}
if (opts.manualthumb !== undefined) {
obj.thumb = opts.manualthumb.v;
}
if (Object.keys(obj).length) {
container.addAttribute("data-mw", JSON.stringify(obj));
}
tokens.push(containerClose);
cb({ tokens: tokens });
};
if (dataAttribs.uneditable || !optSources) {
setupDataMW(dataMw);
} else {
cb({ async: true });
var inVals = optSources.map(function(e) { return e[1]; });
Util.expandValuesToDOM(manager.env, manager.frame, inVals,
this.options.wrapTemplates, function(e, outVals) {
// FIXME: Do something with `e`?
if (!dataMw.attribs) { dataMw.attribs = []; }
for (var i = 0; i < outVals.length; i++) {
dataMw.attribs.push([optSources[i][0].optKey, outVals[i]]);
}
container.addAttribute("about", manager.env.newAboutId());
container.addSpaceSeparatedAttribute("typeof", "mw:ExpandedAttrs");
setupDataMW(dataMw);
});
}
};
/**
* Render a file. This can be an image, a sound, a PDF etc.
*/
WikiLinkHandler.prototype.renderFile = function(token, frame, cb, target) {
var title = target.title;
// First check if we have a cached copy of this image expansion, and
// avoid any further processing if we have a cache hit.
var env = this.manager.env;
var cachedMedia = env.mediaCache[token.dataAttribs.src];
if (cachedMedia) {
var wrapperTokens = DU.encapsulateExpansionHTML(env, token, cachedMedia, {
noAboutId: true,
setDSR: true,
});
var firstWrapperToken = wrapperTokens[0];
// Capture the delta between the old/new wikitext start posn.
// 'tsr' values are stripped in the original DOM and won't be
// present. Since dsr[0] is identical to tsr[0] in this case,
// dsr[0] is a safe substitute, if present.
var firstDa = firstWrapperToken.dataAttribs;
if (token.dataAttribs.tsr && firstDa.dsr) {
if (!firstDa.tmp) { firstDa.tmp = {}; }
firstDa.tmp.tsrDelta = token.dataAttribs.tsr[0] - firstDa.dsr[0];
}
cb({ tokens: wrapperTokens });
return;
}
// distinguish media types
// if image: parse options
var content = buildLinkAttrs(token.attribs, true, null, null).contentKVs;
// extract options
// option hash
// keys normalized
// values object
// {
// v: normalized value (object with width / height for size)
// src: the original source
// }
//
var opts = {
title: {
v: title,
src: Util.lookupKV(token.attribs, 'href').vsrc,
},
size: {
v: {
height: null,
width: null,
},
},
};
token.dataAttribs.optList = [];
var optKVs = content;
var optSources = [];
var hasExpandableOpt = false;
var hasTransclusion = function(toks) {
return Array.isArray(toks) && toks.find(function(t) {
return t.constructor === SelfclosingTagTk &&
t.getAttribute("typeof") === "mw:Transclusion";
}) !== undefined;
};
while (optKVs.length > 0) {
var oContent = optKVs.shift();
var origOptSrc, optInfo, oText;
origOptSrc = oContent.v;
if (Array.isArray(origOptSrc) && origOptSrc.length === 1) {
origOptSrc = origOptSrc[0];
}
oText = Util.tokensToString(oContent.v, true);
if (oText.constructor !== String) {
// Might be that this is a valid option whose value is just
// complicated. Try to figure it out, step through all tokens.
var maybeOText = stringifyOptionTokens(oText, '', env);
if (maybeOText !== null) {
oText = maybeOText;
}
}
if (oText.constructor === String) {
if (oText.match(/\|/)) {
// Split the pipe-separated string into pieces
// and convert each one into a KV obj and add them
// to the beginning of the array. Note that this is
// a hack to support templates that provide multiple
// image options as a pipe-separated string. We aren't
// really providing editing support for this yet, or
// ever, maybe.
var pieces = oText.split("|").map(function(s) {
return new KV("mw:maybeContent", s);
});
optKVs = pieces.concat(optKVs);
// Record the fact that we won't provide editing support for this.
token.dataAttribs.uneditable = true;
continue;
} else {
optInfo = getOptionInfo(oText, env);
}
}
// For the values of the caption and options, see
// getOptionInfo's documentation above.
//
// If there are multiple captions, this code always
// picks the last entry. This is the spec; see
// "Image with multiple captions" parserTest.
if (oText.constructor !== String || optInfo === null) {
// No valid option found!?
// Record for RT-ing
var optsCaption = {
v: oContent.constructor === String ? oContent : oContent.v,
src: oContent.vsrc || oText,
srcOffsets: oContent.srcOffsets,
// remember the position
pos: token.dataAttribs.optList.length,
};
// if there was a 'caption' previously, round-trip it as a
// "bogus option".
if (opts.caption) {
token.dataAttribs.optList.splice(opts.caption.pos, 0, {
ck: 'bogus',
ak: opts.caption.src,
});
optsCaption.pos++;
}
opts.caption = optsCaption;
continue;
}
var opt = {
ck: optInfo.v,
ak: oContent.vsrc || optInfo.ak,
};
if (optInfo.s === true) {
// Default: Simple image option
if (optInfo.ck in opts) {
// first option wins, the rest are 'bogus'
token.dataAttribs.optList.push({
ck: 'bogus',
ak: optInfo.ak,
});
continue;
}
opts[optInfo.ck] = { v: optInfo.v };
} else {
// Map short canonical name to the localized version used.
opt.ck = optInfo.ck;
// The MediaWiki magic word for image dimensions is called 'width'
// for historical reasons
// Unlike other options, use last-specified width.
if (optInfo.ck === 'width') {
// We support a trailing 'px' here for historical reasons
// (T15500, T53628)
var maybeSize = optInfo.v.match(/^(\d*)(?:x(\d+))?\s*(?:px\s*)?$/);
if (maybeSize !== null) {
opts.size.v.width = maybeSize[1] && Number(maybeSize[1]) || null;
opts.size.v.height = maybeSize[2] && Number(maybeSize[2]) || null;
// Only round-trip a valid size
opts.size.src = oContent.vsrc || optInfo.ak;
}
} else {
if (optInfo.ck in opts) { continue; } // first option wins
opts[optInfo.ck] = {
v: optInfo.v,
src: oContent.vsrc || optInfo.ak,
srcOffsets: oContent.srcOffsets,
};
}
}
// Collect option in dataAttribs (becomes data-parsoid later on)
// for faithful serialization.
token.dataAttribs.optList.push(opt);
// Collect source wikitext for image options for possible template expansion.
// FIXME: Does VE need the wikitext version as well in a "txt" key?
optSources.push([{"optKey": opt.ck }, {"html": origOptSrc}]);
if (hasTransclusion(origOptSrc)) {
hasExpandableOpt = true;
}
}
// Handle image default sizes and upright option after extracting all
// options
if (opts.format && opts.format.v === 'framed') {
// width and height is ignored for framed images
// https://phabricator.wikimedia.org/T64258
opts.size.v.width = null;
opts.size.v.height = null;
} else if (opts.format) {
if (!opts.size.v.height && !opts.size.v.width) {
// Default to 220px thumb width as in WMF configuration
var defaultWidth = 220;
if (opts.upright !== undefined) {
if (opts.upright.v > 0) {
defaultWidth *= opts.upright.v;
} else {
defaultWidth *= 0.75;
}
// round to nearest 10 pixels
defaultWidth = 10 * Math.round(defaultWidth / 10);
}
opts.size.v.width = defaultWidth;
}
}
// Add the last caption in the right position if there is one
if (opts.caption) {
token.dataAttribs.optList.splice(opts.caption.pos, 0, {
ck: 'caption',
ak: opts.caption.src,
});
}
if (!hasExpandableOpt) {
optSources = null;
}
// reset title if this is a manual thumbnail
if (opts.manualthumb) {
title = env.makeTitleFromText(opts.manualthumb.v, undefined, true);
if (title && title.nskey === '') {
// inherit namespace from main image
title.ns = opts.title.v.ns;
title.nskey = opts.title.v.nskey;
}
}
if (!env.conf.parsoid.fetchImageInfo) {
return this.handleInfo(cb, token, title, opts, optSources, 'Fetch of image info disabled.');
} else if (!title) {
return this.handleInfo(cb, token, title, opts, optSources, 'Error creating thumbnail: "' + opts.manualthumb.v + '"');
}
cb({ async: true });
env.batcher.imageinfo(
title.getKey(),
opts.size.v
).nodify(this.handleInfo.bind(this, cb, token, title, opts, optSources));
};
/**
* @class
* @extends TokenHandler
* @constructor
*/
function ExternalLinkHandler() {
TokenHandler.apply(this, arguments);
}
coreutil.inherits(ExternalLinkHandler, TokenHandler);
ExternalLinkHandler.prototype.rank = 1.15;
ExternalLinkHandler.prototype.init = function() {
this.manager.addTransform(this.onUrlLink.bind(this),
'ExternalLinkHandler:onUrlLink', this.rank, 'tag', 'urllink');
this.manager.addTransform(this.onExtLink.bind(this),
'ExternalLinkHandler:onExtLink', this.rank - 0.001, 'tag', 'extlink');
this.manager.addTransform(this.onEnd.bind(this),
'ExternalLinkHandler:onEnd', this.rank, 'end');
// Create a new peg parser for image options.
if (!this.urlParser) {
// Actually the regular tokenizer, but we'll call it with the
// url rule only.
ExternalLinkHandler.prototype.urlParser = new PegTokenizer(this.env);
}
this._reset();
};
ExternalLinkHandler.prototype._reset = function() {
this.linkCount = 1;
};
ExternalLinkHandler.prototype._imageExtensions = {
'jpg': true,
'png': true,
'gif': true,
'svg': true,
};
ExternalLinkHandler.prototype._hasImageLink = function(href) {
var allowedPrefixes = this.manager.env.conf.wiki.allowExternalImages;
var bits = href.split('.');
var hasImageExtension = bits.length > 1 &&
this._imageExtensions.hasOwnProperty(lastItem(bits)) &&
href.match(/^https?:\/\//i);
// Typical settings for mediawiki configuration variables
// $wgAllowExternalImages and $wgAllowExternalImagesFrom will
// result in values like these:
// allowedPrefixes = undefined; // no external images
// allowedPrefixes = ['']; // allow all external images
// allowedPrefixes = ['http://127.0.0.1/', 'http://example.com'];
// Note that the values include the http:// or https:// protocol.
// See https://phabricator.wikimedia.org/T53092
return hasImageExtension && Array.isArray(allowedPrefixes) &&
// true iff some prefix in the list matches href
allowedPrefixes.some(function(prefix) {
return href.indexOf(prefix) === 0;
});
};
ExternalLinkHandler.prototype.onUrlLink = function(token, frame, cb) {
var tagAttrs, builtTag;
var env = this.manager.env;
var origHref = Util.lookup(token.attribs, 'href');
var href = Util.tokensToString(origHref);
var hrefWithEntities = Util.tokensToString(origHref, null, null, true);
var dataAttribs = Util.clone(token.dataAttribs);
if (this._hasImageLink(href)) {
tagAttrs = [
new KV('src', href),
new KV('alt', lastItem(href.split('/'))),
new KV('rel', 'mw:externalImage'),
];
// combine with existing rdfa attrs
tagAttrs = buildLinkAttrs(token.attribs, false, null, tagAttrs).attribs;
cb({ tokens: [ new SelfclosingTagTk('img', tagAttrs, dataAttribs) ] });
} else {
tagAttrs = [
new KV('rel', 'mw:ExtLink'),
// href is set explicitly below
];
// combine with existing rdfa attrs
tagAttrs = buildLinkAttrs(token.attribs, false, null, tagAttrs).attribs;
builtTag = new TagTk('a', tagAttrs, dataAttribs);
dataAttribs.stx = 'url';
if (!this.options.inTemplate) {
// Since we messed with the text of the link, we need
// to preserve the original in the RT data. Or else.
builtTag.addNormalizedAttribute('href', hrefWithEntities, token.getWTSource(env));
} else {
builtTag.addAttribute('href', hrefWithEntities);
}
cb({
tokens: [
builtTag,
// Make sure there are no IDN-ignored characters in the text so
// the user doesn't accidentally copy any.
Sanitizer.cleanUrl(env, hrefWithEntities),
new EndTagTk('a', [], { tsr: [dataAttribs.tsr[1], dataAttribs.tsr[1]] }),
],
});
}
};
// Bracketed external link
ExternalLinkHandler.prototype.onExtLink = function(token, manager, cb) {
var newAttrs, aStart;
var env = this.manager.env;
var origHref = Util.lookup(token.attribs, 'href');
var href = Util.tokensToString(origHref);
var hrefWithEntities = Util.tokensToString(origHref, null, null, true);
var content = Util.lookup(token.attribs, 'mw:content');
var dataAttribs = Util.clone(token.dataAttribs);
var rdfaType = token.getAttribute('typeof');
var magLinkRe = /(?:^|\s)(mw:(?:Ext|Wiki)Link\/(?:ISBN|RFC|PMID))(?=$|\s)/;
if (rdfaType && magLinkRe.test(rdfaType)) {
var newHref = href;
var newRel = 'mw:ExtLink';
if (/(?:^|\s)mw:(Ext|Wiki)Link\/ISBN/.test(rdfaType)) {
newHref = env.page.relativeLinkPrefix + href;
// ISBNs use mw:WikiLink instead of mw:ExtLink
newRel = 'mw:WikiLink';
}
newAttrs = [
new KV('href', newHref),
new KV('rel', newRel),
];
token.removeAttribute('typeof');
// SSS FIXME: Right now, Parsoid does not support templating
// of ISBN attributes. So, "ISBN {{echo|1234567890}}" will not
// parse as you might expect it to. As a result, this code below
// that attempts to combine rdf attrs from earlier is unnecessary
// right now. But, it will become necessary if Parsoid starts
// supporting templating of ISBN attributes.
//
// combine with existing rdfa attrs
newAttrs = buildLinkAttrs(token.attribs, false, null, newAttrs).attribs;
aStart = new TagTk ('a', newAttrs, dataAttribs);
cb({
tokens: [aStart].concat(content, [new EndTagTk('a')]),
});
} else if (this.urlParser.tokenizeURL(hrefWithEntities)) {
rdfaType = 'mw:ExtLink';
if (content.length === 1 &&
content[0].constructor === String &&
this.urlParser.tokenizeURL(content[0]) &&
this._hasImageLink(content[0])) {
var src = content[0];
content = [
new SelfclosingTagTk('img', [
new KV('src', src),
new KV('alt', lastItem(src.split('/'))),
], { type: 'extlink' }),
];
}
newAttrs = [
new KV('rel', rdfaType),
// href is set explicitly below
];
// combine with existing rdfa attrs
newAttrs = buildLinkAttrs(token.attribs, false, null, newAttrs).attribs;
aStart = new TagTk ('a', newAttrs, dataAttribs);
if (!this.options.inTemplate) {
// If we are from a top-level page, add normalized attr info for
// accurate roundtripping of original content.
//
// targetOff covers all spaces before content
// and we need src without those spaces.
var tsr0a = dataAttribs.tsr[0] + 1;
var tsr1a = dataAttribs.targetOff - (token.getAttribute('spaces') || '').length;
aStart.addNormalizedAttribute('href', hrefWithEntities, env.page.src.substring(tsr0a, tsr1a));
} else {
aStart.addAttribute('href', hrefWithEntities);
}
content = Util.getDOMFragmentToken(content, dataAttribs.tsr ? dataAttribs.contentOffsets : null, {noPWrapping: true, noPre: true, token: token});
cb({
tokens: [aStart].concat(content, [new EndTagTk('a')]),
});
} else {
// Not a link, convert href to plain text.
var tokens = ['['];
var closingTok = null;
var spaces = token.getAttribute('spaces') || '';
if ((token.getAttribute("typeof") || "").match(/mw:ExpandedAttrs/)) {
// The token 'non-url' came from a template.
// Introduce a span and capture the original source for RT purposes.
var da = token.dataAttribs;
// targetOff covers all spaces before content
// and we need src without those spaces.
var tsr0b = da.tsr[0] + 1;
var tsr1b = da.targetOff - spaces.length;
var span = Util.placeholder({}, { // {} !== null
tsr: [tsr0b, tsr1b],
src: env.page.src.substring(tsr0b, tsr1b),
})[0]; // We only want the first token.
tokens.push(span);
closingTok = new EndTagTk('span');
}
var hrefText = token.getAttribute("href");
if (Array.isArray(hrefText)) {
tokens = tokens.concat(hrefText);
} else {
tokens.push(hrefText);
}
if (closingTok) {
tokens.push(closingTok);
}
// FIXME: Use this attribute in regular extline
// cases to rt spaces correctly maybe? Unsure
// it is worth it.
if (spaces) {
tokens.push(spaces);
}
if (content.length) {
tokens = tokens.concat(content);
}
tokens.push(']');
cb({ tokens: tokens });
}
};
ExternalLinkHandler.prototype.onEnd = function(token, manager, cb) {
this._reset();
cb({ tokens: [ token ] });
};
if (typeof module === "object") {
module.exports.WikiLinkHandler = WikiLinkHandler;
module.exports.ExternalLinkHandler = ExternalLinkHandler;
}
|
var loadDate = new Date();
console.log(loadDate);
window.setInterval(function(){
getTimeFromLoading();
}, 1000);
function getTimeFromLoading(){
var now = new Date();
var resultado = (now - loadDate);
var seconds = Math.round(resultado/1000);
document.getElementById('time').innerHTML="<strong>The time since the page load is: " +
seconds + " seconds</strong>";
}
// TODO: Look for a more efficient way to do it;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.