code stringlengths 2 1.05M |
|---|
/**
* Simple linked list node
* @param {any} data Any value
* @param {Node} next Link to next node
*/
class Node {
constructor(data = null, next = null) {
this.data = data;
this.next = next;
}
}
module.exports = exports = Node;
|
Meteor.publish('finances', function() {
return Finances.find();
});
|
import React from 'react';
import PropTypes from 'prop-types';
import remark from 'remark';
import {isUndefined} from 'lodash';
import slug from 'remark-slug';
import ghSlugs from 'github-slugger';
import remarkReact from 'remark-react';
import {Element} from 'react-scroll';
import {Link} from 'react-router-dom';
import toc from 'mdast-util-toc';
import frontmatter from 'remark-frontmatter';
const remarkHeading = (component, boundProps = {}) => {
class Heading extends React.Component {
render() {
const slugs = ghSlugs();
const props = {...this.props, ...boundProps};
const [slug] = props.children;
return (
<Element name={`${slugs.slug(slug)}`}>
{React.createElement(component, {...props}, this.props.children)}
</Element>
);
}
}
Heading.propTypes = {
children: PropTypes.element.isRequired
};
return Heading;
};
const RemarkLink = props => {
const {href, children} = props;
if (href && href.startsWith('#') && typeof window.location !== 'undefined') {
return (<Link to={{pathname: window.location.pathname, hash: href}} {...props}>{children}</Link>);
}
if (href && href.startsWith('/')) {
return (<Link to={href} {...props}>{children}</Link>);
}
if (href && typeof window.location !== 'undefined' && !href.includes(window.location.hostname)) {
return (<a href={href} target="_blank" rel="noopener noreferrer">{children}</a>);
}
if (href) {
return (<a href={href} target="_blank" rel="noopener noreferrer">{children}</a>);
}
return (<Link {...props}>{children}</Link>);
};
RemarkLink.propTypes = {
href: PropTypes.string,
children: PropTypes.node.isRequired
};
RemarkLink.defaultProps = {
href: undefined
};
export const remarkConfigDefault = {
remarkReactComponents: {
a: RemarkLink,
h1: remarkHeading('H1'),
h2: remarkHeading('H2'),
h3: remarkHeading('H3'),
h4: remarkHeading('H4'),
h5: remarkHeading('H5'),
h6: remarkHeading('H6')
}
};
export const Markdown = ({component, style, source, children, remarkConfig}) => {
const content = (isUndefined(source) || source === '') ? children : source;
const output = remark().use(frontmatter).use(slug).use(remarkReact, remarkConfig).processSync(content).contents;
return React.createElement(component, {style}, output);
};
Markdown.propTypes = {
component: PropTypes.any,
style: PropTypes.object,
children: PropTypes.node,
source: PropTypes.string,
remarkConfig: PropTypes.object
};
Markdown.defaultProps = {
component: 'div',
style: {},
children: undefined,
source: '',
remarkConfig: remarkConfigDefault
};
export const Toc = ({source, children, remarkConfig}) => {
const content = (isUndefined(source) || source === '') ? children : source;
const tocOut = remark().use(frontmatter).use(() => node => {
node.children = [toc(node, {tight: true}).map];
}).processSync(content).contents;
return (
<Markdown remarkConfig={remarkConfig}>
{tocOut}
</Markdown>
);
};
Toc.propTypes = {
children: PropTypes.node,
source: PropTypes.string,
remarkConfig: PropTypes.object
};
Toc.defaultProps = {
children: undefined,
source: '',
remarkConfig: remarkConfigDefault
};
|
(function() {
'use strict';
angular.module('jwt')
.factory('jwtRestangular', jwtRestangular)
.factory('noTokenRestangular', noTokenRestangular);
/** @ngInject */
function jwtRestangular(Restangular, $sessionStorage, appConfig, $window) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl(appConfig.apiBaseUrl);
RestangularConfigurer.setFullResponse(true);
RestangularConfigurer.setDefaultHeaders({Authorization: 'Bearer ' + $sessionStorage.token});
RestangularConfigurer.setErrorInterceptor(
function ( response ) {
if ( response.status == 401 ) {
alert('Unauthorized - Error 401', 'Musisz się zalogować aby przeglądać zawartość.');
$window.location.href = 'login.html';
}
else {
return response;
}
// Stop the promise chain.
return false;
}
);
});
}
/** @ngInject */
function noTokenRestangular(Restangular, $sessionStorage, appConfig, $window) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl(appConfig.apiBaseUrl);
RestangularConfigurer.setFullResponse(true);
RestangularConfigurer.setErrorInterceptor(
function ( response ) {
if ( response.status == 401 ) {
alert('Unauthorized - Error 401', 'Musisz się zalogować aby przeglądać zawartość.');
$window.location.href = 'login.html';
}
else {
return response;
}
// Stop the promise chain.
return false;
}
);
});
}
})(); |
version https://git-lfs.github.com/spec/v1
oid sha256:002b49e48e55b1804abcec8c833836c8696df57d31a6d76efcb5ac7e116e4c5d
size 193107
|
jQuery(document).ready(function ($) {
envADSR = new ADSR;
document.getElementById("ratioASlider").value = Math.log(0.5 * 1000 + 1) * 200.0 / 12.0;
document.getElementById("ratioDRSlider").value = Math.log(0.0001 * 1000 + 1) * 200.0 / 12.0;
drawAllADSR();
});
function drawAllADSR() {
envADSR.setAttackRate(document.getElementById("attackSlider").value);
envADSR.setDecayRate(document.getElementById("decaySlider").value);
envADSR.setSustainLevel(document.getElementById("sustainSlider").value / 200);
envADSR.setReleaseRate(document.getElementById("releaseSlider").value);
envADSR.setTargetRatioA(0.001 * (Math.exp(12.0 * document.getElementById("ratioASlider").value / 200) - 1.0));
envADSR.setTargetRatioDR(0.001 * (Math.exp(12.0 * document.getElementById("ratioDRSlider").value / 200) - 1.0));
drawADSR();
}
function drawADSR() {
var val;
var envPlot = [];
envADSR.reset();
envADSR.gate(1);
envPlot.push([0, 0]);
var idx;
for (idx = 1; idx < 400; idx++)
envPlot.push([idx, envADSR.process()]);
envADSR.gate(0);
for (idx = 400; idx < 600; idx++)
envPlot.push([idx, envADSR.process()]);
// plot linear or log
if (document.getElementById("PlotType").value == "linear")
Flotr.draw(document.getElementById('adsr-container'), [envPlot], {yaxis: {max: 1.0, min: 0}});
else {
for (idx = 0; idx < 600; idx++) {
val = envPlot[idx][1];
if (val == 0)
envPlot[idx][1] = -200;
else
envPlot[idx][1] = 20 * Math.log(val) / Math.LN10;
}
Flotr.draw(document.getElementById('adsr-container'), [envPlot], {yaxis: {max: 0.0, min: -100}});
}
}
|
var path = require('path');
var fs = require('fs');
// hide warning //
var emitter = require('events');
emitter.defaultMaxListeners = 20;
var appRoot = 'src/';
var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));
var paths = {
root: appRoot,
source: appRoot + '**/*.js',
html: appRoot + '**/*.html',
style: 'styles/**/*.css',
output: 'dist/',
doc:'./doc',
e2eSpecsSrc: 'test/e2e/src/*.js',
e2eSpecsDist: 'test/e2e/dist/',
packageName: pkg.name,
ignore: [],
useTypeScriptForDTS: false,
importsToAdd: [],
sort: false
};
paths.files = [
'analyzer.js',
'getter-observer.js',
'index.js'
].map(function(file){
return paths.root + file;
});
module.exports = paths;
|
var tools = require('./tools')
var Job = require('../../tools/job')
var getCandidatesForJob = require('./getcandidates')
var pickServerFromCandidates = require('./pickserver')
var filterCandidatesForDuplicates = require('./filterduplicates')
// temporarily record the state so the next allocation has a good picture
// this means we can do a batch of allocations without actually commiting them
function injectJobIntoState(job, hostname, state){
state.run['/' + job.id.replace(/-/g, '/')] = hostname
state.deploy['/' + hostname + '/' + job.id] = job.id
}
function allocateServer(etcd, job, state, done){
var candidates = getCandidatesForJob(job, state.host)
candidates = filterCandidatesForDuplicates(job, candidates, state.run)
if(!candidates || !candidates.length){
return done()
}
pickServerFromCandidates(etcd, state, job, candidates, function(err, server){
if(err) return done(err)
if(!server) return done()
injectJobIntoState(job, server.name, state)
done(null, server)
})
}
module.exports = allocateServer |
import React from 'react'
const Todo = ({text, completed, onClick}) => (
<li style={{
textDecoration: completed ? 'line-through' : 'none'
}}
onClick={onClick}
>
{text}
</li>
)
export default Todo
|
ScalaJS.is.scala_collection_TraversableViewLike$Forced = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_TraversableViewLike$Forced)))
});
ScalaJS.as.scala_collection_TraversableViewLike$Forced = (function(obj) {
if ((ScalaJS.is.scala_collection_TraversableViewLike$Forced(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.collection.TraversableViewLike$Forced")
}
});
ScalaJS.isArrayOf.scala_collection_TraversableViewLike$Forced = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_TraversableViewLike$Forced)))
});
ScalaJS.asArrayOf.scala_collection_TraversableViewLike$Forced = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_collection_TraversableViewLike$Forced(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.collection.TraversableViewLike$Forced;", depth)
}
});
ScalaJS.data.scala_collection_TraversableViewLike$Forced = new ScalaJS.ClassTypeData({
scala_collection_TraversableViewLike$Forced: 0
}, true, "scala.collection.TraversableViewLike$Forced", undefined, {
scala_collection_TraversableViewLike$Forced: 1,
scala_collection_GenTraversableViewLike$Forced: 1,
scala_collection_TraversableViewLike$Transformed: 1,
scala_collection_GenTraversableViewLike$Transformed: 1,
scala_collection_TraversableView: 1,
scala_collection_GenTraversableView: 1,
scala_collection_TraversableViewLike: 1,
scala_collection_GenTraversableViewLike: 1,
scala_collection_ViewMkString: 1,
scala_collection_Traversable: 1,
scala_collection_GenTraversable: 1,
scala_collection_generic_GenericTraversableTemplate: 1,
scala_collection_TraversableLike: 1,
scala_collection_GenTraversableLike: 1,
scala_collection_Parallelizable: 1,
scala_collection_TraversableOnce: 1,
scala_collection_GenTraversableOnce: 1,
scala_collection_generic_FilterMonadic: 1,
scala_collection_generic_HasNewBuilder: 1,
java_lang_Object: 1
});
//@ sourceMappingURL=TraversableViewLike$Forced.js.map
|
'use strict';
angular.module('wateringApp')
.factory('SensorsFactory', function ($resource) {
return $resource('/api/sensor', {}, {
query: { method: 'GET' },
create: { method: 'POST' }
})
})
.factory('SensorFactory', function ($resource) {
return $resource('/api/sensor/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '@sensor_channel'} },
delete: { method: 'DELETE', params: {id: '@sensor_channel'} }
})
})
.factory('MotorsFactory', function ($resource) {
return $resource('/api/motor', {}, {
query: { method: 'GET' },
create: { method: 'POST' }
})
})
.factory('MotorFactory', function ($resource) {
return $resource('/api/motor/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '@motor_channel'} },
delete: { method: 'DELETE', params: {id: '@motor_channel'} }
})
})
.factory('PlantsFactory', function ($resource) {
return $resource('/api/plant', {}, {
query: { method: 'GET' },
create: { method: 'POST' }
})
})
.factory('PlantFactory', function ($resource) {
return $resource('/api/plant/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '@id'} },
delete: { method: 'DELETE', params: {id: '@id'} }
})
})
.factory('LogsFactory', function ($resource) {
return $resource('/api/log', {}, {
query: { method: 'GET' },
create: { method: 'POST' }
})
})
.factory('LogFactory', function ($resource) {
return $resource('/api/log/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '@id'} },
delete: { method: 'DELETE', params: {id: '@id'} }
})
})
.factory('WateringsFactory', function ($resource) {
return $resource('/api/watering', {}, {
query: { method: 'GET' },
create: { method: 'POST' }
})
})
.factory('WateringFactory', function ($resource) {
return $resource('/api/watering/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '@id'} },
delete: { method: 'DELETE', params: {id: '@id'} }
})
})
.factory('SensorResponsesFactory', function ($resource) {
return $resource('/api/sensor_responses', {}, {
query: { method: 'GET' }
})
}); |
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const concat = require('gulp-concat');
const cssnano = require('gulp-cssnano');
const sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var sourcemaps = require('gulp-sourcemaps');
const image = require('gulp-image');
var paths = {
css: {
src: ['app/Resources/web/sass/**/*.scss'],
dest: 'web/css/main',
watch: ['app/Resources/web/sass/**/*.scss']
},
js: {
src: [''],
dest: [''],
watch: ['']
},
html: {
src: [''],
dest: [''],
watch: ['app/Resources/views/**/*']
},
img: {
src: ['app/Resources/web/img/**/*'],
dest: 'web/img',
watch: ['app/Resources/web/img/**/*']
}
};
var autoprefixerOptions = {
browsers: [
'last 3 versions',
'not ie <= 8'
],
cascade: false
};
/*TASKS*/
/*DEFAULT*/
gulp.task(
'default', [
'sass'
]);
/*SASS*/
gulp.task(
'sass', function () {
return gulp.src(paths.css.src)
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: [paths.css.src],
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(sourcemaps.write())
.pipe(autoprefixer(autoprefixerOptions))
.pipe(cssnano())
.pipe(concat('styles.min.css'))
.pipe(gulp.dest(paths.css.dest))
.pipe(browserSync.stream());
});
/* IMAGES*/
gulp.task(
'image', function () {
gulp.src(paths.img.src)
.pipe(image())
.pipe(gulp.dest(paths.img.dest));
});
/*SERVE*/
gulp.task('serve', ['sass', 'image'], function () {
browserSync.init({
proxy: "wankul.dev/app_dev.php"
});
gulp.watch(paths.css.watch, ['sass']);
gulp.watch(paths.img.watch, ['image']);
gulp.watch(paths.html.watch);
}); |
const Utilities = require('../src/utilities')
const assert = require('assert')
describe('isString', () => {
it('should determine if the given string parameter is a string', () => {
var isString = Utilities.isString('string')
assert.equal(true, isString)
})
it('should determine if the given non-string parameters are not a string', () => {
var isString = Utilities.isString(1)
assert.equal(false, isString)
isString = Utilities.isString(['string'])
assert.equal(false, isString)
isString = Utilities.isString({ name: 'string' })
assert.equal(false, isString)
isString = Utilities.isString(() => {})
assert.equal(false, isString)
isString = Utilities.isString(true)
assert.equal(false, isString)
isString = Utilities.isString(false)
assert.equal(false, isString)
isString = Utilities.isString(null)
assert.equal(false, isString)
isString = Utilities.isString(undefined)
assert.equal(false, isString)
})
})
describe('isArray', () => {
it('should determine if the given array parameter is an array', () => {
var isArray = Utilities.isArray(['string'])
assert.equal(true, isArray)
})
it('should determine if the given non-array parameters are not an array', () => {
var isArray = Utilities.isArray(1)
assert.equal(false, isArray)
isArray = Utilities.isArray('string')
assert.equal(false, isArray)
isArray = Utilities.isArray({ name: 'string' })
assert.equal(false, isArray)
isArray = Utilities.isArray(() => {})
assert.equal(false, isArray)
isArray = Utilities.isArray(true)
assert.equal(false, isArray)
isArray = Utilities.isArray(false)
assert.equal(false, isArray)
isArray = Utilities.isArray(null)
assert.equal(false, isArray)
isArray = Utilities.isArray(undefined)
assert.equal(false, isArray)
})
})
describe('isFunction', () => {
it('should determine if the given function parameter is a function', () => {
var isFunction = Utilities.isFunction(() => {})
assert.equal(true, isFunction)
})
it('should determine if the given non-function parameters are not a function', () => {
var isFunction = Utilities.isFunction(1)
assert.equal(false, isFunction)
isFunction = Utilities.isFunction(['string'])
assert.equal(false, isFunction)
isFunction = Utilities.isFunction({ name: 'string' })
assert.equal(false, isFunction)
isFunction = Utilities.isFunction('string')
assert.equal(false, isFunction)
isFunction = Utilities.isFunction(true)
assert.equal(false, isFunction)
isFunction = Utilities.isFunction(false)
assert.equal(false, isFunction)
isFunction = Utilities.isFunction(null)
assert.equal(false, isFunction)
isFunction = Utilities.isFunction(undefined)
assert.equal(false, isFunction)
})
})
describe('removeArrayItems', () => {
it('should successfully remove desired items from an array', () => {
var array = ['a', 'b', 'c', 'd']
var toRemove = ['b', 'd']
var result = Utilities.removeArrayItems(array, toRemove)
assert.deepEqual(['a', 'c'], result)
})
}) |
/*! networking definitions for skybox interfacing 2014-6-16
* This includes websockets and POST functions
*
* @author ndepalma
* skybox_network.js
* Licensed MIT */
//////////////////////////////////////////
// Global Host
//////////////////////////////////////////
// which server to point to - localhost for debugging
var default_port = 8080;
var global_name = document.domain + ":" + default_port;
var global_host = global_name+"/"; // for testing
//var global_host = "nimbus.media.mit.edu/servlets/obj-collect-1.0-SNAPSHOT-standalone/"; // for deployment
var ws_connection;
var room_num;
var has_ui;
var UID;
//connect websocket and hold the connection to match state
function connectWSLive(_uid, _room_num) {
try {
console.log("Opening websocket");
ws_connection = new WebSocket('ws://'+ global_host + 'attachroom?UID='+_uid+'&room-num='+_room_num);
ws_connection.onopen = function(){
/*Send a small message to the console once the connection is established */
console.log('Connection open!');
}
ws_connection.onclose = function(){
console.log('Connection closed');
}
ws_connection.onerror = function(error){
console.log('Error detected: ' + error.message);
}
ws_connection.onmessage = function(e){
var server_message = e.data;
console.log("msg: " + server_message);
jsob =eval("(" + server_message + ")");
console.log("JSOB: " + JSON.stringify(jsob));
if(jsob == null) {
console.log("Returning null for some reason?");
return;
}
if("play" in jsob) {
console.log("Got a play event!");
document.getElementById("video1").play();
timestream();
} else if("rdebug" in jsob) {
if(typeof(vizdebug) != "undefined") {
if(!vizdebug) {
debugOn();
}
rdebug = jsob.rdebug;
console.log("Debug: " + rdebug);
targetObj = "#" + rdebug.target;
rx = rdebug.x * $(document).width() - 75 + "px";
ry = (1.0-rdebug.y) * $(document).height() - 75 + "px";
if(typeof($(targetObj)) != "undefined") {
$(targetObj).css("left", rx)
$(targetObj).css("top", ry)
}
}
} else if("movie" in jsob) {
movname = jsob.movie;
setMovie(movname);
} else {
//console.log("ELSE");
read_all(jsob);
}
}
}
catch(err) {
console.log(" websocket fail!");
}
}
function sendMsg(msg) {
ws_connection.send(msg);
}
|
'use strict';
var fetchRequest = function (method, url, requestData, callback) {
var config = {
method: method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
if (requestData) {
config.body = JSON.stringify(requestData);
}
fetch(url, config).then(function (response) {
return response.json();
}).then(function (json) {
if (callback) {
callback(json);
}
}).catch(function (err) {
console.log(err.stack);
});
};
module.exports = fetchRequest;
|
import React from 'react';
import InputArea from 'wix-style-react/InputArea';
const style = {
display: 'inline-block',
padding: '0 5px',
width: '200px',
lineHeight: '22px'
};
export default () =>
<div style={{display: 'flex'}}>
<div className="ltr" style={style}>InputArea<br/><InputArea resizable/></div>
<div className="ltr" style={style}>Focus<br/><InputArea forceFocus resizable/></div>
<div className="ltr" style={style}>Hover<br/><InputArea forceHover resizable/></div>
<div className="ltr" style={style}>With placeholder<br/><InputArea placeholder="duyg" resizable/></div>
</div>;
|
// label
module.exports = {
type: {
flow : true,
phrasing : true,
interactive: true
},
contents: {
ng : 'label',
phrasing: true
},
attributes: 'for,form'
};
|
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var qs = require('qs');
var parseurl = require('parseurl');
var config = require('../lib/config');
var log = require('../lib/log');
var middlewareLogger = function middlewareLogger (app) {
app.use(morgan({
format: config.debug ? 'dev' : 'default',
stream: {
write: function writeLog (message) {
log.info(message);
}
}
}));
};
var middlewareBodyParser = function middlewareBodyParser (app) {
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
};
var middlewareQuery = function middlewareQuery (app) {
app.use(function (req, res, next) {
if (!req.query) {
req.query = ~req.url.indexOf('?') ? qs.parse(parseurl(req).query) : {};
}
next();
});
};
var middlewareMethodOverride = function middlewareMethodOverride (app) {
app.use(methodOverride('_method'));
};
module.exports = function middlewares (nutricola) {
middlewareLogger(nutricola.app);
middlewareBodyParser(nutricola.app);
middlewareMethodOverride(nutricola.app);
middlewareQuery(nutricola.app);
}; |
version https://git-lfs.github.com/spec/v1
oid sha256:5d42507f9ec9bde7a602697ff4f52558fefcbaa49664e6505083fc2ad92e07d0
size 365002
|
function between(x, min, max) {
return x >= min && x <= max;
}
function changeRate(sound, rateStart, rateEnd, duration) {
let counter = rateStart;
if (rateStart < rateEnd) {
const timer = setInterval(() => {
sound.rate(counter.toFixed(2));
counter += rateEnd / duration;
if (counter >= rateEnd) {
clearInterval(timer);
}
}, 1);
} else {
const timer = setInterval(() => {
sound.rate(counter.toFixed(2));
counter -= rateEnd / duration;
if (counter <= rateEnd) {
clearInterval(timer);
}
}, 1);
}
}
function interval(duration, fn){
this.baseline = undefined
this.run = function(){
if(this.baseline === undefined){
this.baseline = new Date().getTime()
}
fn()
var end = new Date().getTime()
this.baseline += duration
var nextTick = duration - (end - this.baseline)
if(nextTick<0){
nextTick = 0
}
(function(i){
i.timer = setTimeout(function(){
i.run(end)
}, nextTick)
}(this))
}
this.stop = function(){
clearTimeout(this.timer)
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export { between, changeRate, interval, sleep };
|
var compareTree = require('./_utils').compareTree;
var _i = require('./_utils')._i;
var _root = require('./_utils')._root;
var node = require('./_utils').node;
describe('Conditional parser', function() {
it('should parse simple blocks', function() {
compareTree(
'if(x) {foo();}',
_root([
node(
'If',
0,
14,
{
condition: _i('x'),
consequent: [node(
'CallStatement',
7,
13,
{
call: node(
'Call',
7,
12,
{
callee: _i('foo'),
params: []
}
),
}
)],
alternate: null
}
)
])
);
});
it('should parse simple alternates', function() {
compareTree(
'if(x) {foo();} else {bar();}',
_root([
node(
'If',
0,
28,
{
condition: _i('x'),
consequent: [node(
'CallStatement',
7,
13,
{
call: node(
'Call',
7,
12,
{
callee: _i('foo'),
params: []
}
),
}
)],
alternate: [node(
'CallStatement',
21,
27,
{
call: node(
'Call',
21,
26,
{
callee: _i('bar'),
params: []
}
),
}
)],
}
)
])
);
});
});
|
var MAX_DISPLAY_LINES = 5;
var LINE_HEIGHT = 75;
var DELAY = {
PAGE: 1000,
CHAPTER: 2000
};
c.font = '36px Papyrus, fantasy';
// Text is an array of strings.
// Example: ['one string', 'two string', 'three string', 'four']
function writeText(x, y, lineHeight, text) {
c.fillStyle = '#001f3f';
c.fillRect(0, 0, a.width, a.height);
c.fillStyle = '#01FF70'
text.forEach(function(line, idx) {
c.fillText(line, x, y + (idx * lineHeight));
console.log(line);
});
}
var write = writeText.bind(null, 100, 100, LINE_HEIGHT);
function render(journal) {
var log = [];
function addLog(line) {
// Do we need to make room on the log?
if (log.length === MAX_DISPLAY_LINES) {
log.shift();
}
log.push(line);
return log;
}
function next(x, y) {
var chapter = journal[x];
var page = chapter[y];
// Out of chapters?
if (journal.length === x) {
return write(addLog('I\'ve been defeated.'));
}
// end of chapter?
if (chapter.length === y) {
return setTimeout(next.bind(0, x+1, 0), DELAY.CHAPTER);
}
write(addLog(page));
setTimeout(next.bind(0, x, y+1), DELAY.PAGE);
}
// Start the render loop
next(0, 0);
}
// 138 bytes.
// dice is a string in D&D style
// example: 2d6, 1d20, 4d2+7, 1d10-2
function rollDice(dice) {
var match = /(\d*)d(\d+)([+-]?\d*)/.exec(dice);
var numberOfDice = 0|match[1] || 1;
var numberOfSides = 0|match[2];
var modifier = 0|match[3];
var result = 0;
while (numberOfDice--) {
result += 0| (Math.random() * numberOfSides) + 1;
}
result += modifier;
return result;
}
var d20 = rollDice.bind(0, '1d20');
var d4 = rollDice.bind(0, '1d4');
// Basic battle:
// I spoted a Goblin.
// That Goblin was no match for me!
// I suffered 1 damage.
// Player battles a monster!
// Mutates player.hp
// player {hp, bab, ac}
// monster {name, bab, ac, dmg}
function battle(player, monster) {
var log = [
'I spotted a ' + monster.name + '.'
, (d20() + player.bab) >= monster.ac ?
'The '+ monster.name +' was no match for me!'
: 'I managed to flee.'
];
var attack;
// Monster attack
if ((d20() + monster.bab) > player.ac) {
attack = monster.dmg();
player.hp -= attack;
log.push('I took ' + attack + ' damage.');
}
return log;
}
// basic trap
// I see a strange rock.
// It was a trap!
// I took X damage.
// Player triggers a trap.
// player = {bab, hp}
// trap = {name, ac, dmg}
function trap(player, trap) {
var log = [
'I see a ' + trap.name
];
var attack = d20() + player.bab;
if (attack >= trap.ac) {
log.push('I found some gold coins!');
player.gold += d4();
} else {
log.push('It was a trap!');
attack = trap.dmg();
player.hp -= attack;
log.push('I took ' + attack + ' damage.');
}
return log;
}
function status(player) {
var log = [
'Status: HP ' + player.hp + ', Gold ' + player.gold
];
return log;
}
function run() {
var log = [];
var player = {hp: 11, bab: 5, ac: 17, gold: 0};
var goblin = {name: 'Goblin', bab: 2, ac: 13, dmg: d4};
var trapRock = {name: 'strange rocks', ac: 13, dmg: d4};
var result, roll;
while (player.hp > 0) {
roll = d4();
if (1 === roll) {
result = battle(player, goblin);
}
if (2 === roll) {
result = trap(player, trapRock);
}
if (3 === roll) {
// result = status(player);
}
log.push(result);
}
return log;
}
// Try it out
// battle returns an l-system string.
var log = run();
render(log);
|
import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/index.js',
output: {
file: 'index.js',
format: 'cjs', // immediately-invoked function expression — suitable for <script> tags
},
plugins: [
resolve(), // tells Rollup how to find date-fns in node_modules
commonjs(), // converts date-fns to ES modules
babel({
exclude: 'node_modules/**'
}),
production && uglify() // minify, but only in production
],
sourcemap: true
}; |
import React, { Component } from "react";
import GridContainer from "./components/GridContainer";
import TileContainer from "./components/TileContainer";
import GameManager from "./GameManager";
require("../assets/main.scss");
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
manager: new GameManager(4)
};
}
onLeft() {
var manager = this.state.manager;
manager.move(3);
this.setState({
manager: manager
});
}
onRight() {
var manager = this.state.manager;
manager.move(1);
this.setState({
manager: manager
});
}
onTop() {
var manager = this.state.manager;
manager.move(0);
this.setState({
manager: manager
});
}
onBottom() {
var manager = this.state.manager;
manager.move(2);
this.setState({
manager: manager
});
}
render() {
return (
<div className="game-container">
<GridContainer />
<TileContainer board={this.state.manager.grid} />
<div style={{position: 'absolute', left: '50%', transform: "translateX(-50%)", bottom: -30}}>
<button onClick={this.onLeft.bind(this)}>
LEFT
</button>
<button onClick={this.onRight.bind(this)}>
RIGHT
</button>
<button onClick={this.onTop.bind(this)}>
TOP
</button>
<button onClick={this.onBottom.bind(this)}>
BOTTOM
</button>
</div>
</div>
);
}
}
|
'use strict';
var userInfo = {
OAuth: '',
currentUser: '',
userID: ''
};
$('.twitch-connect').click(function () {
window.location='https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=pxic46d4dsydwhxvlh341kb7dgdnc6&redirect_uri=https://bittoolscod301.herokuapp.com&scope=user_read+channel_read';
});
function checkLogin() {
if (localStorage.userInfo) {
$('#login').hide();
$('#widgets').show();
$('#navBlock').show();
var savedInfo = JSON.parse(localStorage.getItem('userInfo'));
userInfo.OAuth = savedInfo.OAuth;
userInfo.currentUser = savedInfo.currentUser;
userInfo.userID = savedInfo.userID;
renderWidget();
} else {
$('#widgets').hide();
$('#navBlock').hide();
$('#login').show();
var newValue = document.location.href.split("=")[1].split("&")[0];
// var redirectURL = document.location.href.includes('localhost') ? 'http://localhost:31337' : 'https://bittoolscod301.herokuapp.com';
$.ajax({
url: "https://api.twitch.tv/kraken/oauth2/token",
method: "POST",
data: {
client_id: "pxic46d4dsydwhxvlh341kb7dgdnc6",
client_secret: "c5kugf7f8ugkahsbpryccq6cocitxr",
grant_type: "authorization_code",
redirect_uri: 'https://bittoolscod301.herokuapp.com',
code: newValue
},
success: function(data) {
userInfo.OAuth = data.access_token;
$.ajax({
url: 'https://api.twitch.tv/kraken',
headers: {
Accept: "application/vnd.twitchtv.v5+json",
Authorization: `OAuth ${data.access_token}`,
"Client-ID": "pxic46d4dsydwhxvlh341kb7dgdnc6"
},
success: function(data){
userInfo.currentUser = data.token.user_name;
userInfo.userID = data.token.user_id;
localStorage.setItem('userInfo', JSON.stringify(userInfo));
$('#login').hide();
$('#widgets').show();
$('#navBlock').show();
renderWidget();
}
})
}
})
}
}
|
import React, { PropTypes } from 'react'
export const Intro = (props) => (
<article className="ContentBlock Intro">
<h2>{props.heading}</h2>
<p>{props.children}</p>
</article>
)
Intro.propTypes = {
heading: PropTypes.string.isRequired
}
export const Horz = (props) => (
<article className="ContentBlock Feature Horz">
<h2>
<a target='_blank' href={props.url}>
<span className="FeatureHeading">
{props.heading}
</span>
</a>
</h2>
<p>{props.children}</p>
</article>
)
Horz.propTypes = {
heading: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}
|
"use strict";
// Run me with Node to see my output!
let util = require("util");
let P = require("..");
///////////////////////////////////////////////////////////////////////
// -*- Parser -*-
let Lang = P.createLanguage({
s0: () => P.regexp(/[ ]*/),
s1: () => P.regexp(/[ ]+/),
Whitespace: () => P.regexp(/[ \n]*/),
NotNewline: () => P.regexp(/[^\n]*/),
Comma: () => P.string(","),
Comment: r => r.NotNewline.wrap(P.string("//"), P.string("\n")),
End: r => P.alt(P.string(";"), r._, P.string("\n"), P.eof),
_: r => r.Comment.sepBy(r.Whitespace).trim(r.Whitespace),
Program: r =>
r.Statement.many()
.trim(r._)
.node("Program"),
Statement: r => P.alt(r.Declaration, r.Assignment, r.Call),
Declaration: r =>
P.seqObj(
P.string("var"),
r.s1,
["identifier", r.Identifier],
r.s0,
P.string("="),
r.s0,
["initialValue", r.Expression],
r.End
).node("Declaration"),
Assignment: r =>
P.seqObj(
["identifier", r.Identifier],
r.s0,
P.string("="),
r.s0,
["newValue", r.Expression],
r.End
).node("Assignment"),
Call: r =>
P.seqObj(
["function", r.Expression],
P.string("("),
["arguments", r.Expression.trim(r._).sepBy(r.Comma)],
P.string(")")
).node("Call"),
Expression: r => P.alt(r.Number, r.Reference),
Number: () =>
P.regexp(/[0-9]+/)
.map(Number)
.node("Number"),
Identifier: () => P.regexp(/[a-z]+/).node("Identifier"),
Reference: r => r.Identifier.node("Reference")
});
// -*- Linter -*-
// NOTE: This simplified language only has global scope. Most real languages
// have layers of scope, so your scope data structure will need to be something
// more complicated than just an object keeping track of variable names.
let scope = null;
let messages = null;
function noLint() {
// This function intentionally left blank
}
let lintHelpers = {
Program(node) {
node.value.forEach(lint_);
},
Declaration(node) {
scope[node.value.identifier.value] = true;
lint_(node.value.initialValue);
},
Reference(node) {
let name = node.value.value;
if (!scope.hasOwnProperty(name)) {
messages.push("undeclared variable " + name);
}
},
Assignment(node) {
lint_(node.value.newValue);
},
Call(node) {
lint_(node.value.function);
node.value.arguments.forEach(lint_);
},
Number: noLint
};
function lint_(node) {
if (!node) {
throw new TypeError("not an AST node: " + node);
}
if (!lintHelpers.hasOwnProperty(node.name)) {
throw new TypeError("no lint helper for " + node.name);
}
return lintHelpers[node.name](node);
}
function lint(node) {
scope = {};
messages = [];
lint_(node);
return messages;
}
///////////////////////////////////////////////////////////////////////
let text = `\
// nice stuff
var x = 1 // declare this one
x = 2
// Notice this variable is undeclared.
y = 3
// And f is undeclared too...
f(x, y, 3)
`;
function prettyPrint(x) {
let opts = { depth: null, colors: "auto" };
let s = util.inspect(x, opts);
console.log(s);
}
let ast = Lang.Program.tryParse(text);
let linterMessages = lint(ast);
prettyPrint(linterMessages);
prettyPrint(ast);
|
const uuid = {
_regex: {
default: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
},
default: context => {
if (context.value === null || context.value && !context.value.toString().match(uuid._regex.default)) {
context.fail('Value must be a valid UUID')
}
}
}
module.exports = uuid
|
(function($){
var cache = [], timeout;
$.fn.remove = function(){
return this.each(function(element){
if(element.tagName == 'IMG'){
cache.push(element);
element.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function(){ cache = [] }, 60000);
}
element.parentNode.removeChild(element);
});
}
})(Zepto);
|
var elixir = require('laravel-elixir');
var gulp = require('gulp');
var jade;
var rename = require('gulp-rename');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
var changed = require('gulp-changed');
var jadeInheritance = require('gulp-jade-inheritance');
var _ = require('underscore');
var Task = elixir.Task;
/*
|----------------------------------------------------------------
| Gulp Jade Wrapper
|----------------------------------------------------------------
|
| This task will compile your Jade files into your views folder.
| You can make use of Blade variables in your jade files as well.
| Examples see README.md
|
*/
elixir.extend('jade', function (options) {
options = _.extend({
baseDir: './resources',
blade: true,
html: false,
dest: '/views/',
pretty: true,
search: '**/*.jade',
src: '/jade/',
jadephp: false
}, options);
jade = options.jadephp ? require('gulp-jade-php') : require('gulp-jade');
var gulp_src = options.baseDir + options.src + options.search;
var jade_options = _.pick(
options,
'filename',
'doctype',
'pretty',
'self',
'debug',
'compileDebug',
'compiler',
'locals'
);
jade_options.basedir = options.baseDir + options.src;
var gulp_dest = options.baseDir + options.dest;
var extension;
if(typeof options.extension === 'string') {
extension = options.extension;
if(extension.slice(0,1)!=='.') {
extension = '.' + extension;
}
} else {
extension = (options.html === true ? '.html' : (options.blade === true ? '.blade.php' : '.php'));
}
new Task('jade', function() {
return gulp.src(gulp_src)
.pipe(plumber())
.pipe(changed(gulp_dest, { extension: extension }))
.pipe(jadeInheritance({basedir: options.baseDir + options.src }))
.pipe(jade(jade_options))
.pipe(rename(function (path) {
path.extname = extension;
}))
.pipe(gulp.dest(gulp_dest))
.pipe(notify({
title: 'Jade completed',
message: '<%= file.relative %> have been compiled.',
icon: __dirname + '/../laravel-elixir/icons/pass.png'
}));
})
.watch([ options.baseDir + options.src + options.search ]);
});
|
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, node: true, nomen: true,
indent: 4, maxerr: 50 */
/*global expect, describe, it, beforeEach, afterEach */
"use strict";
var rewire = require("rewire"),
repository = rewire("../lib/repository"),
user_utils = rewire("../lib/user_utils"),
path = require("path");
var testPackageDirectory = path.join(path.dirname(module.filename), "data"),
basicValidExtension = path.join(testPackageDirectory, "basic-valid-extension.zip");
var originalValidate = repository.__get__("validate"),
ADMIN = "github:admin";
describe("Repository", function () {
beforeEach(function () {
// Clear the repository
repository.configure({
storage: "./ramstorage",
admins: [ADMIN]
});
});
afterEach(function () {
repository.__set__("validate", originalValidate);
});
function setValidationResult(result) {
repository.__set__("validate", function (path, options, callback) {
callback(null, result);
});
}
var createFakeUser = user_utils._createFakeUser;
var adminLogged = createFakeUser(ADMIN);
var user = createFakeUser("github:reallyreallyfakeuser");
it("should fail with no configuration", function (done) {
repository.__set__("config", null);
repository.addPackage(basicValidExtension, createFakeUser("github:adobe"), function (err, entry) {
expect(err.message).toEqual("Repository not configured!");
done();
});
});
it("should be able to add a valid package", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
expect(err).toEqual(null);
expect(entry.metadata.name).toEqual("basic-valid-extension");
var registered = repository.__get__("registry")["basic-valid-extension"];
expect(registered).toBeDefined();
expect(registered.metadata.name).toEqual("basic-valid-extension");
expect(registered.owner).toEqual(user.owner);
expect(registered.versions.length).toEqual(1);
expect(registered.versions[0].version).toEqual("1.0.0");
// toBeCloseTo with precision -4 means that we're allowing anything less than 10
// seconds of difference to pass
var pubDate = new Date(registered.versions[0].published);
expect(pubDate.getTime()).toBeCloseTo(new Date().getTime(), -4);
var storage = repository.__get__("storage");
expect(storage.files["basic-valid-extension/basic-valid-extension-1.0.0.zip"]).toEqual(basicValidExtension);
storage.getRegistry(function (err, storedRegistry) {
var registered2 = storedRegistry["basic-valid-extension"];
expect(registered2.metadata.name).toEqual(registered.metadata.name);
// testing that Date serialization is working as it should
expect(new Date(registered2.versions[0].published).getTime()).toBeCloseTo(new Date().getTime(), -4);
done();
});
});
});
it("should verify ownership before allowing action for a package", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
repository.addPackage(basicValidExtension, createFakeUser("github:someonewhowedontknowandshouldnthaveaccess"), function (err, metadata) {
expect(err.message).toEqual("NOT_AUTHORIZED");
done();
});
});
});
it("should not get tripped up by JS object properties", function (done) {
setValidationResult({
metadata: {
name: "constructor",
version: "1.0.0"
}
});
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err).toBeNull();
done();
});
});
it("should handle good version upgrades", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
setValidationResult({
metadata: {
name: "basic-valid-extension",
description: "Less basic than before",
version: "2.0.0",
engines: {
brackets: ">0.21.0"
}
}
});
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(entry.metadata.description).toEqual("Less basic than before");
expect(entry.metadata.version).toEqual("2.0.0");
expect(entry.versions.length).toEqual(2);
expect(entry.versions[1].version).toEqual("2.0.0");
expect(entry.versions[1].brackets).toEqual(">0.21.0");
// toBeCloseTo with precision -4 means that we're allowing anything less than 10
// seconds of difference to pass
var pubDate = new Date(entry.versions[1].published);
expect(pubDate.getTime()).toBeCloseTo(new Date().getTime(), -4);
var storage = repository.__get__("storage");
expect(storage.files["basic-valid-extension/basic-valid-extension-1.0.0.zip"]).toEqual(basicValidExtension);
expect(storage.files["basic-valid-extension/basic-valid-extension-2.0.0.zip"]).toEqual("nopackage.zip");
done();
});
});
});
it("should reject versions that are not higher than the previous version", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
setValidationResult({
metadata: {
name: "basic-valid-extension",
version: "0.9.9"
}
});
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err.message).toEqual("BAD_VERSION");
done();
});
});
});
it("should reject packages with validation errors", function (done) {
setValidationResult({
errors: [
["BAD_PACKAGE_NAME", "foo@bar"],
["INVALID_VERSION_NUMBER", "x.231.aaa", "nopackage.zip"]
],
metadata: {
name: "foo@bar",
version: "x.231.aaa"
}
});
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err).not.toBeNull();
expect(err.message).toEqual("VALIDATION_FAILED");
expect(err.errors.length).toEqual(2);
expect(err.errors[0][0]).toEqual("BAD_PACKAGE_NAME");
expect(err.errors[1][0]).toEqual("INVALID_VERSION_NUMBER");
done();
});
});
it("should return an error if the registry is not loaded", function (done) {
repository.__set__("registry", null);
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err.message).toEqual("REGISTRY_NOT_LOADED");
done();
});
});
it("should return the current registry", function () {
var registry = {
"my-extension": {
metadata: { name: "my-extension", version: "1.0.0" }
}
};
repository.__set__("registry", registry);
expect(repository.getRegistry()).toBe(registry);
});
it("should report errors that come from the storage", function (done) {
var storage = repository.__get__("storage");
var expectedError = new Error("It brokeded.");
storage.savePackage = function (entry, path, callback) {
callback(expectedError);
};
repository.addPackage(basicValidExtension, user, function (err, entry) {
expect(err).toBe(expectedError);
var registry = repository.__get__("registry");
expect(registry["basic-valid-extension"]).toBeUndefined();
done();
});
});
it("should not update the registry if there's a storage error", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
setValidationResult({
metadata: {
name: "basic-valid-extension",
description: "Less basic than before",
version: "2.0.0",
engines: {
brackets: ">0.21.0"
}
}
});
var storage = repository.__get__("storage");
var expectedError = new Error("It brokeded.");
storage.savePackage = function (entry, path, callback) {
callback(expectedError);
};
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err).toBe(expectedError);
var registry = repository.__get__("registry");
expect(registry["basic-valid-extension"].versions.length).toEqual(1);
done();
});
});
});
it("should not allow two packages with the same title, even from the same owner", function (done) {
setValidationResult({
metadata: {
name: "anotherpkg",
version: "2.1.1"
}
});
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err).toBeNull();
setValidationResult({
metadata: {
name: "superawesome",
title: "Super Awesome!",
description: "It's awesome.",
version: "1.0.0"
}
});
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err).toBeNull();
setValidationResult({
metadata: {
name: "super-awesome",
title: "Super awesome!",
description: "It's awesomer.",
version: "1.0.0"
}
});
repository.addPackage("nopackage.zip", user, function (err, entry) {
expect(err).not.toBeNull();
expect(err.message).toEqual("VALIDATION_FAILED");
expect(err.errors.length).toEqual(1);
expect(err.errors[0][0]).toEqual("DUPLICATE_TITLE");
done();
});
});
});
});
it("should delete a package when requested by the owner", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
var registry = repository.__get__("registry");
expect(registry["basic-valid-extension"]).toBeDefined();
repository.deletePackageMetadata("basic-valid-extension", user, function (err) {
expect(err).toBeNull();
expect(registry["basic-valid-extension"]).toBeUndefined();
done();
});
});
});
it("should produce an error for unknown package", function (done) {
repository.deletePackageMetadata("does-not-exist", user, function (err) {
expect(err).not.toBeNull();
done();
});
});
it("should not delete a package when requested by a non-owner", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
repository.deletePackageMetadata("basic-valid-extension", createFakeUser("github:unknown"), function (err) {
var registry = repository.__get__("registry");
expect(err).not.toBeNull();
expect(registry["basic-valid-extension"]).toBeDefined();
done();
});
});
});
it("should delete a package when requested by an admin", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
var registry = repository.__get__("registry");
expect(registry["basic-valid-extension"]).toBeDefined();
repository.deletePackageMetadata("basic-valid-extension", adminLogged, function (err) {
expect(err).toBeNull();
expect(registry["basic-valid-extension"]).toBeUndefined();
done();
});
});
});
it("should change a package's owner when requested by the owner", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
var registry = repository.__get__("registry");
expect(registry["basic-valid-extension"]).toBeDefined();
repository.changePackageOwner("basic-valid-extension", user, "github:newuser", function (err) {
expect(err).toBeNull();
expect(registry["basic-valid-extension"].owner).toEqual("github:newuser");
done();
});
});
});
it("should produce an error for unknown package when changing ownership", function (done) {
repository.changePackageOwner("does-not-exist", user, function (err) {
expect(err).not.toBeNull();
done();
});
});
it("should not change ownership for a package when requested by a non-owner", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
repository.changePackageOwner("basic-valid-extension", createFakeUser("github:unknown"), "github:badguy", function (err) {
var registry = repository.__get__("registry");
expect(err).not.toBeNull();
expect(registry["basic-valid-extension"].owner).toEqual("github:reallyreallyfakeuser");
done();
});
});
});
it("should change ownership of a package when requested by an admin", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
var registry = repository.__get__("registry");
repository.changePackageOwner("basic-valid-extension", adminLogged, "github:someuser", function (err) {
expect(err).toBeNull();
expect(registry["basic-valid-extension"].owner).toEqual("github:someuser");
done();
});
});
});
it("should change a package's requirements when requested by the owner", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
var registry = repository.__get__("registry");
repository.changePackageRequirements("basic-valid-extension", user, "<0.38.0", function (err) {
expect(err).toBeNull();
registry["basic-valid-extension"].versions.forEach(function (version) {
expect(version.brackets).toEqual("<0.38.0");
});
done();
});
});
});
it("should produce an error for unknown package when changing requrements", function (done) {
repository.changePackageRequirements("does-not-exist", user, "<0.38.0", function (err) {
expect(err).not.toBeNull();
done();
});
});
it("should not change requirements for a package when requested by a non-owner", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
repository.changePackageRequirements("basic-valid-extension", createFakeUser("github:unknown"), "<0.38.0", function (err) {
var registry = repository.__get__("registry");
expect(err).not.toBeNull();
expect(registry["basic-valid-extension"].versions[0].brackets).toBeUndefined();
done();
});
});
});
it("should change requirements of a package when requested by an admin", function (done) {
repository.addPackage(basicValidExtension, user, function (err, entry) {
var registry = repository.__get__("registry");
repository.changePackageRequirements("basic-valid-extension", adminLogged, "<0.38.0", function (err) {
expect(err).toBeNull();
expect(registry["basic-valid-extension"].versions[0].brackets).toEqual("<0.38.0");
done();
});
});
});
});
describe("Add download data", function () {
describe("Extension version download numbers", function () {
beforeEach(function () {
var registry = JSON.parse('{"snippets-extension":{"metadata":{"name":"snippets-extension","title":"Brackets Snippets","homepage":"https://github.com/testuser/brackets-snippets","author":{"name":"Testuser"},"version":"1.0.0","engines":{"brackets":">=0.24"},"description":"A simple brackets snippets extension."},"owner":"irichter","versions":[{"version":"0.2.0","published":"2014-01-10T17:27:25.996Z","brackets":">=0.24"},{"version":"0.3.0","published":"2014-01-10T17:27:25.996Z","brackets":">=0.24"}]}}');
repository.__set__("registry", registry);
});
it("should add the download numbers to the 0.3.0 extension version and update the download total", function () {
repository.addDownloadDataToPackage("snippets-extension", {"0.3.0" : 5}, {"20130805": 5});
var registry = repository.getRegistry();
expect(registry["snippets-extension"].versions[1].downloads).toBe(5);
expect(registry["snippets-extension"].totalDownloads).toBe(5);
});
it("should add the download numbers to the 0.3.0 extension version and update the download total when called twice", function () {
repository.addDownloadDataToPackage("snippets-extension", {"0.3.0" : 5}, {"20130805": 5});
repository.addDownloadDataToPackage("snippets-extension", {"0.3.0" : 8}, {"20130805": 8});
var registry = repository.getRegistry();
expect(registry["snippets-extension"].versions[1].downloads).toBe(13);
expect(registry["snippets-extension"].totalDownloads).toBe(13);
});
it("should add the download numbers to the 0.2.0 and 0.3.0 extension and update the download total", function () {
repository.addDownloadDataToPackage("snippets-extension", {"0.3.0": 5, "0.2.0": 3}, {"20130805": 8});
var registry = repository.getRegistry();
expect(registry["snippets-extension"].versions[0].downloads).toBe(3);
expect(registry["snippets-extension"].versions[1].downloads).toBe(5);
expect(registry["snippets-extension"].totalDownloads).toBe(8);
});
});
describe("Recent Downloads", function () {
var registry;
beforeEach(function () {
var registry = JSON.parse('{"test-package":{"metadata":{"name":"test-package"}, "versions":[{"version":"0.2.0","published":"2014-01-10T17:27:25.996Z","brackets":">=0.24"}]}}');
repository.__set__("registry", registry);
});
it("should update the recent download numbers on new extension", function () {
var recentDownloads = {"20130216": 10, "20130217": 5, "20130218": 7, "20130219": 4, "20130220": 41, "20130221": 14, "20130222": 30};
repository._updateRecentDownloadsForPackage("test-package", recentDownloads);
var updatedRecentDownload = repository.getRegistry()["test-package"].recent;
expect(Object.keys(updatedRecentDownload).length).toBe(7);
// Check that the download numbers got doubled
expect(updatedRecentDownload).toEqual({"20130216": 10, "20130217": 5, "20130218": 7, "20130219": 4, "20130220": 41, "20130221": 14, "20130222": 30});
});
it("should update the recent download numbers 2 times and ensure that the sum of the downloads is correct", function () {
var recentDownloads = {"20130216": 10, "20130217": 5, "20130218": 7, "20130219": 4, "20130220": 41, "20130221": 14, "20130222": 30};
var recentDownloads2 = {"20130216": 10, "20130217": 5, "20130218": 7, "20130219": 4, "20130220": 20, "20130221": 7, "20130222": 15};
repository._updateRecentDownloadsForPackage("test-package", recentDownloads);
repository._updateRecentDownloadsForPackage("test-package", recentDownloads2);
var updatedRecentDownload = repository.getRegistry()["test-package"].recent;
expect(Object.keys(updatedRecentDownload).length).toBe(7);
expect(updatedRecentDownload).toEqual({"20130216": 20, "20130217": 10, "20130218": 14, "20130219": 8, "20130220": 61, "20130221": 21, "20130222": 45});
});
it("should update the recent download numbers with 3 datapoints and keep only these 3 datapoints on new extension", function () {
var recentDownloads = {"20130215": 10, "20130216": 5, "20130217": 7};
repository._updateRecentDownloadsForPackage("test-package", recentDownloads);
var updatedRecentDownload = repository.getRegistry()["test-package"].recent;
expect(Object.keys(updatedRecentDownload).length).toBe(3);
expect(updatedRecentDownload).toEqual({"20130215": 10, "20130216": 5, "20130217": 7});
});
});
});
|
// Use the function below in the main browser thread, as the handler
// for message events from the Caffeine worker. You can post messages
// to Caffeine with the worker's postMessage() function. Caffeine
// responds with message events.
//
// In Caffeine's "Tether" protocol, the browser is the first side to
// speak, by exposing a special tether object to Caffeine. Caffeine
// responds by exposing its local counterpart tether to the
// browser. Expose your tether by evaluating:
//
// caffeine.tether.push(caffeine.tether)
//
// You can send simple messages to Caffeine's tether object like so:
//
// ***
//
// caffeine.tether.sendMessage(
// {
// 'selector': 'echo:',
// 'arguments': [3]},
//
// (result) => {console.log(result)})
//
// ***
//
// Tether also enables sending complex messages to Caffeine's other
// objects, including its compiler. For details, see /js/squeakjs/tether/tether.js
return (message) => {
let data = JSON.parse(message.data)
if (data.result) {
(caffeine.tether.callbacks[data.exposureHash])(data.result)}
else {
caffeine.tether.setIncomingMessage(data.payload);
let tag = caffeine.tether.nextWord()
if (!(window.caffeinePeer)) {window.caffeinePeer = tag}
else {
let constructor = caffeine.classes[tag]
if (!(constructor)) {debugger}
else {(new constructor()).handleEventFrom(caffeine.tether)}}}}
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"dop.",
"odp."
],
"DAY": [
"ned\u011ble",
"pond\u011bl\u00ed",
"\u00fater\u00fd",
"st\u0159eda",
"\u010dtvrtek",
"p\u00e1tek",
"sobota"
],
"MONTH": [
"ledna",
"\u00fanora",
"b\u0159ezna",
"dubna",
"kv\u011btna",
"\u010dervna",
"\u010dervence",
"srpna",
"z\u00e1\u0159\u00ed",
"\u0159\u00edjna",
"listopadu",
"prosince"
],
"SHORTDAY": [
"ne",
"po",
"\u00fat",
"st",
"\u010dt",
"p\u00e1",
"so"
],
"SHORTMONTH": [
"Led",
"\u00dano",
"B\u0159e",
"Dub",
"Kv\u011b",
"\u010cer",
"\u010cvc",
"Srp",
"Z\u00e1\u0159",
"\u0158\u00edj",
"Lis",
"Pro"
],
"fullDate": "EEEE, d. MMMM y",
"longDate": "d. MMMM y",
"medium": "d. M. yyyy H:mm:ss",
"mediumDate": "d. M. yyyy",
"mediumTime": "H:mm:ss",
"short": "dd.MM.yy H:mm",
"shortDate": "dd.MM.yy",
"shortTime": "H:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "K\u010d",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "cs",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == (n | 0) && n >= 2 && n <= 4) { return PLURAL_CATEGORY.FEW; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
ig.module(
'game.entities.title-alt'
)
.requires(
'plusplus.core.config',
'plusplus.core.entity'
)
.defines(function () {
"use strict";
var _c = ig.CONFIG;
/**
* Alt title for Impact++.
* @class
* @extends ig.EntityExtended
* @memberof ig
* @author Collin Hover - collinhover.com
*/
ig.EntityTitleAlt = ig.global.EntityTitleAlt = ig.EntityExtended.extend(/**@lends ig.EntityTitleAlt.prototype */{
size: { x: 256, y: 44 },
animSheet: new ig.AnimationSheet(_c.PATH_TO_MEDIA + 'titles/title_alt.png', 256, 44 ),
animInit: "blinkX",
animSettings: {
idleX: {
sequence: [3],
frameTime: 1,
stop: true
},
blinkX: {
sequence: [
0, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 0, 0, 0, 0, 0, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 0, 1, 2, 1, 0, 0, 0, 0, 0
],
frameTime: 0.05
}
},
/**
* When title activated, change animation to idle.
* @override
*/
activate: function ( entity ) {
this.parent( entity );
this.currentAnim = this.anims[ "idleX" ];
}
});
}); |
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'lib/*.js', 'public/js/*.js']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('test', ['jshint']);
grunt.registerTask('default', ['jshint']);
}; |
define(["react", "immutable", "vector", "game/world", "game/tile", "ai/heatmapper2"], function (React, Immutable, Vector, World, GTile, AI) {
"use strict";
var IMequals = function (a, b) {
return Immutable.is(Immutable.fromJS(a), Immutable.fromJS(b));
};
var PureRenderMixin = {
shouldComponentUpdate: function (nextProps, nextState) {
return !(
IMequals(nextProps, this.props)
&& IMequals(nextState, this.state)
);
}
};
var Tile = React.createClass({
displayName: "Tile",
getDefaultProps: function () {
return {
fontScale: 1
};
},
mixins: [PureRenderMixin],
render: function () {
var self = this;
var pos = self.props.pos;
var next = self.props.pos.add(Vector(1, 1));
var dir = self.props.orientation;
var scale = function (vec) {
var gridPos = vec.divide(self.props.bounds);
var canvasPos = gridPos.multiply(self.props.canvas);
return canvasPos;
};
pos = scale(pos);
var size = scale(next).map(Math.floor);
pos = pos.map(Math.floor);
size = size.subtract(pos);
if (dir === 1 || dir === 3) {
var inv = size.invert();
var offs = size.subtract(inv);
var offsHalf = offs.divide(Vector(2, 2));
pos = pos.add(offsHalf);
size = size.invert();
}
var rot = dir * 90;
var style = Immutable.fromJS({
position: "absolute",
left: pos.x + "px",
top: pos.y + "px",
width: size.x + "px",
height: size.y + "px",
lineHeight: size.y + "px",
transform: "rotate(" + rot + "deg)",
fontSize: Math.floor(this.props.fontScale * (Math.min(size.y, size.x))) + "px",
overflow: "hidden",
verticalAlign: "middle",
boxSizing: "border-box"
// border: "1px solid rgb(0, 155, 0)"
});
style = style.merge(style, self.props.style);
return React.createElement("div", {
// id: "tile_" + self.props.pos.x + "_" + self.props.pos.y,
style: style.toJS()}, self.props.children);
}
});
var GrassTile = React.createClass({
displayName: "GrassTile",
shouldComponentUpdate: function (nextProps) {
return !(
Immutable.is(this.props.tile, nextProps.tile) &&
Immutable.is(this.props.bounds, nextProps.bounds) &&
Immutable.is(this.props.canvas, nextProps.canvas)
);
},
render: function () {
return React.createElement(Tile, {
pos: this.props.tile.pos,
bounds: this.props.bounds,
canvas: this.props.canvas,
style: {
backgroundColor: this.props.tile.type === GTile.TILE_GRASS_CUT ? "rgb(0, 180, 0)" : "rgb(0, 160, 0)",
textAlign: "center"
},
fontScale: 0.2,
orientation: 0
}, this.props.tile.number !== undefined ? this.props.tile.number.toFixed(1) : "");
}
});
var LawnMower = React.createClass({
displayName: "LawnMower",
mixins: [PureRenderMixin],
render: function () {
return React.createElement(Tile, {
pos: this.props.pos,
bounds: this.props.bounds,
canvas: this.props.canvas,
style: {
textAlign: "right"
},
orientation: this.props.dir,
fontScale: 0.8
}, ">");
}
});
var GridWidget = React.createClass({
displayName: "Grid",
mixins: [PureRenderMixin],
getInitialState: function () {
return {
canvas: this.getSize()
};
},
getSize: function () {
var sizeMin = Math.min(document.body.clientWidth, document.body.clientHeight);
return Vector(sizeMin, sizeMin);
},
componentDidMount: function () {
var self = this;
window.addEventListener("resize", function () {
self.setState({
canvas: self.getSize()
});
});
},
render: function () {
var self = this;
var tiles = self.props.game.area.tiles.map(function (tile, key) {
return React.createElement(GrassTile, {
bounds: self.props.game.area.bounds,
key: key,
canvas: self.state.canvas,
tile: tile
});
});
var middle = self.state.canvas.divide(new Vector(-2, -2));
return React.createElement("div", {
style: {
width: String(self.state.canvas.x) + "px",
height: String(self.state.canvas.y) + "px",
position: "absolute",
top: "50%",
left: "50%",
marginLeft: String(middle.x) + "px",
marginTop: String(middle.y) + "px",
overflow: "hidden"
}
},
tiles.toJS(),
React.createElement(LawnMower, {
pos: self.props.game.pos,
bounds: self.props.game.area.bounds,
canvas: self.state.canvas,
dir: self.props.game.dir
}),
React.createElement("button", {style: {
position: "absolute",
top: 0,
right: 0
}, onClick: self.props.onStop}, "STOP/START"),
React.createElement("div", {style: {
position: "absolute",
background: "rgba(255, 255, 255, 0.8)"
}}, "Score: ", self.props.game.score.toFixed(2))
);
}
});
var Main = React.createClass({
displayName: "main",
getInitialState: function () {
return {
i: 0,
game: World.World(),
running: true
};
},
componentDidMount: function () {
var self = this;
setInterval(function () {
if (!self.state.running) {
return;
}
var game = AI(self.state.game);
self.setState({
game: game,
i: self.state.i + 1
});
}, 500);
},
shouldComponentUpdate: function (nextProps, nextState) {
return !this.state.game.equals(nextState.game);
},
render: function () {
var self = this;
return React.createElement(GridWidget, {
game: this.state.game,
onStop: function () {
self.setState({running: !self.state.running});
}
});
}
});
return Main;
});
|
import { resolve } from 'path';
import { getIfUtils, removeEmpty } from 'webpack-config-utils';
import webpack, { ContextReplacementPlugin } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ProgressBarPlugin from 'progress-bar-webpack-plugin';
import ExtendedDefinePlugin from 'extended-define-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import S3Plugin from 'webpack-s3-plugin';
import FaviconsWebpackPlugin from 'favicons-webpack-plugin';
import CompressionPlugin from 'compression-webpack-plugin';
import { getAppConfig, getS3Config } from './webpack-helpers';
const webpackConfig = (env = {}) => {
const { ifDevelopment, ifNotDevelopment } = getIfUtils(env);
const config = {
context: resolve('src'),
entry: {
app: [
'babel-polyfill',
'react-hot-loader/patch',
'./app.js'
]
},
output: {
filename: ifNotDevelopment('bundle.[name].[hash].js', 'bundle.[name].js'),
path: resolve(__dirname, 'dist'),
pathinfo: ifDevelopment(true)
},
devtool: ifNotDevelopment('source-map', 'eval'),
module: {
rules: [
{
enforce: 'pre',
test: /\.js(|x)$/,
exclude: /node_modules/,
use: 'eslint-loader'
},
{
test: /\.js(|x)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [['es2015', { modules: false }], 'react', 'stage-0']
}
}
},
{
test: /\.(eot|ttf|svg|woff|woff2)$/,
include: /fonts/,
use: 'file-loader?name=./fonts/[name]-[hash].[ext]'
},
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [
{
loader: 'url-loader',
options: { limit: 40000 }
},
'image-webpack-loader'
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
use: 'css-loader'
})
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
use: [
'css-loader',
{
loader: 'sass-loader',
options: {
sourceMap: true,
includePaths: [
resolve(__dirname, './node_modules/compass-mixins/lib'),
resolve(__dirname, './src/assets/sass')
]
}
}
]
})
}
]
},
plugins: removeEmpty([
ifDevelopment(new ProgressBarPlugin()),
new webpack.NoEmitOnErrorsPlugin(),
new ExtractTextPlugin({
filename: ifNotDevelopment('styles.[hash].css', 'styles.css'),
allChunks: true
}),
new HtmlWebpackPlugin({ template: './index.html' }),
new ExtendedDefinePlugin({ APP_CONFIG: getAppConfig(env) }),
new webpack.LoaderOptionsPlugin({
minimize: ifNotDevelopment(true),
options: {
eslint: {
formatter: require('eslint-friendly-formatter'),
configFile: '.eslintrc',
quiet: true
}
}
}),
new FaviconsWebpackPlugin('./assets/img/syncano-symbol.svg'),
ifNotDevelopment(...[
new webpack.optimize.CommonsChunkPlugin({
async: true,
children: true
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
filename: 'manifest.js',
minChunks: Infinity
}),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.css$/,
threshold: 10240,
minRatio: 0.8
})
]),
env.deploy && new S3Plugin(getS3Config(env))
]),
resolve: {
extensions: ['.js', '.jsx'],
modules: [
'node_modules'
]
},
externals: {
analyticsjs: 'window.analytics',
stripejs: 'Stripe'
},
stats: 'errors-only',
devServer: {
stats: 'errors-only'
}
};
if (env.debug) {
console.log(config);
debugger; // eslint-disable-line
}
return config;
};
export default webpackConfig;
|
'use strict';
angular.module('giv2givApp')
.factory('donor', function ($resource, appConfig) {
var url = appConfig.apiUrl;
var endpoint = "/donors.json"
return $resource(url + endpoint);
});
|
'use strict';
var UserTokens = require('./userTokens');
module.exports = function(){
var userTokens = new UserTokens();
return {
_connections : {},
_userTokens : userTokens,
put : function(user, token , type, connection){
this._userTokens.put(user, token);
this._connections[token] = {
type : type,
connection : connection
};
},
updateConnection : function(token, newConnection){
if(!token)
return;
var connection = this._connections[token];
if(!connection)
return;
connection.connection = newConnection;
this._connections[token] = connection;
},
getByToken : function(token){
if(token)
return this._connections[token];
},
getByUser : function(user){
var token = this._userTokens.getByUser(user);
if(token)
return this._connections[token];
},
forEach : function(cb){
for(var token in this._connections){
cb(this._connections[token]);
}
},
setUserToken : function(user, token){
if(!user || !token)
return;
if(this._connections[token])
return this._userTokens.put(user,token);
},
delByToken : function(token){
this._userTokens.delByToken(token);
if(this._connections[token])
delete this._connections[token];
}
};
}; |
var gulp = require('gulp');
var fs = require('fs');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var spawn = require('child_process').spawn;
var gutil = require('gulp-util');
gulp.task('default', function() {
console.log('Default Gulp');
});
gulp.task('server', function() {
console.log('Starting livereload server...');
gulp.src('sample/jsunittestingsample/static/js/app/**.js')
.pipe(watch())
.pipe(livereload());
});
gulp.task('test', function() {
return gulp.watch('sample/jsunittestingsample/static/js/**.js', function(e) {
var child = spawn("testem", [], {cwd: process.cwd()}),
stdout = '',
stderr = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', function (data) {
stdout += data;
gutil.log(data);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
stderr += data;
gutil.log(gutil.colors.red(data));
gutil.beep();
});
child.on('close', function(code) {
gutil.log("Done with exit code", code);
gutil.log("You access complete stdout and stderr from here"); // stdout, stderr
});
e();
});
});
gulp.task('testci', function() {
return gulp.watch('sample/jsunittestingsample/static/js/**.js', function(e) {
var child = spawn("testem", ['ci'], {cwd: process.cwd()}),
stdout = '',
stderr = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', function (data) {
stdout += data;
gutil.log(data);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
stderr += data;
gutil.log(gutil.colors.red(data));
gutil.beep();
});
child.on('close', function(code) {
gutil.log("Done with exit code", code);
gutil.log("You access complete stdout and stderr from here"); // stdout, stderr
});
e();
});
});
gulp.task('clean', function() {
return gulp.src('sample/jsunittestingsample/static/build', {read: false})
.pipe(clean());
});
gulp.task('build', function(cb) {
//runSequence(
// 'clean',
// ['less','js_build', 'coffeescript']
//);
console.log("This is the build task.");
});
|
module.exports = function (app, db) {
return function (opts) {
var middleware = function (req, res, next) {
if (opts.whitelist && opts.whitelist(req)) return next()
opts.lookup = Array.isArray(opts.lookup) ? opts.lookup : [opts.lookup]
opts.onRateLimited = typeof opts.onRateLimited === 'function' ? opts.onRateLimited : function (req, res, next) {
res.status(429).send('Rate limit exceeded')
}
var lookups = opts.lookup.map(function (item) {
return item + ':' + item.split('.').reduce(function (prev, cur) {
return prev[cur]
}, req)
}).join(':')
var path = opts.path || req.path
var method = (opts.method || req.method).toLowerCase()
var key = 'ratelimit:' + path + ':' + method + ':' + lookups
db.get(key, function (err, limit) {
if (err && opts.ignoreErrors) return next()
var now = Date.now()
limit = limit ? JSON.parse(limit) : {
total: opts.total,
remaining: opts.total,
reset: now + opts.expire
}
if (now > limit.reset) {
limit.reset = now + opts.expire
limit.remaining = opts.total
}
// do not allow negative remaining
limit.remaining = Math.max(Number(limit.remaining) - 1, -1)
db.set(key, JSON.stringify(limit), 'PX', opts.expire, function (e) {
if (!opts.skipHeaders) {
res.set('X-RateLimit-Limit', limit.total)
res.set('X-RateLimit-Reset', Math.ceil(limit.reset / 1000)) // UTC epoch seconds
res.set('X-RateLimit-Remaining', Math.max(limit.remaining,0))
}
if (limit.remaining >= 0) return next()
var after = (limit.reset - Date.now()) / 1000
if (!opts.skipHeaders) res.set('Retry-After', after)
opts.onRateLimited(req, res, next)
})
})
}
if (typeof(opts.lookup) === 'function') {
middleware = function (middleware, req, res, next) {
return opts.lookup(req, res, opts, function () {
return middleware(req, res, next)
})
}.bind(this, middleware)
}
if (opts.method && opts.path) app[opts.method](opts.path, middleware)
return middleware
}
}
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define("require exports ./nextTick ./libs/gl-matrix-2/mat3f64 ./libs/gl-matrix-2/mat4f64 ./libs/gl-matrix-2/quatf64 ./libs/gl-matrix-2/vec2f64 ./libs/gl-matrix-2/vec3f64 ./libs/gl-matrix-2/vec4f64".split(" "),function(d,e,f,g,h,k,l,m,n){Object.defineProperty(e,"__esModule",{value:!0});d=function(){function b(a,b,c){var p=this;this.itemByteSize=a;this.itemCreate=b;this.buffers=[];this.items=[];this.itemsPtr=this.itemsPerBuffer=0;this.itemsPerBuffer=Math.ceil(c/this.itemByteSize);this.tickHandle=f.before(function(){return p.reset()})}
b.prototype.destroy=function(){this.tickHandle&&(this.tickHandle.remove(),this.tickHandle=null);this.itemsPtr=0;this.buffers=this.items=null};b.prototype.get=function(){0===this.itemsPtr&&f(function(){});for(var a=Math.floor(this.itemsPtr/this.itemsPerBuffer);this.buffers.length<=a;){for(var b=new ArrayBuffer(this.itemsPerBuffer*this.itemByteSize),c=0;c<this.itemsPerBuffer;++c)this.items.push(this.itemCreate(b,c*this.itemByteSize));this.buffers.push(b)}return this.items[this.itemsPtr++]};b.prototype.reset=
function(){for(var a=2*(Math.floor(this.itemsPtr/this.itemsPerBuffer)+1);this.buffers.length>a;)this.buffers.pop(),this.items.length=this.buffers.length*this.itemsPerBuffer;this.itemsPtr=0};b.createVec2f64=function(a){void 0===a&&(a=c);return new b(16,l.vec2f64.createView,a)};b.createVec3f64=function(a){void 0===a&&(a=c);return new b(24,m.vec3f64.createView,a)};b.createVec4f64=function(a){void 0===a&&(a=c);return new b(32,n.vec4f64.createView,a)};b.createMat3f64=function(a){void 0===a&&(a=c);return new b(72,
g.mat3f64.createView,a)};b.createMat4f64=function(a){void 0===a&&(a=c);return new b(128,h.mat4f64.createView,a)};b.createQuatf64=function(a){void 0===a&&(a=c);return new b(32,k.quatf64.createView,a)};Object.defineProperty(b.prototype,"test",{get:function(){return{size:this.buffers.length*this.itemsPerBuffer*this.itemByteSize}},enumerable:!0,configurable:!0});return b}();e.VectorStack=d;var c=4096}); |
define(['mn',
'text!templates/setting/membershipItem.html',
'alertify'
], function(Mn, template,alertify) {
var MembershipItem = Mn.ItemView.extend({
template: function(model) {
return _.template(template, {
model: model
})
},
ui:{
submit:".changeButton",
form:".infoForm"
},
events:{
"click @ui.submit":"changeSetting"
},
changeSetting:function(e){
e.preventDefault();
e.stopPropagation();
var formData = this.ui.form.serializeObject()
this.model.save(formData,{success:function(){
alertify.alert("修改成功")
}})
}
})
//usually returning the object you created...
return MembershipItem;
}); |
export const centerGameObjects = (objects) => {
objects.forEach(function (object) {
object.anchor.setTo(0.5)
})
}
export const shuffle = (arr) => {
let j = 0
for (let i = arr.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1))
swap(arr, i, j)
}
}
export const swap = (arr, i, j) => {
let tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
}
|
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _SwitchRequest = require('../SwitchRequest');
var _SwitchRequest2 = _interopRequireDefault(_SwitchRequest);
var _modelsMediaPlayerModel = require('../../models/MediaPlayerModel');
var _modelsMediaPlayerModel2 = _interopRequireDefault(_modelsMediaPlayerModel);
var _controllersAbrController = require('../../controllers/AbrController');
var _controllersAbrController2 = _interopRequireDefault(_controllersAbrController);
var _coreFactoryMaker = require('../../../core/FactoryMaker');
var _coreFactoryMaker2 = _interopRequireDefault(_coreFactoryMaker);
var _coreDebug = require('../../../core/Debug');
var _coreDebug2 = _interopRequireDefault(_coreDebug);
function BufferOccupancyRule(config) {
var instance = undefined;
var context = this.context;
var log = (0, _coreDebug2['default'])(context).getInstance().log;
var metricsModel = config.metricsModel;
var dashMetrics = config.dashMetrics;
var lastSwitchTime = undefined,
mediaPlayerModel = undefined;
function setup() {
lastSwitchTime = 0;
mediaPlayerModel = (0, _modelsMediaPlayerModel2['default'])(context).getInstance();
}
function execute(rulesContext, callback) {
var now = new Date().getTime() / 1000;
var mediaInfo = rulesContext.getMediaInfo();
var representationInfo = rulesContext.getTrackInfo();
var mediaType = mediaInfo.type;
var waitToSwitchTime = !isNaN(representationInfo.fragmentDuration) ? representationInfo.fragmentDuration / 2 : 2;
var current = rulesContext.getCurrentValue();
var streamProcessor = rulesContext.getStreamProcessor();
var abrController = streamProcessor.getABRController();
var metrics = metricsModel.getReadOnlyMetricsFor(mediaType);
var lastBufferLevel = dashMetrics.getCurrentBufferLevel(metrics);
var lastBufferStateVO = metrics.BufferState.length > 0 ? metrics.BufferState[metrics.BufferState.length - 1] : null;
var isBufferRich = false;
var maxIndex = mediaInfo.representationCount - 1;
var switchRequest = (0, _SwitchRequest2['default'])(context).create(_SwitchRequest2['default'].NO_CHANGE, _SwitchRequest2['default'].WEAK, { name: BufferOccupancyRule.__dashjs_factory_name });
if (now - lastSwitchTime < waitToSwitchTime || abrController.getAbandonmentStateFor(mediaType) === _controllersAbrController2['default'].ABANDON_LOAD) {
callback(switchRequest);
return;
}
if (lastBufferStateVO !== null) {
// This will happen when another rule tries to switch from top to any other.
// If there is enough buffer why not try to stay at high level.
if (lastBufferLevel > lastBufferStateVO.target) {
isBufferRich = lastBufferLevel - lastBufferStateVO.target > mediaPlayerModel.getRichBufferThreshold();
if (isBufferRich && mediaInfo.representationCount > 1) {
switchRequest.value = maxIndex;
switchRequest.priority = _SwitchRequest2['default'].STRONG;
switchRequest.reason.bufferLevel = lastBufferLevel;
switchRequest.reason.bufferTarget = lastBufferStateVO.target;
}
}
}
if (switchRequest.value !== _SwitchRequest2['default'].NO_CHANGE && switchRequest.value !== current) {
log('BufferOccupancyRule requesting switch to index: ', switchRequest.value, 'type: ', mediaType, ' Priority: ', switchRequest.priority === _SwitchRequest2['default'].DEFAULT ? 'Default' : switchRequest.priority === _SwitchRequest2['default'].STRONG ? 'Strong' : 'Weak');
}
callback(switchRequest);
}
function reset() {
lastSwitchTime = 0;
}
instance = {
execute: execute,
reset: reset
};
setup();
return instance;
}
BufferOccupancyRule.__dashjs_factory_name = 'BufferOccupancyRule';
exports['default'] = _coreFactoryMaker2['default'].getClassFactory(BufferOccupancyRule);
module.exports = exports['default'];
//# sourceMappingURL=BufferOccupancyRule.js.map
|
export let EntityMethod = class EntityMethod {
constructor(source, name) {
this.source = source;
this.name = name;
}
execute(params, options) {
return new Promise((resolve, reject) => {
this.source.__queueRequest(done => {
let entity = this.source.entity;
if (entity) {
entity = this.source.entity[this.source.key];
}
if (entity) {
options = options === undefined ? {} : options;
let asPost = true === options.asPost;
let dataURI = this.source.dataURI + "(" + this.source.entity[this.source.key] + ")" + "/" + this.name;
let restString = this.source.restApi.generateRestString(dataURI, {
params: asPost ? null : params
});
let requestOptions = {
body: asPost ? params : null,
method: asPost ? "post" : "get"
};
this.source.restApi.callServer(restString, requestOptions).then(data => {
done();
resolve(data);
}).catch(err => {
done();
reject(err);
});
} else {
done();
reject({ message: "no currentEntity" });
}
});
});
}
}; |
//============================================================================
/*
// Sky Generator 1.3 - an HTML generator inspired by Emmet
// Copyright (c) 2014, Ilia Yatchev (MIT Licensed)
// https://github.com/IliaSky/skygenerator
*/
//============================================================================
//
// USAGE INSTRUCTIONS
//
// This file will export the global variable SG
// API:
// SG(pattern, object)
// SG.wrap(html, selector)
//
// Config:
// SG.VIEWS -> your views (patterns or templates)
// SG.FLAGS -> flags allow minor conditional logic inside the templates
// SG.FILTERS ->
// you can apply them when interpolating attributes and switching objects
// by default: 'default' is used when interpolating object attributes
// and 'safe' is used when switching objects
//
// Although it is not recommended you can also alter:
// SG.REGEX -> regexes used in the script - alter at your own risk
// SG.SELF_CLOSING_TAGS and SG.BOOLEAN_ATTRIBUTES -> change them if you want
//============================================================================
//
// PATTERN INSTRUCTIONS
//
// $.VIEW = inserts view pattern from SG.VIEWS
// tag#id.class
// #this.will.be.a.div.if.there.is.no.tag
// tag + tag
// element[text without html elements]
// span[This content will be displayed in a span tag]
// note[text inside square brackets is the only place where space matters]
// [if tag, id and class are all missing then this will be in a text node]
// tag(attribute:value) tag(attr:val, attr:val)
// a(href:#)[click me] + input(type: number, value: 5)
// outer-tag > inner-tag outer{ inner + inner }
// section{ h1[title] + atricle[content] }
//
// @var = inserts variable from current data object
// @@ = inserts the value of the current object
// @(var){markup} = changes current object to object.var inside the brackets
// ?(flag){markup} = renders markup if flag is on
// @(var|f){}, @var|f, @@|f = Also applies the filter f from SG.FILTERS
// *markup = repeats the markup for each element in the current object (array)
//
//============================================================================
//
// REAL WORLD EXAMPLE PATTERNS
//
/*
SG.VIEWS = {
ID : "data-id:@id",
RENT_RETURN : "div.rent-return > button.return-movie($.ID)[Return]+button.rent-movie($.ID)[Rent]",
STORE : "a.store(href:#info/@id)[@title]",
CATEGORY : "a.category(href:#category-info/@id,title:@name)[@name]",
ACTOR : "a.actor(href:#actor-info/@id)[@firstName @lastName]",
MOVIE : "h1{a.movie(href:#movie-info/@id)[@title]} + span.date[from @publishDate] +$.RENT_RETURN +article[@description]",
STORES : "section#stores > h1[Stores] + nav > *$.STORE",
CATEGORIES : "section#categories > h1[Categories] + nav > *$.CATEGORY",
ACTORS : "section#actors > h1[Actors] + nav> *$.ACTOR",
MOVIES : "ul#movies > *li > section > $.MOVIE",
STORE_INFO : "section#store-info > h1{$.STORE} + @(movies){$.MOVIES}",
CATEGORY_INFO : "section#category-info > h1{$.CATEGORY} + @(movies){$.MOVIES}",
ACTOR_INFO : "section#actor-info > h1{$.ACTOR} + @(movies){$.MOVIES}",
MOVIE_INFO : "div#movie-info > @(actors){$.ACTORS} + section#movie-basic-info{$.MOVIE}+ $(categories){$.CATEGORIES} + @(stores){$.STORES}",
USERNAME: "label(for:username)[Username]+input#username(type:text,required)",
PASSWORD: "label(for:password)[Password]+input#password(type:password,required)",
PASSWORD_AGAIN: "label(for:password-again)[Password Again]+input#password-again(type:password,required)",
SUBMIT: "input(type:submit)",
LOGIN : "form#login-form > $.USERNAME + $.PASSWORD + $.SUBMIT",
REGISTER : "form#register-form> $.USERNAME + $.PASSWORD + $.PASSWORD_AGAIN + $.SUBMIT",
FIND_CATEGORY : "form#search-form> label(for:search)[Search Categories]+input#search(placeholder:Search,list:search-data-list) + input(type:submit,value:Search) + datalist#search-data-list > *option(value:$name,$.ID)",
ALL_CATEGORIES : "$.FIND_CATEGORY + $.CATEGORIES"
};
*/
//============================================================================
(function() {
/***** indexOf and map for Older IE **********/
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(element) {
for (var i = 0, n = this.length; i < n; i++)
if(this[i] === element)
return i;
return -1;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function(func) {
var output = [];
for(var i = 0, n = this.length; i < n; i++)
output[i] = func(this[i]);
return output;
};
}
SG = function (str, obj){
var i, m, n, unclosedBrackets = 0;
// Change a>b+c>d+e to a{b+c{d+e}}
str = expandInlineTemplates(str);
str = greaterThanToBrackets(str);
// Remove all whitespace except for spaces inside []
str = str.replace(/ (?=[^\[]*\])/g,' ').replace(/[\s]/g,'').replace(/ /g,' ');
// If the pattern begins with * then returns the sum of the pattern filled with each element in the array(obj)
if (str.charAt(0)=='*')
return obj.map(function(x){ return SG(str.slice(1), x); }).join('');
// render both sides of '+', not inside {} using recursion
for(i = 0, n = str.length; i < n; i++){
unclosedBrackets += (str.charAt(i) == '{') - (str.charAt(i) == '}');
if (unclosedBrackets === 0 && str.charAt(i) == '+')
return SG(str.slice(0, i), obj) + SG(str.slice(i + 1), obj);
}
// @(inner){} => Change current object to obj.inner
// @(inner|filter){} => Also apply filter if there is such
if (m = str.match(SG.REGEX.CONTEXT_CHANGE))
return obj ? SG(m[3], SG.FILTERS[m[2] || 'safe'](obj[m[1]])) : ''; // maybe change this behaviour?
// ?(flag){} => Render only when SG.FLAGS[flag] is true when
if (m = str.match(SG.REGEX.FLAG))
return SG.FLAGS[m[1]] ? SG(m[2], obj) : '';
// render simple selector and content
m = str.match(SG.REGEX.ELEMENT);
// replace @var with object.var and @var|f with SG.FILTERS[f](object.var)
var selector = insertVariableValues(m[1], obj);
var textNode = m[2] && insertVariableValues(m[2], obj) || '';
var innerElements = m[3] && SG(m[3], obj) || '';
return SG.wrap(textNode + innerElements, selector);
};
SG.VIEWS = {};
SG.FLAGS = {};
SG.FILTERS = {
stringify: function(e){
return JSON.stringify(e);
},
escape: function(string) {
var pre = document.createElement('pre');
pre.appendChild(document.createTextNode(string));
return pre.innerHTML;
},
safe: function(string){
return string;
}
};
SG.FILTERS['default'] = SG.FILTERS.escape;
SG.SELF_CLOSING_TAGS = "area base br col hr img input link meta param command keygen source".split(' ');
SG.BOOLEAN_ATTRIBUTES = "async autofocus autoplay checked controls default defer disabled formnovalidate hidden ismap loop multiple muted novalidate open readonly required reversed scoped seamless selected truespeed typemustmatch".split(' ');
SG.REGEX = {
TAG : /^([\-_a-zA-Z0-9$]*)/,
ID : /(?:#([\-_a-zA-Z0-9$]*))?/,
CLASS : /([\-._a-zA-Z0-9$]*)/,
ATTR : /(?:\(([?=&\.\/\-_a-zA-Z0-9@\|$:,#\/]*)\))?/,
SIMPLE_SELECTOR : /([?=\-_a-zA-Z0-9@\|.#(:\/,)$]*)/,
INNER_ELEMENTS : /(?:\{([?=\-_a-zA-Z0-9.#(:,)@\|$\[\] +*{}\/]*)\})?/,
TEXT_NODE : /(?:\[([\-_a-zA-Z0-9@\|$ ]*)\])?/,
CONTEXT_CHANGE : /^@\(([_a-z]+)(?:\|([_a-z]+))?\)\{(.*)\}/i,
FLAG : /^\?\(([_a-z]+)\)\{(.*)\}/i,
VARIABLE : /@(@|[_a-z]+)(?:\|([_a-z]+))?/gi
};
var regexConcat = function (arr){
return RegExp(arr.map(function(e){return SG.REGEX[e].source;}).join(''));
};
SG.REGEX.SELECTOR = regexConcat(['TAG', 'ID', 'CLASS', 'ATTR']);
SG.REGEX.ELEMENT = regexConcat(['SIMPLE_SELECTOR', 'TEXT_NODE', 'INNER_ELEMENTS']);
var greaterThanToBrackets = function (str){
return str.split('>').join('{') + new Array(str.split('>').length).join('}');
};
var expandInlineTemplates = function (str){
for (var i in SG.VIEWS){
var regex = RegExp('\\$\\.' + i + '(?=([^_a-z]|$))','gi');
if (str.match(regex))
str = str.replace(regex, expandInlineTemplates(greaterThanToBrackets(SG.VIEWS[i])));
}
return str;
};
var insertVariableValues = function (str, obj){
return str.replace(SG.REGEX.VARIABLE, function(_, key, filter){
return SG.FILTERS[filter || 'default'](key == '@' ? obj : obj[key]);
});
};
var attr = function (key, value){
if (value)
return ' ' + key.replace(/"/g, '') + '="' + value.replace(/"/g, '\"') + '"';
if (SG.BOOLEAN_ATTRIBUTES.indexOf(key) != -1)
return ' ' + key;
return '';
};
var multipleAttributes = function (array){
return array.map(function(kv){ return attr(kv[0], kv[1]); }).join('');
};
SG.wrap = function (html, selector){
var m = selector.match(SG.REGEX.SELECTOR);
var tag = m[1];
var id = m[2];
var klass = m[3].slice(1).replace(/\./g, ' ');
var attributes = (m[4] || '').split(',').map(function(kv){
var i = kv.indexOf(':');
return [kv.slice(0, i), kv.slice(i + 1)];
});
// set href of anchor tag to # if missing
var attrNames = attributes.map(function(kv){ return kv[0]; });
if (tag == 'a' && attrNames.indexOf('href') == -1)
attributes.push(['href','#']);
if (tag == 'input' && html !== '')
attributes.push(['value', html.replace(/"/g, '\"')]);
// return text node if there is no selector
if (tag + id + klass === '')
return html;
// make div the default tag
tag = tag || 'div';
// create text of opening tag
var text = tag + attr('id',id) + attr('class',klass) + multipleAttributes(attributes);
// create self closing tag
if (SG.SELF_CLOSING_TAGS.indexOf(tag) != -1)
return "<" + text +" />";
// create normal tag
return "<" + text +">" + html + "</" + tag +">";
};
})(); |
var proxyquire = require('proxyquire').noCallThru();
var sinon = require('sinon');
var expect = require('chai').expect;
describe('check factory', function() {
it('returns a default check if non specified', function() {
var factory = require('../checks');
var checker = factory.create();
expect(checker.check).to.exist();
});
it('returns a checker containing the specified reporters', function() {
// Arrange
var check = sinon.spy();
var factory = proxyquire('../checks', {
'./mock.js': {
create: function() { return {
check: check,
}}
}
});
// Act
var checker = factory.create({ mock: {} });
var url = 'http://test.example.com', response = { status: 200 }, time = 132;
checker.check(url, response, time);
// Assert
expect(check.calledWith(url, response, time)).to.be.true();
});
it('passes config to the specified checks', function() {
// Arrange
var actualConfig = null;
var factory = proxyquire('../checks', {
'./mock.js': {
create: function(config) { actualConfig = config; }
}
});
// Act
var reporter = factory.create({ mock: { foo: 'bar' } });
// Assert
expect(actualConfig.foo).to.eq('bar');
});
});
|
module.exports = (function () {
var PI2 = Math.PI * 2;
return {
normalizeRadian: function(angle) {
angle %= PI2;
if (angle < 0) {
angle += PI2;
}
return angle;
}
};
})(); |
#!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const pkg = require( path.join(__dirname, 'package.json') );
const server = require('./dist/server');
const program = require('commander');
program.version(pkg.version)
.option('-c --config <config>', 'config file for mongodb backup manager')
.option('-p --serverPort <serverPort>', 'mongodb backup manager port number', parseInt)
.option('-i --interval <interval>', 'interval for task pool scanning', parseInt)
.option('--dbServer <dbServer>', 'local database server address')
.option('--dbPort <dbPort>', 'local database server port number', parseInt)
.option('--username <username>', 'username for local database')
.option('--password <password>', 'password for local database')
.option('--authDB <authDB>', 'authentication DB for local database')
.option('--log <logLevel>', 'log level for the system')
.parse(process.argv);
let options = ["config", "serverPort", "interval", "dbServer", "dbPort", "username", "password", "authDB", "log"]
let managerConfig = {};
for(let opt of options) {
let o = program[opt];
if(o != null) {
managerConfig[opt] = o;
}
}
server.start(managerConfig); |
'use strict';
/* eslint comma-dangle:[0, "only-multiline"] */
module.exports = {
client: {
lib: {
css: [
// bower:css
'public/lib/bootstrap/dist/css/bootstrap.css',
//'public/lib/bootstrap/dist/css/bootstrap-theme.css',
'public/lib/angular-ui-notification/dist/angular-ui-notification.css',
'public/bootflat/css/bootflat.css',
'public/site.css'
// endbower
],
js: [
// bower:js
'public/lib/angular/angular.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/ng-file-upload/ng-file-upload.js',
'public/lib/angular-file-upload/dist/angular-file-upload.js',
'public/lib/angular-messages/angular-messages.js',
'public/lib/angular-mocks/angular-mocks.js',
'public/lib/angular-modal/modal.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-spinner/dist/angular-spinner.js',
'public/lib/angular-ui-notification/dist/angular-ui-notification.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-translate/angular-translate.js',
'public/lib/angular-translate-loader-url/angular-translate-loader-url.js',
'public/lib/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
'public/lib/jquery/dist/jquery.js',
'public/lib/bootstrap/dist/js/bootstrap.js',
'public/lib/js-hypercube-master/src/ps.js',
'public/lib/js-hypercube-master/src/ps.array.js',
'public/lib/js-hypercube-master/src/ps.object.js',
'public/lib/js-hypercube-master/src/ps.FactIndex.js',
'public/lib/js-hypercube-master/src/ps.Cell.js',
'public/lib/js-hypercube-master/src/ps.Cube.js',
'public/lib/js-hypercube-master/src/ps.Cube.transforms.js'
// endbower
],
tests: ['public/lib/angular-mocks/angular-mocks.js']
},
css: [
'modules/*/client/{css,less,scss}/*.css'
],
less: [
'modules/*/client/less/*.less'
],
sass: [
'modules/*/client/scss/*.scss'
],
js: [
'modules/core/client/app/config.js',
'modules/core/client/app/init.js',
'modules/*/client/*.js',
'modules/*/client/**/*.js'
],
img: [
'modules/**/*/img/**/*.jpg',
'modules/**/*/img/**/*.png',
'modules/**/*/img/**/*.gif',
'modules/**/*/img/**/*.svg'
],
views: ['modules/*/client/views/**/*.html'],
templates: ['build/templates.js']
},
server: {
gulpConfig: ['gulpfile.js'],
allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
models: 'modules/*/server/models/**/*.js',
routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
sockets: 'modules/*/server/sockets/**/*.js',
config: ['modules/*/server/config/*.js'],
policies: 'modules/*/server/policies/*.js',
views: ['modules/*/server/views/*.html']
}
};
|
'use strict';
import angular from 'angular';
import ngRouter from 'angular-route';
import pagesRouter from './pagesRouter';
import MainPageCtrl from './controllers/MainPageCtrl';
/*
Module of static pages without complex logics
*/
export default angular.module('app.pages', [ngRouter])
.config(pagesRouter)
.controller('MainPageCtrl', MainPageCtrl)
.name; |
'use strict';
class SomeMod3 {
constructor(someMod4) {
console.log('Creating SomeMode3');
}
callMe() {
console.log('show me some thing');
}
}
module.exports = SomeMod3; |
/**
* Copyright (c) 2008-2011 The Open Planning Project
*
* Published under the BSD license.
* See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
* of the license.
*/
/** api: (define)
* module = gxp
* class = LayerUploadPanel
* base_link = `Ext.FormPanel <http://extjs.com/deploy/dev/docs/?class=Ext.FormPanel>`_
*/
Ext.namespace("gxp");
/** api: constructor
* .. class:: LayerUploadPanel(config)
*
* A panel for uploading new layer data to GeoServer.
*/
gxp.LayerUploadPanel = Ext.extend(Ext.FormPanel, {
/** i18n */
titleLabel: "Title",
titleEmptyText: "Layer title",
abstractLabel: "Description",
abstractEmptyText: "Layer description",
fileLabel: "Data",
fieldEmptyText: "Browse for data archive...",
uploadText: "Upload",
waitMsgText: "Uploading your data...",
invalidFileExtensionText: "File extension must be one of: ",
optionsText: "Options",
workspaceLabel: "Workspace",
workspaceEmptyText: "Default workspace",
dataStoreLabel: "Store",
dataStoreEmptyText: "Default datastore",
crsLabel: "CRS",
crsEmptyText: "Coordinate Reference System ID",
invalidCrsText: "CRS identifier should be an EPSG code (e.g. EPSG:4326)",
/** private: property[fileUpload]
* ``Boolean``
*/
fileUpload: true,
/** api: config[validFileExtensions]
* ``Array``
* List of valid file extensions. These will be used in validating the
* file input value. Default is ``[".zip", ".tif", ".gz", ".tar.bz2",
* ".tar", ".tgz", ".tbz2"]``.
*/
validFileExtensions: [".zip", ".tif", ".gz", ".tar.bz2", ".tar", ".tgz", ".tbz2"],
/** api: config[url]
* ``String``
* URL for GeoServer RESTConfig root. E.g. "http://example.com/geoserver/rest".
*/
/** private: method[constructor]
*/
constructor: function(config) {
// Allow for a custom method to handle upload responses.
config.errorReader = {
read: config.handleUploadResponse || this.handleUploadResponse.createDelegate(this)
};
gxp.LayerUploadPanel.superclass.constructor.call(this, config);
},
/** private: property[selectedWorkspace]
* {Ext.data.Record}
*/
selectedWorkspace: null,
/** private: method[initComponent]
*/
initComponent: function() {
this.items = [{
xtype: "textfield",
name: "title",
fieldLabel: this.titleLabel,
emptyText: this.titleEmptyText,
allowBlank: true
}, {
xtype: "textarea",
name: "abstract",
fieldLabel: this.abstractLabel,
emptyText: this.abstractEmptyText,
allowBlank: true
}, {
xtype: "fileuploadfield",
id: "file",
emptyText: this.fieldEmptyText,
fieldLabel: this.fileLabel,
name: "file",
buttonText: "",
buttonCfg: {
iconCls: "gxp-icon-filebrowse"
},
validator: this.fileNameValidator.createDelegate(this)
}, {
xtype: "fieldset",
title: this.optionsText,
checkboxToggle: true,
collapsed: true,
hideMode: "offsets",
defaults: {
anchor: "97%"
},
items: [
this.createWorkspacesCombo(),
this.createDataStoresCombo(),
{
xtype: "textfield",
name: "crs",
// anchor: "90%",
fieldLabel: this.crsLabel,
emptyText: this.crsEmptyText,
allowBlank: true,
regex: /^epsg:\d+$/i,
regexText: this.invalidCrsText
}
],
listeners: {
collapse: function(fieldset) {
// reset all combos
fieldset.items.each(function(item) {
item.reset();
});
}
}
}];
this.buttons = [{
text: this.uploadText,
handler: function() {
var form = this.getForm();
if (form.isValid()) {
form.submit({
url: this.getUploadUrl(),
submitEmptyText: false,
waitMsg: this.waitMsgText,
waitMsgTarget: true,
reset: true,
success: this.handleUploadSuccess,
scope: this
});
}
},
scope: this
}];
this.addEvents(
/**
* Event: workspaceselected
* Fires when a workspace is selected.
*
* Listener arguments:
* panel - {<gxp.LayerUploadPanel} This form panel.
* record - {Ext.data.Record} The selected workspace record.
*/
"workspaceselected",
/**
* Event: datastoreselected
* Fires when a datastore is selected.
*
* Listener arguments:
* panel - {<gxp.LayerUploadPanel} This form panel.
* record - {Ext.data.Record} The selected datastore record.
*/
"datastoreselected",
/**
* Event: uploadcomplete
* Fires upon successful upload.
*
* Listener arguments:
* panel - {<gxp.LayerUploadPanel} This form panel.
* details - {Object} An object with "name" and "href" properties
* corresponding to the uploaded layer name and resource href.
*/
"uploadcomplete"
);
gxp.LayerUploadPanel.superclass.initComponent.call(this);
},
/** private: method[fileNameValidator]
* :arg name: ``String`` The chosen filename.
* :returns: ``Boolean | String`` True if valid, message otherwise.
*/
fileNameValidator: function(name) {
var valid = false;
var ext, len = name.length;
for (var i=0, ii=this.validFileExtensions.length; i<ii; ++i) {
ext = this.validFileExtensions[i];
if (name.slice(-ext.length).toLowerCase() === ext) {
valid = true;
break;
}
}
return valid || this.invalidFileExtensionText + this.validFileExtensions.join(", ");
},
/** private: method[createWorkspacesCombo]
* :returns: ``Object`` Combo config.
*/
createWorkspacesCombo: function() {
return {
xtype: "combo",
name: "workspace",
fieldLabel: this.workspaceLabel,
emptyText: this.workspaceEmptyText,
store: new Ext.data.JsonStore({
url: this.getWorkspacesUrl(),
autoLoad: true,
root: "workspaces.workspace",
fields: ["name", "href"]
}),
displayField: "name",
valueField: "name",
mode: "local",
allowBlank: true,
triggerAction: "all",
editable: false,
listeners: {
select: function(combo, record, index) {
this.fireEvent("workspaceselected", this, record);
},
scope: this
}
};
},
/** private: method[createDataStoresCombo]
* :returns: ``Ext.form.ComboBox``
*/
createDataStoresCombo: function() {
// this store will be loaded whenever a workspace is selected
var store = new Ext.data.JsonStore({
autoLoad: false,
root: "dataStores.dataStore",
fields: ["name", "href"]
});
this.on({
workspaceselected: function(panel, record) {
combo.reset();
var workspaceUrl = record.get("href");
store.removeAll();
store.proxy = new Ext.data.HttpProxy({
url: workspaceUrl.split(".json").shift() + "/datastores.json"
});
store.load();
},
scope: this
});
var combo = new Ext.form.ComboBox({
name: "store",
fieldLabel: this.dataStoreLabel,
emptyText: this.dataStoreEmptyText,
store: store,
displayField: "name",
valueField: "name",
mode: "local",
allowBlank: true,
triggerAction: "all",
editable: false,
listeners: {
select: function(combo, record, index) {
this.fireEvent("datastoreselected", this, record);
},
scope: this
}
});
return combo;
},
/** private: method[getUploadUrl]
*/
getUploadUrl: function() {
return this.url + "/upload";
},
/** private: method[getWorkspacesUrl]
*/
getWorkspacesUrl: function() {
return this.url + "/workspaces.json";
},
/** private: method[handleUploadResponse]
* TODO: if response includes errors object, this can be removed
* Though it should only be removed if the server always returns text/html!
*/
handleUploadResponse: function(response) {
var obj = this.parseResponseText(response.responseText);
var success = obj && obj.success;
var records = [];
if (!success) {
// mark the file field as invlid
records = [{data: {id: "file", msg: obj.message}}];
}
return {success: success, records: records};
},
/** private: parseResponseText
* :arg text: ``String``
* :returns: ``Object``
*
* Parse the response text. Assuming a JSON string but allowing for a
* string wrapped in a <pre> element (given non text/html response type).
*/
parseResponseText: function(text) {
var obj;
try {
obj = Ext.decode(text);
} catch (err) {
// if response type was text/plain, the text will be wrapped in a <pre>
var match = text.match(/^\s*<pre>(.*)<\/pre>\s*/);
if (match) {
try {
obj = Ext.decode(match[1]);
} catch (err) {
// pass
}
}
}
return obj;
},
/** private: method[handleUploadSuccess]
*/
handleUploadSuccess: function(form, action) {
var details = this.parseResponseText(action.response.responseText);
this.fireEvent("uploadcomplete", this, details);
}
});
/** api: xtype = gxp_layeruploadpanel */
Ext.reg("gxp_layeruploadpanel", gxp.LayerUploadPanel); |
/* Ship.js
KC3改 Ship Object
*/
(function(){
"use strict";
var deferList = {};
window.KC3Ship = function( data ){
// Default object properties included in stringifications
this.rosterId = 0;
this.masterId = 0;
this.level = 0;
this.exp = [0,0,0];
this.hp = [0,0];
this.afterHp = [0,0];
this.fp = [0,0];
this.tp = [0,0];
this.aa = [0,0];
this.ar = [0,0];
this.ev = [0,0];
this.as = [0,0];
this.ls = [0,0];
this.lk = [0,0];
this.range = 0;
// corresponds to "api_slot" in the API,
// but devs change it to length == 5 someday,
// and item of ex slot still not at 5th.
// extended to 5 slots on 2018-02-16 for Musashi Kai Ni.
this.items = [-1,-1,-1,-1,-1];
// corresponds to "api_slot_ex" in the API,
// which has special meanings on few values:
// 0: ex slot is not available
// -1: ex slot is available but nothing is equipped
this.ex_item = 0;
// "api_onslot" in API, also changed to length 5 now.
this.slots = [0,0,0,0,0];
this.slotnum = 0;
this.speed = 0;
// corresponds to "api_kyouka" in the API,
// represents [fp,tp,aa,ar,lk] in the past.
// expanded to 7-length array since 2017-09-29
// last new twos are [hp,as]
this.mod = [0,0,0,0,0,0,0];
this.fuel = 0;
this.ammo = 0;
this.repair = [0,0,0];
this.stars = 0;
this.morale = 0;
this.lock = 0;
this.sally = 0;
this.akashiMark = false;
this.preExpedCond = [
/* Data Example
["exped300",12,20, 0], // fully supplied
["exped301", 6,10, 0], // not fully supplied
NOTE: this will be used against comparison of pendingConsumption that hardly to detect expedition activities
*/
];
this.pendingConsumption = {
/* Data Example
typeName: type + W {WorldNum} + M {MapNum} + literal underscore + type_id
type_id can be described as sortie/pvp/expedition id
valueStructure: typeName int[3][3] of [fuel, ammo, bauxites] and [fuel, steel, buckets] and [steel]
"sortie3000":[[12,24, 0],[ 0, 0, 0]], // OREL (3 nodes)
"sortie3001":[[ 8,16, 0],[ 0, 0, 0]], // SPARKLE GO 1-1 (2 nodes)
"sortie3002":[[ 4,12, 0],[ 0, 0, 0]], // PVP (1 node+yasen)
"sortie3003":[[ 0, 0, 0],[ 0, 0, 0],[-88]], // 1 node with Jet battle of 36 slot
Practice and Expedition automatically ignore repair consumption.
For every action will be recorded before the sortie.
*/
};
this.lastSortie = ['sortie0'];
// Define properties not included in stringifications
Object.defineProperties(this,{
didFlee: {
value: false,
enumerable: false,
configurable: false,
writable: true
},
mvp: {
value: false,
enumerable: false,
configurable: false,
writable: true
},
// useful when making virtual ship objects.
// requirements:
// * "GearManager.get( itemId )" should get the intended equipment
// * "itemId" is taken from either "items" or "ex_item"
// * "shipId === -1 or 0" should always return a dummy gear
GearManager: {
value: null,
enumerable: false,
configurable: false,
writable: true
}
});
// If specified with data, fill this object
if(typeof data != "undefined"){
// Initialized with raw data
if(typeof data.api_id != "undefined"){
this.rosterId = data.api_id;
this.masterId = data.api_ship_id;
this.level = data.api_lv;
this.exp = data.api_exp;
this.hp = [data.api_nowhp, data.api_maxhp];
this.afterHp = [data.api_nowhp, data.api_maxhp];
this.fp = data.api_karyoku;
this.tp = data.api_raisou;
this.aa = data.api_taiku;
this.ar = data.api_soukou;
this.ev = data.api_kaihi;
this.as = data.api_taisen;
this.ls = data.api_sakuteki;
this.lk = data.api_lucky;
this.range = data.api_leng;
this.items = data.api_slot;
if(typeof data.api_slot_ex != "undefined"){
this.ex_item = data.api_slot_ex;
}
if(typeof data.api_sally_area != "undefined"){
this.sally = data.api_sally_area;
}
this.slotnum = data.api_slotnum;
this.slots = data.api_onslot;
this.speed = data.api_soku;
this.mod = data.api_kyouka;
this.fuel = data.api_fuel;
this.ammo = data.api_bull;
this.repair = [data.api_ndock_time].concat(data.api_ndock_item);
this.stars = data.api_srate;
this.morale = data.api_cond;
this.lock = data.api_locked;
// Initialized with formatted data
}else{
$.extend(this, data);
}
if(this.getDefer().length <= 0)
this.checkDefer();
}
};
// Define complex properties on prototype
Object.defineProperties(KC3Ship.prototype,{
bull: {
get: function(){return this.ammo;},
set: function(newAmmo){this.ammo = newAmmo;},
configurable:false,
enumerable :true
}
});
KC3Ship.prototype.getGearManager = function(){ return this.GearManager || KC3GearManager; };
KC3Ship.prototype.exists = function(){ return this.rosterId > 0 && this.masterId > 0; };
KC3Ship.prototype.isDummy = function(){ return ! this.exists(); };
KC3Ship.prototype.master = function(){ return KC3Master.ship( this.masterId ); };
KC3Ship.prototype.name = function(){ return KC3Meta.shipName( this.master().api_name ); };
KC3Ship.prototype.stype = function(){ return KC3Meta.stype( this.master().api_stype ); };
KC3Ship.prototype.equipment = function(slot){
switch(typeof slot) {
case 'number':
case 'string':
/* Number/String => converted as equipment slot key */
return this.getGearManager().get( slot < 0 || slot >= this.items.length ? this.ex_item : this.items[slot] );
case 'boolean':
/* Boolean => return all equipments with ex item if true */
return slot ? this.equipment().concat(this.exItem())
: this.equipment();
case 'undefined':
/* Undefined => returns whole equipment as equip object array */
return this.items
// cloned and fixed to max 4 slots if 5th or more slots not found
.slice(0, Math.max(this.slotnum, 4))
.map(Number.call, Number)
.map(i => this.equipment(i));
case 'function':
/* Function => iterates over given callback for every equipment */
var equipObjs = this.equipment();
equipObjs.forEach((item, index) => {
slot.call(this, item.itemId, index, item);
});
// forEach always return undefined, return equipment for chain use
return equipObjs;
}
};
KC3Ship.prototype.slotSize = function(slotIndex){
// ex-slot is always assumed to be 0 for now
return (slotIndex < 0 || slotIndex >= this.slots.length ? 0 : this.slots[slotIndex]) || 0;
};
KC3Ship.prototype.slotCapacity = function(slotIndex){
// no API data defines the capacity for ex-slot
var maxeq = (this.master() || {}).api_maxeq;
return (Array.isArray(maxeq) ? maxeq[slotIndex] : 0) || 0;
};
KC3Ship.prototype.areAllSlotsFull = function(){
// to left unfulfilled slots in-game, make bauxite insufficient or use supply button at expedition
var maxeq = (this.master() || {}).api_maxeq;
return Array.isArray(maxeq) ?
maxeq.every((expectedSize, index) => !expectedSize || expectedSize <= this.slotSize(index)) : true;
};
KC3Ship.prototype.isFast = function(){ return (this.speed || this.master().api_soku) >= 10; };
KC3Ship.prototype.getSpeed = function(){ return this.speed || this.master().api_soku; };
KC3Ship.prototype.exItem = function(){ return this.getGearManager().get(this.ex_item); };
KC3Ship.prototype.isStriped = function(){ return (this.hp[1]>0) && (this.hp[0]/this.hp[1] <= 0.5); };
// Current HP < 25% but already in the repair dock not counted
KC3Ship.prototype.isTaiha = function(){ return (this.hp[1]>0) && (this.hp[0]/this.hp[1] <= 0.25) && !this.isRepairing(); };
// To indicate the face grey out ship, retreated or sunk (before her data removed from API)
KC3Ship.prototype.isAbsent = function(){ return (this.didFlee || this.hp[0] <= 0 || this.hp[1] <= 0); };
KC3Ship.prototype.speedName = function(){ return KC3Meta.shipSpeed(this.speed); };
KC3Ship.prototype.rangeName = function(){ return KC3Meta.shipRange(this.range); };
KC3Ship.getMarriedLevel = function(){ return 100; };
KC3Ship.getMaxLevel = function(){ return 165; };
// hard-coded at `Core.swf/vo.UserShipData.VHP`
KC3Ship.getMaxHpModernize = function() { return 2; };
// hard-coded at `Core.swf/vo.UserShipData.VAS`
KC3Ship.getMaxAswModernize = function() { return 9; };
KC3Ship.prototype.isMarried = function(){ return this.level >= KC3Ship.getMarriedLevel(); };
KC3Ship.prototype.levelClass = function(){
return this.level === KC3Ship.getMaxLevel() ? "married max" :
this.level >= KC3Ship.getMarriedLevel() ? "married" :
this.level >= 80 ? "high" :
this.level >= 50 ? "medium" :
"";
};
/** @return full url of ship face icon according her hp percent. */
KC3Ship.prototype.shipIcon = function(){
return KC3Meta.shipIcon(this.masterId, undefined, true, this.isStriped());
};
KC3Ship.shipIcon = function(masterId, mhp = 0, chp = mhp){
const isStriped = mhp > 0 && (chp / mhp) <= 0.5;
return KC3Meta.shipIcon(masterId, undefined, true, isStriped);
};
/** @return icon file name only without path and extension suffix. */
KC3Ship.prototype.moraleIcon = function(){
return KC3Ship.moraleIcon(this.morale);
};
KC3Ship.moraleIcon = function(morale){
return morale > 49 ? "4" : // sparkle
morale > 29 ? "3" : // normal
morale > 19 ? "2" : // orange face
"1"; // red face
};
/**
* The reason why 53 / 33 is the bound of morale effect being taken:
* on entering battle, morale is subtracted -3 (day) or -2 (night) before its value gets in,
* so +3 value is used as the indeed morale bound for sparkle or fatigue.
*
* @param {Array} valuesArray - values to be returned based on morale section.
* @param {boolean} onBattle - if already on battle, not need to use the bounds mentioned above.
*/
KC3Ship.prototype.moraleEffectLevel = function(valuesArray = [0, 1, 2, 3, 4], onBattle = false){
return onBattle ? (
this.morale > 49 ? valuesArray[4] :
this.morale > 29 ? valuesArray[3] :
this.morale > 19 ? valuesArray[2] :
this.morale >= 0 ? valuesArray[1] :
valuesArray[0]
) : (
this.morale > 52 ? valuesArray[4] :
this.morale > 32 ? valuesArray[3] :
this.morale > 19 ? valuesArray[2] :
this.morale >= 0 ? valuesArray[1] :
valuesArray[0]);
};
KC3Ship.prototype.getDefer = function(){
// returns a new defer if possible
return deferList[this.rosterId] || [];
};
KC3Ship.prototype.checkDefer = function() {
// reset defer if it does not in normal state
var
self= this,
ca = this.getDefer(), // get defer array
cd = ca[0]; // current collection of deferred
if(ca && cd && cd.state() == "pending")
return ca;
//console.debug("replacing",this.rosterId,"cause",!cd ? typeof cd : cd.state());
ca = deferList[this.rosterId] = Array.apply(null,{length:2}).map(function(){return $.Deferred();});
cd = $.when.apply(null,ca);
ca.unshift(cd);
return ca;
};
/* DAMAGE STATUS
Get damage status of the ship, return one of the following string:
* "dummy" if this is a dummy ship
* "taiha" (HP <= 25%)
* "chuuha" (25% < HP <= 50%)
* "shouha" (50% < HP <= 75%)
* "normal" (75% < HP < 100%)
* "full" (100% HP)
--------------------------------------------------------------*/
KC3Ship.prototype.damageStatus = function() {
if (this.hp[1] > 0) {
if (this.hp[0] === this.hp[1]) {
return "full";
}
var hpPercent = this.hp[0] / this.hp[1];
if (hpPercent <= 0.25) {
return "taiha";
} else if (hpPercent <= 0.5) {
return "chuuha";
} else if (hpPercent <= 0.75) {
return "shouha";
} else {
return "normal";
}
} else {
return "dummy";
}
};
KC3Ship.prototype.isSupplied = function(){
if(this.isDummy()){ return true; }
return this.fuel >= this.master().api_fuel_max
&& this.ammo >= this.master().api_bull_max;
};
KC3Ship.prototype.isNeedSupply = function(isEmpty){
if(this.isDummy()){ return false; }
var
fpc = function(x,y){return Math.qckInt("round",(x / y) * 10);},
fuel = fpc(this.fuel,this.master().api_fuel_max),
ammo = fpc(this.ammo,this.master().api_bull_max);
return Math.min(fuel,ammo) <= (ConfigManager.alert_supply) * (!isEmpty);
};
KC3Ship.prototype.onFleet = function(){
var fleetNum = 0;
PlayerManager.fleets.find((fleet, index) => {
if(fleet.ships.some(rid => rid === this.rosterId)){
fleetNum = index + 1;
return true;
}
});
return fleetNum;
};
/**
* @return a tuple for [position in fleet (0-based), fleet total ship amount].
* return [-1, 0] if this ship is not on any fleet.
*/
KC3Ship.prototype.fleetPosition = function(){
var position = -1,
total = 0;
if(this.exists()) {
const fleetNum = this.onFleet();
if(fleetNum > 0) {
var fleet = PlayerManager.fleets[fleetNum - 1];
position = fleet.ships.indexOf(this.rosterId);
total = fleet.countShips();
}
}
return [position, total];
};
KC3Ship.prototype.isRepairing = function(){
return PlayerManager.repairShips.indexOf(this.rosterId) >= 0;
};
KC3Ship.prototype.isAway = function(){
return this.onFleet() > 1 /* ensures not in main fleet */
&& (KC3TimerManager.exped(this.onFleet()) || {active:false}).active; /* if there's a countdown on expedition, means away */
};
KC3Ship.prototype.isFree = function(){
return !(this.isRepairing() || this.isAway());
};
KC3Ship.prototype.resetAfterHp = function(){
this.afterHp[0] = this.hp[0];
this.afterHp[1] = this.hp[1];
};
KC3Ship.prototype.applyRepair = function(){
this.hp[0] = this.hp[1];
// also keep afterHp consistent
this.resetAfterHp();
this.morale = Math.max(40, this.morale);
this.repair.fill(0);
};
/**
* Return max HP of a ship. Static method for library.
* Especially after marriage, api_taik[1] is hard to reach in game.
* Since 2017-09-29, HP can be modernized, and known max value is within 2.
* @return false if ship ID belongs to abyssal or nonexistence
* @see http://wikiwiki.jp/kancolle/?%A5%B1%A5%C3%A5%B3%A5%F3%A5%AB%A5%C3%A5%B3%A5%AB%A5%EA
* @see https://github.com/andanteyk/ElectronicObserver/blob/develop/ElectronicObserver/Other/Information/kcmemo.md#%E3%82%B1%E3%83%83%E3%82%B3%E3%83%B3%E3%82%AB%E3%83%83%E3%82%B3%E3%82%AB%E3%83%AA%E5%BE%8C%E3%81%AE%E8%80%90%E4%B9%85%E5%80%A4
*/
KC3Ship.getMaxHp = function(masterId, currentLevel, isModernized){
var masterHpArr = KC3Master.isNotRegularShip(masterId) ? [] :
(KC3Master.ship(masterId) || {"api_taik":[]}).api_taik;
var masterHp = masterHpArr[0], maxLimitHp = masterHpArr[1];
var expected = ((currentLevel || KC3Ship.getMaxLevel())
< KC3Ship.getMarriedLevel() ? masterHp :
masterHp > 90 ? masterHp + 9 :
masterHp >= 70 ? masterHp + 8 :
masterHp >= 50 ? masterHp + 7 :
masterHp >= 40 ? masterHp + 6 :
masterHp >= 30 ? masterHp + 5 :
masterHp >= 8 ? masterHp + 4 :
masterHp + 3) || false;
if(isModernized) expected += KC3Ship.getMaxHpModernize();
return maxLimitHp && expected > maxLimitHp ? maxLimitHp : expected;
};
KC3Ship.prototype.maxHp = function(isModernized){
return KC3Ship.getMaxHp(this.masterId, this.level, isModernized);
};
// Since 2017-09-29, asw stat can be modernized, known max value is within 9.
KC3Ship.prototype.maxAswMod = function(){
// the condition `Core.swf/vo.UserShipData.hasTaisenAbility()` also used
var maxAswBeforeMarriage = this.as[1];
var maxModAsw = this.nakedAsw() + KC3Ship.getMaxAswModernize() - (this.mod[6] || 0);
return maxAswBeforeMarriage > 0 ? maxModAsw : 0;
};
/**
* Return total count of aircraft slots of a ship. Static method for library.
* @return -1 if ship ID belongs to abyssal or nonexistence
*/
KC3Ship.getCarrySlots = function(masterId){
var maxeq = KC3Master.isNotRegularShip(masterId) ? undefined :
(KC3Master.ship(masterId) || {}).api_maxeq;
return Array.isArray(maxeq) ? maxeq.sumValues() : -1;
};
KC3Ship.prototype.carrySlots = function(){
return KC3Ship.getCarrySlots(this.masterId);
};
/**
* @param isExslotIncluded - if equipment on ex-slot is counted, here true by default
* @return current equipped pieces of equipment
*/
KC3Ship.prototype.equipmentCount = function(isExslotIncluded = true){
let amount = (this.items.indexOf(-1) + 1 || (this.items.length + 1)) - 1;
// 0 means ex-slot not opened, -1 means opened but none equipped
amount += (isExslotIncluded && this.ex_item > 0) & 1;
return amount;
};
/**
* @param isExslotIncluded - if ex-slot is counted, here true by default
* @return amount of all equippable slots
*/
KC3Ship.prototype.equipmentMaxCount = function(isExslotIncluded = true){
return this.slotnum + ((isExslotIncluded && (this.ex_item === -1 || this.ex_item > 0)) & 1);
};
/**
* @param stypeValue - specific a ship type if not refer to this ship
* @return true if this (or specific) ship is a SS or SSV
*/
KC3Ship.prototype.isSubmarine = function(stypeValue){
if(this.isDummy()) return false;
const stype = stypeValue || this.master().api_stype;
return [13, 14].includes(stype);
};
/**
* @return true if this ship type is CVL, CV or CVB
*/
KC3Ship.prototype.isCarrier = function(){
if(this.isDummy()) return false;
const stype = this.master().api_stype;
return [7, 11, 18].includes(stype);
};
/**
* @return true if this ship is a CVE, which is Light Carrier and her initial ASW stat > 0
*/
KC3Ship.prototype.isEscortLightCarrier = function(){
if(this.isDummy()) return false;
const stype = this.master().api_stype;
// Known implementations: Taiyou series, Gambier Bay series, Zuihou K2B
const minAsw = (this.master().api_tais || [])[0];
return stype === 7 && minAsw > 0;
};
/* REPAIR TIME
Get ship's docking and Akashi times
when optAfterHp is true, return repair time based on afterHp
--------------------------------------------------------------*/
KC3Ship.prototype.repairTime = function(optAfterHp){
var
HPPercent = this.hp[0] / this.hp[1],
RepairTSec = Math.hrdInt('floor',this.repair[0],3,1),
RepairCalc = PS['KanColle.RepairTime'],
hpArr = optAfterHp ? this.afterHp : this.hp;
var result = { akashi: 0 };
if (HPPercent > 0.5 && HPPercent < 1.00 && this.isFree()) {
var repairTime = KC3AkashiRepair.calculateRepairTime(this.repair[0]);
result.akashi = Math.max(
Math.hrdInt('floor', repairTime,3,1), // convert to seconds
20 * 60 // should be at least 20 minutes
);
}
if (optAfterHp) {
result.docking = RepairCalc.dockingInSecJSNum( this.master().api_stype, this.level, hpArr[0], hpArr[1] );
} else {
result.docking = this.isRepairing() ?
Math.ceil(KC3TimerManager.repair(PlayerManager.repairShips.indexOf(this.rosterId)).remainingTime()) / 1000 :
/* RepairCalc. dockingInSecJSNum( this.master().api_stype, this.level, this.hp[0], this.hp[1] ) */
RepairTSec;
}
return result;
};
/* Calculate resupply cost
----------------------------------
0 <= fuelPercent <= 1, < 0 use current fuel
0 <= ammoPercent <= 1, < 0 use current ammo
to calculate bauxite cost: bauxiteNeeded == true
to calculate steel cost per battles: steelNeeded == true
costs of expeditions simulate rounding by adding roundUpFactor(0.4/0.5?) before flooring
returns an object: {fuel: <fuelCost>, ammo: <ammoCost>, steel: <steelCost>, bauxite: <bauxiteCost>}
*/
KC3Ship.prototype.calcResupplyCost = function(fuelPercent, ammoPercent, bauxiteNeeded, steelNeeded, roundUpFactor) {
var self = this;
var result = {
fuel: 0, ammo: 0
};
if(this.isDummy()) {
if(bauxiteNeeded) result.bauxite = 0;
if(steelNeeded) result.steel = 0;
return result;
}
var master = this.master();
var fullFuel = master.api_fuel_max;
var fullAmmo = master.api_bull_max;
var mulRounded = function (a, percent) {
return Math.floor( a * percent + (roundUpFactor || 0) );
};
var marriageConserve = function (v) {
return self.isMarried() ? Math.floor(0.85 * v) : v;
};
result.fuel = fuelPercent < 0 ? fullFuel - this.fuel : mulRounded(fullFuel, fuelPercent);
result.ammo = ammoPercent < 0 ? fullAmmo - this.ammo : mulRounded(fullAmmo, ammoPercent);
// After testing, 85% is applied to supply cost, not max value
result.fuel = marriageConserve(result.fuel);
result.ammo = marriageConserve(result.ammo);
if(bauxiteNeeded){
var slotsBauxiteCost = function(current, max) {
return current < max ? (max-current) * KC3GearManager.carrierSupplyBauxiteCostPerSlot : 0;
};
var shipBauxiteCost = function() {
return slotsBauxiteCost(self.slots[0], master.api_maxeq[0])
+ slotsBauxiteCost(self.slots[1], master.api_maxeq[1])
+ slotsBauxiteCost(self.slots[2], master.api_maxeq[2])
+ slotsBauxiteCost(self.slots[3], master.api_maxeq[3]);
};
result.bauxite = shipBauxiteCost();
// Bauxite cost to fill slots not affected by marriage.
// via http://kancolle.wikia.com/wiki/Marriage
//result.bauxite = marriageConserve(result.bauxite);
}
if(steelNeeded){
result.steel = this.calcJetsSteelCost();
}
return result;
};
/**
* Calculate steel cost of jet aircraft for 1 battle based on current slot size.
* returns total steel cost for this ship at this time
*/
KC3Ship.prototype.calcJetsSteelCost = function(currentSortieId) {
var totalSteel = 0, consumedSteel = 0;
if(this.isDummy()) { return totalSteel; }
this.equipment().forEach((item, i) => {
// Is Jet aircraft and left slot > 0
if(item.exists() && this.slots[i] > 0 &&
KC3GearManager.jetAircraftType2Ids.includes(item.master().api_type[2])) {
consumedSteel = Math.round(
this.slots[i]
* item.master().api_cost
* KC3GearManager.jetBomberSteelCostRatioPerSlot
) || 0;
totalSteel += consumedSteel;
if(!!currentSortieId) {
let pc = this.pendingConsumption[currentSortieId];
if(!Array.isArray(pc)) {
pc = [[0,0,0],[0,0,0],[0]];
this.pendingConsumption[currentSortieId] = pc;
}
if(!Array.isArray(pc[2])) {
pc[2] = [0];
}
pc[2][0] -= consumedSteel;
}
}
});
if(!!currentSortieId && totalSteel > 0) {
KC3ShipManager.save();
}
return totalSteel;
};
/**
* Naked stats of this ship.
* @return stats without the equipment but with modernization.
*/
KC3Ship.prototype.nakedStats = function(statAttr){
if(this.isDummy()) { return false; }
const stats = {
aa: this.aa[0],
ar: this.ar[0],
as: this.as[0],
ev: this.ev[0],
fp: this.fp[0],
// Naked HP maybe mean HP before marriage
hp: (this.master().api_taik || [])[0] || this.hp[1],
lk: (this.master().api_luck || [])[0] || this.lk[0],
ls: this.ls[0],
tp: this.tp[0],
// Accuracy not shown in-game, so naked value might be plus-minus 0
ac: 0
};
const statApiNames = {
"tyku": "aa",
"souk": "ar",
"tais": "as",
"houk": "ev",
"houg": "fp",
"saku": "ls",
"raig": "tp",
"houm": "ac"
};
for(const apiName in statApiNames) {
const equipStats = this.equipmentTotalStats(apiName);
stats[statApiNames[apiName]] -= equipStats;
}
return !statAttr ? stats : stats[statAttr];
};
KC3Ship.prototype.equipmentStatsMap = function(apiName, isExslotIncluded = true){
return this.equipment(isExslotIncluded).map(equip => {
if(equip.exists()) {
return equip.master()["api_" + apiName];
}
return undefined;
});
};
KC3Ship.prototype.equipmentTotalStats = function(apiName, isExslotIncluded = true){
var total = 0;
var hasSurfaceRadar = false;
const thisShipClass = this.master().api_ctype;
// Explicit stats bonuses from equipment on specific ship are added to API result by server-side,
// To correct the 'naked stats' for these cases, have to simulate them all.
// A summary table: https://twitter.com/Lambda39/status/990268289866579968
// In order to handle some complex cases,
// this definition table includes some functions which can not be moved to JSON file.
const explicitStatsBonusGears = {
// 61cm Quadruple (Oxygen) Torpedo Mount
"15": {
count: 0,
byShip: {
// Kagerou K2
ids: [566],
multiple: { "raig": 2 },
countCap: 2,
},
},
// 61cm Triple (Oxygen) Torpedo Mount Late Model
// https://wikiwiki.jp/kancolle/61cm%E4%B8%89%E9%80%A3%E8%A3%85%28%E9%85%B8%E7%B4%A0%29%E9%AD%9A%E9%9B%B7%E5%BE%8C%E6%9C%9F%E5%9E%8B
"285": {
count: 0,
byShip: {
// Here goes ship ID white-list:
// Fubuki K2, Murakumo K2,
// Ayanami K2, Ushio K2
// Akatsuki K2, Bep (Hibiki K2)
// Hatsuharu K2, Hatsushimo K2
ids: [426, 420, 195, 407, 437, 147, 326, 419],
multiple: { "raig": 2, "houk": 1 },
},
},
// 61cm Quadruple (Oxygen) Torpedo Mount Late Model
// https://wikiwiki.jp/kancolle/61cm%E5%9B%9B%E9%80%A3%E8%A3%85%28%E9%85%B8%E7%B4%A0%29%E9%AD%9A%E9%9B%B7%E5%BE%8C%E6%9C%9F%E5%9E%8B
"286": {
count: 0,
byClass: {
// Asashio Class, Kai Nis
"18": {
remodel: 2,
multiple: { "raig": 2, "houk": 1 },
},
// Shiratsuyu Class, Kai Nis
"23": {
remodel: 2,
multiple: { "raig": 2, "houk": 1 },
},
// Kagerou Class, Kai Nis
// Kagerou K2 only if except Isokaze / Hamakaze B Kai, Urakaze D Kai
"30": {
remodel: 2,
excludes: [556, 557, 558],
multiple: { "raig": 2, "houk": 1 },
},
// Yuugumo Class, Kai Nis
// Naganami K2 only
"38": {
remodel: 2,
multiple: { "raig": 2, "houk": 1 },
},
},
},
// 12.7cm Twin Gun Mount Model C Kai Ni
"266": {
count: 0,
byShip: {
// Kagerou K2
ids: [566],
multiple: { "houg": 1 },
countCap: 2,
callback: (api, info) => (
// total +3 instead of +2 if guns >= 2
// https://wikiwiki.jp/kancolle/%E9%99%BD%E7%82%8E%E6%94%B9%E4%BA%8C
({"houg": info.count >= 2 ? 1 : 0})[api] || 0
),
},
},
// 12.7cm Twin Gun Mount Model D Kai Ni
// http://wikiwiki.jp/kancolle/?12.7cm%CF%A2%C1%F5%CB%A4D%B7%BF%B2%FE%C6%F3
"267": {
count: 0,
byClass: {
// Shimakaze Class
"22": {
multiple: { "houg": 2, "houk": 1 },
},
// Kagerou Class
"30": {
multiple: { "houg": 1, "houk": 1 },
},
// Yuugumo Class
"38": {
multiple: { "houg": 2, "houk": 1 },
},
},
byShip: [
{
// Naganami K2, total +3 for each gun
ids: [543],
multiple: { "houg": 1 },
},
{
// Kagerou K2, total +2 for 1st gun
ids: [566],
single: { "houg": 1 },
},
],
synergyCallback: (api, info) => (
// Synergy with Surface Radar for Naganami Kai Ni and Shimakaze Kai
hasSurfaceRadar && [543, 229].includes(this.masterId) ? ({
"houg": 1, "raig": 3, "houk": 2
})[api] || 0 : 0
),
},
// Arctic Camouflage
// http://wikiwiki.jp/kancolle/?%CB%CC%CA%FD%CC%C2%BA%CC%28%A1%DC%CB%CC%CA%FD%C1%F5%C8%F7%29
"268": {
count: 0,
byShip: {
// Tama K / K2, Kiso K / K2
ids: [146, 216, 217, 547],
single: { "souk": 2, "houk": 7 },
},
},
};
// Accumulates displayed stats from equipment, and count for special equipment
this.equipment(isExslotIncluded).forEach(equip => {
if(equip.exists()) {
total += (equip.master()["api_" + apiName] || 0);
const bonusDefs = explicitStatsBonusGears[equip.masterId];
if(bonusDefs && bonusDefs.count >= 0) bonusDefs.count += 1;
if(!hasSurfaceRadar && equip.isHighAccuracyRadar()) hasSurfaceRadar = true;
}
});
// Add explicit stats bonuses (not masked, displayed on ship) from equipment on specific ship
const addBonusToTotalIfNecessary = (bonusDef, apiName, gearInfo) => {
if(Array.isArray(bonusDef.ids) && !bonusDef.ids.includes(this.masterId)) { return; }
if(Array.isArray(bonusDef.exlucdes) && bonusDef.exlucdes.includes(this.masterId)) { return; }
if(Array.isArray(bonusDef.classes) && !bonusDef.classes.includes(thisShipClass)) { return; }
if(bonusDef.remodel &&
RemodelDb.remodelGroup(this.masterId).indexOf(this.masterId) < bonusDef.remodel) { return; }
if(bonusDef.single) { total += bonusDef.single[apiName] || 0; }
if(bonusDef.multiple) {
total += (bonusDef.multiple[apiName] || 0) *
(bonusDef.countCap ? Math.min(bonusDef.countCap, gearInfo.count) : gearInfo.count);
}
if(bonusDef.callback) { total += bonusDef.callback(apiName, gearInfo); }
};
Object.keys(explicitStatsBonusGears).forEach(gearId => {
const gearInfo = explicitStatsBonusGears[gearId];
if(gearInfo.count > 0) {
if(gearInfo.byClass) {
const byClass = gearInfo.byClass[thisShipClass];
if(byClass) addBonusToTotalIfNecessary(byClass, apiName, gearInfo);
}
if(gearInfo.byShip) {
const byShip = gearInfo.byShip;
if(Array.isArray(byShip)) {
byShip.forEach(s => addBonusToTotalIfNecessary(s, apiName, gearInfo));
} else {
addBonusToTotalIfNecessary(byShip, apiName, gearInfo);
}
}
if(gearInfo.synergyCallback) {
total += gearInfo.synergyCallback(apiName, gearInfo);
}
}
});
return total;
};
// faster naked asw stat method since frequently used
KC3Ship.prototype.nakedAsw = function(){
var asw = this.as[0];
var equipAsw = this.equipmentTotalStats("tais");
return asw - equipAsw;
};
KC3Ship.prototype.nakedLoS = function(){
var los = this.ls[0];
var equipLos = this.equipmentTotalLoS();
return los - equipLos;
};
KC3Ship.prototype.equipmentTotalLoS = function (){
return this.equipmentTotalStats("saku");
};
KC3Ship.prototype.effectiveEquipmentTotalAsw = function(canAirAttack = false){
// When calculating asw relevant thing,
// asw stat from these known types of equipment not taken into account:
// main gun, recon seaplane, seaplane fighter, radar, large flying boat, LBAA
const noCountEquipType2Ids = [1, 2, 3, 10, 12, 13, 41, 45, 47, 57];
// exclude bomber, seaplane bomber, autogyro, as-pby too if not able to air attack
if(!canAirAttack) {
noCountEquipType2Ids.push(...[7, 8, 11, 25, 26]);
}
const equipmentTotalAsw = this.equipment(true)
.map(g => g.exists() && g.master().api_tais > 0 &&
!noCountEquipType2Ids.includes(g.master().api_type[2]) ? g.master().api_tais : 0
).sumValues();
return equipmentTotalAsw;
};
// estimated LoS without equipments based on WhoCallsTheFleetDb
KC3Ship.prototype.estimateNakedLoS = function() {
var losInfo = WhoCallsTheFleetDb.getLoSInfo( this.masterId );
var retVal = WhoCallsTheFleetDb.estimateStat(losInfo, this.level);
return retVal === false ? 0 : retVal;
};
KC3Ship.prototype.estimateNakedAsw = function() {
var aswInfo = WhoCallsTheFleetDb.getStatBound(this.masterId, "asw");
var retVal = WhoCallsTheFleetDb.estimateStat(aswInfo, this.level);
return retVal === false ? 0 : retVal;
};
KC3Ship.prototype.estimateNakedEvasion = function() {
var evaInfo = WhoCallsTheFleetDb.getStatBound(this.masterId, "evasion");
var retVal = WhoCallsTheFleetDb.estimateStat(evaInfo, this.level);
return retVal === false ? 0 : retVal;
};
KC3Ship.prototype.equipmentTotalImprovementBonus = function(attackType){
return this.equipment(true)
.map(gear => gear.attackPowerImprovementBonus(attackType))
.sumValues();
};
/**
* Maxed stats of this ship.
* @return stats without the equipment but with modernization at Lv.99,
* stats at Lv.165 can be only estimated by data from known database.
*/
KC3Ship.prototype.maxedStats = function(statAttr, isMarried = this.isMarried()){
if(this.isDummy()) { return false; }
const stats = {
aa: this.aa[1],
ar: this.ar[1],
as: this.as[1],
ev: this.ev[1],
fp: this.fp[1],
hp: this.hp[1],
// Maxed Luck includes full modernized + marriage bonus
lk: this.lk[1],
ls: this.ls[1],
tp: this.tp[1]
};
if(isMarried){
stats.hp = KC3Ship.getMaxHp(this.masterId);
const asBound = WhoCallsTheFleetDb.getStatBound(this.masterId, "asw");
const asw = WhoCallsTheFleetDb.estimateStat(asBound, KC3Ship.getMaxLevel());
if(asw !== false) { stats.as = asw; }
const lsBound = WhoCallsTheFleetDb.getStatBound(this.masterId, "los");
const los = WhoCallsTheFleetDb.estimateStat(lsBound, KC3Ship.getMaxLevel());
if(los !== false) { stats.ls = los; }
const evBound = WhoCallsTheFleetDb.getStatBound(this.masterId, "evasion");
const evs = WhoCallsTheFleetDb.estimateStat(evBound, KC3Ship.getMaxLevel());
if(evs !== false) { stats.ev = evs; }
}
// Unlike stats fp, tp, ar and aa,
// increase final maxed asw since modernized asw is not included in both as[1] and db
if(this.mod[6] > 0) { stats.as += this.mod[6]; }
return !statAttr ? stats : stats[statAttr];
};
/**
* Left modernize-able stats of this ship.
* @return stats to be maxed modernization
*/
KC3Ship.prototype.modernizeLeftStats = function(statAttr){
if(this.isDummy()) { return false; }
const shipMst = this.master();
const stats = {
fp: shipMst.api_houg[1] - shipMst.api_houg[0] - this.mod[0],
tp: shipMst.api_raig[1] - shipMst.api_raig[0] - this.mod[1],
aa: shipMst.api_tyku[1] - shipMst.api_tyku[0] - this.mod[2],
ar: shipMst.api_souk[1] - shipMst.api_souk[0] - this.mod[3],
lk: this.lk[1] - this.lk[0],
// or: shipMst.api_luck[1] - shipMst.api_luck[0] - this.mod[4],
// current stat (hp[1], as[0]) already includes the modded stat
hp: this.maxHp(true) - this.hp[1],
as: this.maxAswMod() - this.nakedAsw()
};
return !statAttr ? stats : stats[statAttr];
};
/**
* Get number of equipments of specific masterId(s).
* @param masterId - slotitem master ID to be matched, can be an Array.
* @return count of specific equipment.
*/
KC3Ship.prototype.countEquipment = function(masterId, isExslotIncluded = true) {
return this.findEquipmentById(masterId, isExslotIncluded)
.reduce((acc, v) => acc + (!!v & 1), 0);
};
/**
* Get number of equipments of specific type(s).
* @param typeIndex - the index of `slotitem.api_type[]`, see `equiptype.json` for more.
* @param typeValue - the expected type value(s) to be matched, can be an Array.
* @return count of specific type(s) of equipment.
*/
KC3Ship.prototype.countEquipmentType = function(typeIndex, typeValue, isExslotIncluded = true) {
return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded)
.reduce((acc, v) => acc + (!!v & 1), 0);
};
/**
* Get number of some equipment (aircraft usually) equipped on non-0 slot.
*/
KC3Ship.prototype.countNonZeroSlotEquipment = function(masterId, isExslotIncluded = false) {
return this.findEquipmentById(masterId, isExslotIncluded)
.reduce((acc, v, i) => acc + ((!!v && this.slots[i] > 0) & 1), 0);
};
/**
* Get number of some specific types of equipment (aircraft usually) equipped on non-0 slot.
*/
KC3Ship.prototype.countNonZeroSlotEquipmentType = function(typeIndex, typeValue, isExslotIncluded = false) {
return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded)
.reduce((acc, v, i) => acc + ((!!v && this.slots[i] > 0) & 1), 0);
};
/**
* Get number of drums held by this ship.
*/
KC3Ship.prototype.countDrums = function(){
return this.countEquipment( 75 );
};
/**
* Indicate if some specific equipment equipped.
*/
KC3Ship.prototype.hasEquipment = function(masterId, isExslotIncluded = true) {
return this.findEquipmentById(masterId, isExslotIncluded).some(v => !!v);
};
/**
* Indicate if some specific types of equipment equipped.
*/
KC3Ship.prototype.hasEquipmentType = function(typeIndex, typeValue, isExslotIncluded = true) {
return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded).some(v => !!v);
};
/**
* Indicate if some specific equipment (aircraft usually) equipped on non-0 slot.
*/
KC3Ship.prototype.hasNonZeroSlotEquipment = function(masterId, isExslotIncluded = false) {
return this.findEquipmentById(masterId, isExslotIncluded)
.some((v, i) => !!v && this.slots[i] > 0);
};
/**
* Indicate if some specific types of equipment (aircraft usually) equipped on non-0 slot.
*/
KC3Ship.prototype.hasNonZeroSlotEquipmentType = function(typeIndex, typeValue, isExslotIncluded = false) {
return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded)
.some((v, i) => !!v && this.slots[i] > 0);
};
/**
* Indicate if only specific equipment equipped (empty slot not counted).
*/
KC3Ship.prototype.onlyHasEquipment = function(masterId, isExslotIncluded = true) {
const equipmentCount = this.equipmentCount(isExslotIncluded);
return equipmentCount > 0 &&
equipmentCount === this.countEquipment(masterId, isExslotIncluded);
};
/**
* Indicate if only specific types of equipment equipped (empty slot not counted).
*/
KC3Ship.prototype.onlyHasEquipmentType = function(typeIndex, typeValue, isExslotIncluded = true) {
const equipmentCount = this.equipmentCount(isExslotIncluded);
return equipmentCount > 0 &&
equipmentCount === this.countEquipmentType(typeIndex, typeValue, isExslotIncluded);
};
/**
* Simple method to find equipment by Master ID from current ship's equipment.
* @return the mapped Array to indicate equipment found or not at corresponding position,
* max 6-elements including ex-slot.
*/
KC3Ship.prototype.findEquipmentById = function(masterId, isExslotIncluded = true) {
return this.equipment(isExslotIncluded).map(gear =>
Array.isArray(masterId) ? masterId.includes(gear.masterId) :
masterId === gear.masterId
);
};
/**
* Simple method to find equipment by Type ID from current ship's equipment.
* @return the mapped Array to indicate equipment found or not at corresponding position,
* max 6-elements including ex-slot.
*/
KC3Ship.prototype.findEquipmentByType = function(typeIndex, typeValue, isExslotIncluded = true) {
return this.equipment(isExslotIncluded).map(gear =>
gear.exists() && (
Array.isArray(typeValue) ? typeValue.includes(gear.master().api_type[typeIndex]) :
typeValue === gear.master().api_type[typeIndex]
)
);
};
/* FIND DAMECON
Find first available damecon.
search order: extra slot -> 1st slot -> 2ns slot -> 3rd slot -> 4th slot -> 5th slot
return: {pos: <pos>, code: <code>}
pos: 1-5 for normal slots, 0 for extra slot, -1 if not found.
code: 0 if not found, 1 for repair team, 2 for goddess
----------------------------------------- */
KC3Ship.prototype.findDameCon = function() {
const allItems = [ {pos: 0, item: this.exItem() } ];
allItems.push(...this.equipment(false).map((g, i) => ({pos: i + 1, item: g}) ));
const damecon = allItems.filter(x => (
// 42: repair team
// 43: repair goddess
x.item.masterId === 42 || x.item.masterId === 43
)).map(x => (
{pos: x.pos,
code: x.item.masterId === 42 ? 1
: x.item.masterId === 43 ? 2
: 0}
));
return damecon.length > 0 ? damecon[0] : {pos: -1, code: 0};
};
/* CALCULATE TRANSPORT POINT
Retrieve TP object related to the current ship
** TP Object Detail --
value: known value that were calculated for
clear: is the value already clear or not? it's a NaN like.
**
--------------------------------------------------------------*/
KC3Ship.prototype.obtainTP = function() {
var tp = KC3Meta.tpObtained();
if (this.isDummy()) { return tp; }
if (!(this.isAbsent() || this.isTaiha())) {
var tp1,tp2,tp3;
tp1 = String(tp.add(KC3Meta.tpObtained({stype:this.master().api_stype})));
tp2 = String(tp.add(KC3Meta.tpObtained({slots:this.equipment().map(function(slot){return slot.masterId;})})));
tp3 = String(tp.add(KC3Meta.tpObtained({slots:[this.exItem().masterId]})));
// Special case of Kinu Kai 2: Daihatsu embedded :)
if (this.masterId == 487) {
tp.add(KC3Meta.tpObtained({slots:[68]}));
}
}
return tp;
};
/* FIGHTER POWER
Get fighter power of this ship
--------------------------------------------------------------*/
KC3Ship.prototype.fighterPower = function(){
if(this.isDummy()){ return 0; }
return this.equipment().map((g, i) => g.fighterPower(this.slots[i])).sumValues();
};
/* FIGHTER POWER with WHOLE NUMBER BONUS
Get fighter power of this ship as an array
with consideration to whole number proficiency bonus
--------------------------------------------------------------*/
KC3Ship.prototype.fighterVeteran = function(){
if(this.isDummy()){ return 0; }
return this.equipment().map((g, i) => g.fighterVeteran(this.slots[i])).sumValues();
};
/* FIGHTER POWER with LOWER AND UPPER BOUNDS
Get fighter power of this ship as an array
with consideration to min-max bonus
--------------------------------------------------------------*/
KC3Ship.prototype.fighterBounds = function(forLbas = false){
if(this.isDummy()){ return [0, 0]; }
const powerBounds = this.equipment().map((g, i) => g.fighterBounds(this.slots[i], forLbas));
return [
powerBounds.map(b => b[0]).sumValues(),
powerBounds.map(b => b[1]).sumValues()
];
};
/* FIGHTER POWER on Air Defense with INTERCEPTOR FORMULA
Recon plane gives a modifier to total interception power
--------------------------------------------------------------*/
KC3Ship.prototype.interceptionPower = function(){
if(this.isDummy()){ return 0; }
var reconModifier = 1;
this.equipment(function(id, idx, gear){
if(id === 0){ return; }
var type2 = gear.master().api_type[2];
var los = gear.master().api_saku;
if(KC3GearManager.landBaseReconnType2Ids.includes(type2)){
// Carrier Recon Aircraft
if(type2 == 9){
reconModifier =
(los <= 7) ? 1.2 :
(los >= 9) ? 1.3 :
1; // they say los = 8 not exists
// Recon Seaplane, Flying Boat, etc
} else {
reconModifier =
(los <= 7) ? 1.1 :
(los >= 9) ? 1.16 :
1.13;
}
}
});
var interceptionPower = this.equipment()
.map((g, i) => g.interceptionPower(this.slots[i]))
.sumValues();
return Math.floor(interceptionPower * reconModifier);
};
/* SUPPORT POWER
* Get support expedition shelling power of this ship
* http://kancolle.wikia.com/wiki/Expedition/Support_Expedition
* http://wikiwiki.jp/kancolle/?%BB%D9%B1%E7%B4%CF%C2%E2
--------------------------------------------------------------*/
KC3Ship.prototype.supportPower = function(){
if(this.isDummy()){ return 0; }
const fixedFP = this.nakedStats("fp") - 1;
var supportPower = 0;
// for carrier series: CV, CVL, CVB
if(this.isCarrier()){
supportPower = fixedFP;
supportPower += this.equipmentTotalStats("raig");
supportPower += Math.floor(1.3 * this.equipmentTotalStats("baku"));
// will not attack if no dive/torpedo bomber equipped
if(supportPower === fixedFP){
supportPower = 0;
} else {
supportPower = Math.floor(1.5 * supportPower);
supportPower += 55;
}
} else {
supportPower = 5 + fixedFP + this.equipmentTotalStats("houg");
}
return supportPower;
};
/**
* Get basic pre-cap shelling fire power of this ship (without pre-cap / post-cap modifiers).
*
* @param {number} combinedFleetFactor - additional power if ship is on a combined fleet.
* @return {number} computed fire power, return 0 if unavailable.
* @see http://kancolle.wikia.com/wiki/Damage_Calculation
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#ua92169d
*/
KC3Ship.prototype.shellingFirePower = function(combinedFleetFactor = 0){
if(this.isDummy()) { return 0; }
let isCarrierShelling = this.isCarrier();
if(!isCarrierShelling) {
// Hayasui Kai gets special when any Torpedo Bomber equipped
isCarrierShelling = this.masterId === 352 && this.hasEquipmentType(2, 8);
}
let shellingPower = this.fp[0];
if(isCarrierShelling) {
shellingPower += this.equipmentTotalStats("raig");
shellingPower += Math.floor(1.3 * this.equipmentTotalStats("baku"));
shellingPower += combinedFleetFactor;
shellingPower += this.equipmentTotalImprovementBonus("airattack");
shellingPower = Math.floor(1.5 * shellingPower);
shellingPower += 50;
} else {
shellingPower += combinedFleetFactor;
shellingPower += this.equipmentTotalImprovementBonus("fire");
}
// 5 is attack power constant also used everywhere
shellingPower += 5;
return shellingPower;
};
/**
* Get pre-cap torpedo power of this ship.
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#n377a90c
*/
KC3Ship.prototype.shellingTorpedoPower = function(combinedFleetFactor = 0){
if(this.isDummy()) { return 0; }
return 5 + this.tp[0] + combinedFleetFactor +
this.equipmentTotalImprovementBonus("torpedo");
};
/**
* Get pre-cap anti-sub power of this ship.
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#AntiSubmarine
*/
KC3Ship.prototype.antiSubWarfarePower = function(aswDiff = 0){
if(this.isDummy()) { return 0; }
const isSonarEquipped = this.hasEquipmentType(1, 10);
const isDepthChargeProjectorEquipped = this.equipment(true).some(g => g.isDepthChargeProjector());
const isNewDepthChargeEquipped = this.equipment(true).some(g => g.isDepthCharge());
let synergyModifier = 1;
synergyModifier += isSonarEquipped && isNewDepthChargeEquipped ? 0.15 : 0;
synergyModifier += isDepthChargeProjectorEquipped && isNewDepthChargeEquipped ? 0.1 : 0;
synergyModifier *= isSonarEquipped && isDepthChargeProjectorEquipped ? 1.15 : 1;
// check asw attack type, 1530 is Abyssal Submarine Ka-Class
const isAirAttack = this.estimateDayAttackType(1530, false)[0] === "AirAttack";
const attackMethodConst = isAirAttack ? 8 : 13;
const nakedAsw = this.nakedAsw() + aswDiff;
// only asw stat from partial types of equipment taken into account
const equipmentTotalAsw = this.effectiveEquipmentTotalAsw(isAirAttack);
let aswPower = attackMethodConst;
aswPower += 2 * Math.sqrt(nakedAsw);
aswPower += 1.5 * equipmentTotalAsw;
aswPower += this.equipmentTotalImprovementBonus("asw");
// should move synergy modifier to pre-cap?
aswPower *= synergyModifier;
return aswPower;
};
/**
* Get pre-cap anti land installation power of this ship.
* @see http://kancolle.wikia.com/wiki/Installation_Type
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#antiground
* @see estimateLandingAttackType
*/
KC3Ship.prototype.antiLandWarfarePower = function(){
// TODO
};
/**
* Get post-cap airstrike power tuple of this ship.
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#b8c008fa
* @see KC3Gear.prototype.airstrikePower
*/
KC3Ship.prototype.airstrikePower = function(combinedFleetFactor = 0,
isJetAssaultPhase = false, contactPlaneId = 0, isCritical = false){
const totalPower = [0, 0, false];
if(this.isDummy()) { return totalPower; }
// no ex-slot by default since no plane can be equipped on ex-slot for now
this.equipment().forEach((gear, i) => {
if(this.slots[i] > 0 && gear.isAirstrikeAircraft()) {
const power = gear.airstrikePower(this.slots[i], combinedFleetFactor, isJetAssaultPhase);
const isRange = !!power[2];
const capped = [
this.applyPowerCap(power[0], "Day", "Aerial").power,
isRange ? this.applyPowerCap(power[1], "Day", "Aerial").power : 0
];
const postCapped = [
Math.floor(this.applyPostcapModifiers(capped[0], "Aerial", undefined, contactPlaneId, isCritical).power),
isRange ? Math.floor(this.applyPostcapModifiers(capped[1], "Aerial", undefined, contactPlaneId, isCritical).power) : 0
];
totalPower[0] += postCapped[0];
totalPower[1] += isRange ? postCapped[1] : postCapped[0];
totalPower[2] = totalPower[2] || isRange;
}
});
return totalPower;
};
/**
* Get pre-cap night battle power of this ship.
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#b717e35a
*/
KC3Ship.prototype.nightBattlePower = function(isNightContacted = false){
if(this.isDummy()) { return 0; }
return (isNightContacted ? 5 : 0) + this.fp[0] + this.tp[0]
+ this.equipmentTotalImprovementBonus("yasen");
};
/**
* Get pre-cap carrier night aerial attack power of this ship.
* @see http://kancolle.wikia.com/wiki/Damage_Calculation
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#nightAS
*/
KC3Ship.prototype.nightAirAttackPower = function(isNightContacted = false){
if(this.isDummy()) { return 0; }
const equipTotals = {
fp: 0, tp: 0, slotBonus: 0, improveBonus: 0
};
// Ark Royal (Kai) + Swordfish - NOAP, might use normal formula, but
// in fact, this formula is the same thing besides slot bonus part.
const isThisArkRoyal = [515, 393].includes(this.masterId);
const noNightAvPersonnel = !this.hasEquipment([258, 259]);
this.equipment().forEach((gear, idx) => {
if(gear.exists()) {
const master = gear.master();
const slot = this.slots[idx];
const isNightAircraftType = KC3GearManager.nightAircraftType3Ids.includes(master.api_type[3]);
const isSwordfish = [242, 243, 244].includes(gear.masterId);
// Type 62 Fighter Bomber Iwai for now
const isSpecialNightPlane = [154].includes(gear.masterId);
const isLegacyArkRoyal = isThisArkRoyal && noNightAvPersonnel;
const isNightPlane = isLegacyArkRoyal ? isSwordfish :
isNightAircraftType || isSwordfish || isSpecialNightPlane;
if(isNightPlane && slot > 0) {
// assume all master stats hold value 0 by default
equipTotals.fp += master.api_houg;
equipTotals.tp += master.api_raig;
if(!isLegacyArkRoyal) {
equipTotals.slotBonus += slot * (isNightAircraftType ? 3 : 0);
const ftbaPower = master.api_houg + master.api_raig + master.api_baku + master.api_tais;
equipTotals.slotBonus += Math.sqrt(slot) * ftbaPower * (isNightAircraftType ? 0.45 : 0.3);
}
equipTotals.improveBonus += gear.attackPowerImprovementBonus("yasen");
}
}
});
let shellingPower = this.nakedStats("fp");
shellingPower += equipTotals.fp + equipTotals.tp;
shellingPower += equipTotals.slotBonus;
shellingPower += equipTotals.improveBonus;
shellingPower += isNightContacted ? 5 : 0;
return shellingPower;
};
/**
* Apply known pre-cap modifiers to attack power.
* @return {Object} capped power and applied modifiers.
* @see http://kancolle.wikia.com/wiki/Damage_Calculation
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#beforecap
* @see https://twitter.com/Nishisonic/status/893030749913227264
*/
KC3Ship.prototype.applyPrecapModifiers = function(basicPower, warfareType = "Shelling",
engagementId = 1, formationId = ConfigManager.aaFormation,
nightSpecialAttackType = [], isNightStart = false, isCombined = false){
// Engagement modifier
let engagementModifier = (warfareType === "Aerial" ? [] : [0, 1, 0.8, 1.2, 0.6])[engagementId] || 1;
// Formation modifier
let formationModifier = (warfareType === "Antisub" ?
// ID 1~5: Line Ahead / Double Line / Diamond / Echelon / Line Abreast
// ID 6: new Vanguard formation since 2017-11-17
// ID 11~14: 1st anti-sub / 2nd forward / 3rd diamond / 4th battle
// 0 are placeholders for non-exists ID
[0, 0.6, 0.8, 1.2, 1, 1.3, 1, 0, 0, 0, 0, 1.3, 1.1, 1, 0.7] :
warfareType === "Shelling" || warfareType === "Torpedo" ?
[0, 1, 0.8, 0.7, 0.6, 0.6, 1, 0, 0, 0, 0, 0.8, 1, 0.7, 1.1] :
// Aerial Opening Airstrike not affected
[]
)[formationId] || 1;
// Modifier of vanguard formation depends on the position in the fleet
if(formationId === 6) {
const [shipPos, shipCnt] = this.fleetPosition();
// Vanguard formation needs 4 ships at least, fake ID make no sense
if(shipCnt >= 4) {
// Guardian ships counted from 3rd or 4th ship
const isGuardian = shipPos >= Math.floor(shipCnt / 2);
if(warfareType === "Shelling") {
formationModifier = isGuardian ? 1 : 0.5;
} else if(warfareType === "Antisub") {
formationModifier = isGuardian ? 0.6 : 1;
}
}
}
// Non-empty attack type tuple means this supposed to be night battle
const isNightBattle = nightSpecialAttackType.length > 0;
const canNightAntisub = warfareType === "Antisub" && (isNightStart || isCombined);
// No engagement and formation modifier except night starts / combined ASW attack
if(isNightBattle && !canNightAntisub) {
engagementModifier = 1;
formationModifier = 1;
}
// Damage percent modifier
// http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#m8aa1749
const damageModifier = (warfareType === "Torpedo" ? {
// Day time only affect Opening Torpedo in fact, Chuuha cannot Closing at all
// Night time unmentioned, assume Chuuha 0.8 too?
"chuuha": 0.8,
"taiha": 0.0
} : warfareType === "Shelling" || warfareType === "Antisub" ? {
"chuuha": 0.7,
"taiha": 0.4
} : // Aerial Opening Airstrike not affected
{})[this.damageStatus()] || 1;
// Night special attack modifier, should not x2 although some types attack 2 times
const nightCutinModifier = nightSpecialAttackType[0] === "Cutin" &&
nightSpecialAttackType[3] > 0 ? nightSpecialAttackType[3] : 1;
// Apply modifiers, flooring unknown
let result = basicPower * engagementModifier * formationModifier * damageModifier * nightCutinModifier;
// Light Cruiser fit gun bonus, should not applied before modifiers
const stype = this.master().api_stype;
const ctype = this.master().api_ctype;
const isThisLightCruiser = [2, 3, 21].includes(stype);
let lightCruiserBonus = 0;
if(isThisLightCruiser) {
// 14cm, 15.2cm
const singleMountCnt = this.countEquipment([4, 11]);
const twinMountCnt = this.countEquipment([65, 119, 139]);
lightCruiserBonus = Math.sqrt(singleMountCnt) + 2 * Math.sqrt(twinMountCnt);
result += lightCruiserBonus;
}
// Italian Heavy Cruiser (Zara class) fit gun bonus
const isThisZaraClass = ctype === 64;
let italianHeavyCruiserBonus = 0;
if(isThisZaraClass) {
// 203mm/53
const itaTwinMountCnt = this.countEquipment(162);
italianHeavyCruiserBonus = Math.sqrt(itaTwinMountCnt);
result += italianHeavyCruiserBonus;
}
// Night battle anti-sub regular battle condition forced to no damage
const aswLimitation = isNightBattle && warfareType === "Antisub" && !canNightAntisub ? 0 : 1;
result *= aswLimitation;
return {
power: result,
engagementModifier,
formationModifier,
damageModifier,
nightCutinModifier,
lightCruiserBonus,
italianHeavyCruiserBonus,
aswLimitation
};
};
/**
* Apply cap to attack power according warfare phase.
* @param {number} precapPower - pre-cap power, see applyPrecapModifiers
* @return {Object} capped power, cap value and is capped flag.
* @see http://kancolle.wikia.com/wiki/Damage_Calculation
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#k5f74647
*/
KC3Ship.prototype.applyPowerCap = function(precapPower,
time = "Day", warfareType = "Shelling"){
const cap = time === "Night" ? 300 :
// increased from 150 to 180 since 2017-03-18
warfareType === "Shelling" ? 180 :
// increased from 100 to 150 since 2017-11-10
warfareType === "Antisub" ? 150 :
150; // default cap for other phases
const isCapped = precapPower > cap;
const power = Math.floor(isCapped ? cap + Math.sqrt(precapPower - cap) : precapPower);
return {
power,
cap,
isCapped
};
};
/**
* Apply known post-cap modifiers to capped attack power.
* @return {Object} capped power and applied modifiers.
* @see http://kancolle.wikia.com/wiki/Damage_Calculation
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#aftercap
*/
KC3Ship.prototype.applyPostcapModifiers = function(cappedPower, warfareType = "Shelling",
daySpecialAttackType = [], contactPlaneId = 0,
isCritical = false, isAirAttack = false, targetShipType = 0, isDefenderArmorCounted = false){
// Artillery spotting modifier, should not x2 although some types attack 2 times
const dayCutinModifier = daySpecialAttackType[0] === "Cutin" && daySpecialAttackType[3] > 0 ?
daySpecialAttackType[3] : 1;
let airstrikeConcatModifier = 1;
// Contact modifier only applied to aerial warfare airstrike power
if(warfareType === "Aerial" && contactPlaneId > 0) {
const contactPlaneAcc = KC3Master.slotitem(contactPlaneId).api_houm;
airstrikeConcatModifier = contactPlaneAcc >= 3 ? 1.2 :
contactPlaneAcc >= 2 ? 1.17 : 1.12;
}
let apshellModifier = 1;
// AP Shell modifier applied to specific target ship types:
// CA, CAV, BB, FBB, BBV, CV, CVB and Land installation
const isTargetShipTypeMatched = [5, 6, 8, 9, 10, 11, 18].includes(targetShipType);
if(isTargetShipTypeMatched) {
const mainGunCnt = this.countEquipmentType(2, [1, 2, 3]);
const apShellCnt = this.countEquipmentType(2, 19);
const secondaryCnt = this.countEquipmentType(2, 4);
const radarCnt = this.countEquipmentType(2, [12, 13]);
if(mainGunCnt >= 1 && secondaryCnt >= 1 && apShellCnt >= 1)
apshellModifier = 1.15;
else if(mainGunCnt >= 1 && apShellCnt >= 1 && radarCnt >= 1)
apshellModifier = 1.1;
else if(mainGunCnt >= 1 && apShellCnt >= 1)
apshellModifier = 1.08;
}
// Standard critical modifier
const criticalModifier = isCritical ? 1.5 : 1;
// Additional aircraft proficiency critical modifier
// Applied to open airstrike and shelling air attack including anti-sub
let proficiencyCriticalModifier = 1;
if(isCritical && (isAirAttack || warfareType === "Aerial")) {
if(daySpecialAttackType[0] === "Cutin" && daySpecialAttackType[1] === 7) {
// special proficiency critical modifier for CVCI
// http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#FAcutin
const firstSlotType = (cutinType => {
switch(cutinType) {
case "CutinFDBTB": return [6, 7, 8];
case "CutinDBDBTB":
case "CutinDBTB": return [7, 8];
default: return [];
}
})(daySpecialAttackType[2]);
const hasNonZeroSlotCaptainPlane = (type2Ids) => {
const firstGear = this.equipment(0);
return this.slots[0] > 0 && firstGear.exists() &&
type2Ids.includes(firstGear.master().api_type[2]);
};
// detail modifier affected by (internal) proficiency under verification
// might be an average value from participants, simply use max modifier (+0.1 / +0.25) here
proficiencyCriticalModifier += 0.1;
proficiencyCriticalModifier += hasNonZeroSlotCaptainPlane(firstSlotType) ? 0.15 : 0;
} else {
// http://wikiwiki.jp/kancolle/?%B4%CF%BA%DC%B5%A1%BD%CF%CE%FD%C5%D9#v3f6d8dd
const expBonus = [0, 1, 2, 3, 4, 5, 7, 10];
this.equipment().forEach((g, i) => {
if(g.isAirstrikeAircraft()) {
const aceLevel = g.ace || 0;
const internalExpLow = KC3Meta.airPowerInternalExpBounds(aceLevel)[0];
let mod = Math.floor(Math.sqrt(internalExpLow) + (expBonus[aceLevel] || 0)) / 100;
if(i > 0) mod /= 2;
proficiencyCriticalModifier += mod;
}
});
}
}
// TODO
// Rocket, Landing craft modifier
// Against PT Imp modifier
let result = Math.floor(cappedPower * criticalModifier * proficiencyCriticalModifier)
* dayCutinModifier * airstrikeConcatModifier * apshellModifier;
// New Depth Charge armor penetration, not attack power bonus
let newDepthChargeBonus = 0;
if(warfareType === "Antisub") {
const type95ndcCnt = this.countEquipment(226);
const type2ndcCnt = this.countEquipment(227);
if(type95ndcCnt > 0 || type2ndcCnt > 0) {
const deShipBonus = this.master().api_stype === 1 ? 1 : 0;
newDepthChargeBonus =
type95ndcCnt * (Math.sqrt(KC3Master.slotitem(226).api_tais - 2) + deShipBonus) +
type2ndcCnt * (Math.sqrt(KC3Master.slotitem(227).api_tais - 2) + deShipBonus);
// Applying this to enemy submarine's armor, result will be capped to at least 1
if(isDefenderArmorCounted) result += newDepthChargeBonus;
}
}
// Remaining ammo percent modifier, applied to final damage, not only attack power
const ammoPercent = Math.floor(this.ammo / this.master().api_bull_max * 100);
const remainingAmmoModifier = ammoPercent >= 50 ? 1 : ammoPercent * 2 / 100;
if(isDefenderArmorCounted) {
result *= remainingAmmoModifier;
}
return {
power: result,
criticalModifier,
proficiencyCriticalModifier,
dayCutinModifier,
airstrikeConcatModifier,
apshellModifier,
newDepthChargeBonus,
remainingAmmoModifier,
};
};
/**
* Collect battle conditions from current battle node if available.
* Do not fall-back to default value here if not available, leave it to appliers.
* @return {Object} an object contains battle properties we concern at.
* @see CalculatorManager.collectBattleConditions
*/
KC3Ship.prototype.collectBattleConditions = function(){
return KC3Calc.collectBattleConditions();
};
/**
* @return extra power bonus for combined fleet battle.
* @see http://wikiwiki.jp/kancolle/?%CF%A2%B9%E7%B4%CF%C2%E2#offense
*/
KC3Ship.prototype.combinedFleetPowerBonus = function(playerCombined, enemyCombined,
warfareType = "Shelling"){
const powerBonus = {
main: 0, escort: 0
};
switch(warfareType) {
case "Shelling":
if(!enemyCombined) {
// CTF
if(playerCombined === 1) { powerBonus.main = 2; powerBonus.escort = 10; }
// STF
if(playerCombined === 2) { powerBonus.main = 10; powerBonus.escort = -5; }
// TCF
if(playerCombined === 3) { powerBonus.main = -5; powerBonus.escort = 10; }
} else {
if(playerCombined === 1) { powerBonus.main = 2; powerBonus.escort = -5; }
if(playerCombined === 2) { powerBonus.main = 2; powerBonus.escort = -5; }
if(playerCombined === 3) { powerBonus.main = -5; powerBonus.escort = -5; }
if(!playerCombined) { powerBonus.main = 5; powerBonus.escort = 5; }
}
break;
case "Torpedo":
if(playerCombined) {
if(!enemyCombined) {
powerBonus.main = -5; powerBonus.escort = -5;
} else {
powerBonus.main = 10; powerBonus.escort = 10;
}
}
break;
case "Aerial":
if(!playerCombined && enemyCombined) {
// different by target enemy fleet, targeting main:
powerBonus.main = -10; powerBonus.escort = -10;
// targeting escort:
//powerBonus.main = -20; powerBonus.escort = -20;
}
break;
}
return powerBonus;
};
// check if this ship is capable of equipping Daihatsu (landing craft)
KC3Ship.prototype.canEquipDaihatsu = function() {
if(this.isDummy()) { return false; }
var master = this.master();
// ship types: DD=2, CL=3, BB=9, AV=16, LHA=17, AO=22
// so far only ships with types above can equip daihatsu.
if ([2,3,9,16,17,22].indexOf( master.api_stype ) === -1)
return false;
// excluding Akitsushima(445), Hayasui(460), Commandant Teste(491), Kamoi(162)
// (however their remodels are capable of equipping daihatsu
if ([445, 460, 491, 162].indexOf( this.masterId ) !== -1)
return false;
// only few DDs, CLs and 1 BB are capable of equipping daihatsu
// see comments below.
if ([2 /* DD */,3 /* CL */,9 /* BB */].indexOf( master.api_stype ) !== -1 &&
[
// Abukuma K2(200), Tatsuta K2(478), Kinu K2(487), Yura K2(488), Tama K2(547)
200, 478, 487, 488, 547,
// Satsuki K2(418), Mutsuki K2(434), Kisaragi K2(435), Fumizuki(548)
418, 434, 435, 548,
// Kasumi K2(464), Kasumi K2B(470), Arare K2 (198), Ooshio K2(199), Asashio K2D(468), Michishio K2(489), Arashio K2(490)
464, 470, 198, 199, 468, 489, 490,
// Verniy(147), Kawakaze K2(469), Murasame K2(498)
147, 469, 498,
// Nagato K2(541)
541
].indexOf( this.masterId ) === -1)
return false;
return true;
};
/**
* @return true if this ship is capable of equipping (Striking Force) Fleet Command Facility.
*/
KC3Ship.prototype.canEquipFCF = function() {
if(this.isDummy()) { return false; }
// Excluding DE, DD, XBB, SS, SSV, AO, AR, which can be found at master.stype.api_equip_type[34]
const capableStypes = [3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17, 18, 20, 21];
// These can be found at `RemodelMain.swf/scene.remodel.view.changeEquip._createType3List()`
// DD Kasumi K2, DD Murasame K2, AO Kamoi Kai-Bo, DD Naganami K2
const capableShips = [464, 498, 500, 543];
// CVL Kasugamaru
const incapableShips = [521];
const masterId = this.masterId,
stype = this.master().api_stype;
return incapableShips.indexOf(masterId) === -1 &&
(capableShips.includes(masterId) || capableStypes.includes(stype));
};
// is this ship able to do OASW unconditionally
KC3Ship.prototype.isOaswShip = function() {
// Isuzu K2, Tatsuta K2, Jervis Kai, Samuel B.Roberts Kai
return [141, 478, 394, 681].includes(this.masterId);
};
// test to see if this ship (with equipment) is capable of opening ASW
// reference: http://kancolle.wikia.com/wiki/Partials/Opening_ASW as of Feb 3, 2017
// http://wikiwiki.jp/kancolle/?%C2%D0%C0%F8%C0%E8%C0%A9%C7%FA%CD%EB%B9%B6%B7%E2#o377cad0
KC3Ship.prototype.canDoOASW = function (aswDiff = 0) {
if(this.isDummy()) { return false; }
if(this.isOaswShip()) { return true; }
const stype = this.master().api_stype,
ctype = this.master().api_ctype;
const isEscort = stype === 1;
// is CVE (Taiyou series, Gambier Bay series, Zuihou K2B)
const isEscortLightCarrier = this.isEscortLightCarrier();
const hasLargeSonar = this.hasEquipmentType(2, 40);
// Taiyou series:
// tho Kasugamaru not possible to reach high asw for now
// and base asw stat of Kai and Kai2 already exceed 70
//const isTaiyouClass = ctype === 76;
//const isTaiyouBase = this.masterId === 526;
const isTaiyouKaiAfter = RemodelDb.remodelGroup(521).indexOf(this.masterId) > 1;
// lower condition for DE and CVE, even lower if equips Large Sonar
const aswThreshold = isEscortLightCarrier && hasLargeSonar ? 50
: isEscort ? 60
: isEscortLightCarrier ? 65
: 100;
// ship stats not updated in time when equipment changed, so take the diff if necessary
const shipAsw = this.as[0] + aswDiff;
// shortcut on the stricter condition first
if (shipAsw < aswThreshold)
return false;
// for Taiyou Kai or Kai Ni, any equippable aircraft with asw should work,
// only Autogyro or PBY equipped will not let CVL anti-sub in day shelling phase,
// but CVE can still OASW. only Sonar equipped can do neither.
if (isTaiyouKaiAfter) {
return this.equipment(true).some(gear => gear.isAswAircraft(false));
} else if (isEscortLightCarrier) {
return this.equipment(true).some(gear => gear.isHighAswBomber());
}
const hasSonar = this.hasEquipmentType(1, 10);
// Escort can OASW without Sonar, but total asw >= 75 and equipped total plus asw >= 4
if(isEscort) {
if(hasSonar) return true;
const equipAswSum = this.equipmentTotalStats("tais");
return shipAsw >= 75 && equipAswSum >= 4;
}
return hasSonar;
};
/**
* @return true if this ship can do ASW attack.
*/
KC3Ship.prototype.canDoASW = function() {
if(this.isDummy() || this.isAbsent()) { return false; }
const stype = this.master().api_stype;
const isHayasuiKaiWithTorpedoBomber = this.masterId === 352 && this.hasEquipmentType(2, 8);
// CAV, CVL, BBV, AV, LHA, CVL-like Hayasui Kai
const isAirAntiSubStype = [6, 7, 10, 16, 17].includes(stype) || isHayasuiKaiWithTorpedoBomber;
if(isAirAntiSubStype) {
const isCvlLike = stype === 7 || isHayasuiKaiWithTorpedoBomber;
// false if CVL or CVL-like chuuha
if(isCvlLike && this.isStriped()) return false;
// if ASW plane equipped and slot > 0
return this.equipment().some((g, i) => this.slots[i] > 0 && g.isAswAircraft(isCvlLike));
}
// DE, DD, CL, CLT, CT, AO(*)
// *AO: Hayasui base form and Kamoi Kai-Bo can only depth charge, Kamoi base form cannot asw
const isAntiSubStype = [1, 2, 3, 4, 21, 22].includes(stype);
// if max ASW stat before marriage (Lv99) not 0, can do ASW,
// which also used at `Core.swf/vo.UserShipData.hasTaisenAbility()`
// if as[1] === 0, naked asw stat should be 0, but as[0] may not.
return isAntiSubStype && this.as[1] > 0;
};
/**
* @return true if this ship can do opening torpedo attack.
*/
KC3Ship.prototype.canDoOpeningTorpedo = function() {
if(this.isDummy() || this.isAbsent()) { return false; }
const hasKouhyouteki = this.hasEquipment(41);
const isThisSubmarine = this.isSubmarine();
return hasKouhyouteki || (isThisSubmarine && this.level >= 10);
};
/**
* @return {Object} target (enemy) ship category flags defined by us, possible values are:
* `isSurface`, `isSubmarine`, `isLand`.
*/
KC3Ship.prototype.estimateTargetShipType = function(targetShipMasterId = 0) {
const targetShip = KC3Master.ship(targetShipMasterId);
// land installation
const isLand = targetShip && targetShip.api_soku === 0;
const isSubmarine = targetShip && this.isSubmarine(targetShip.api_stype);
// regular surface vessel by default
const isSurface = !isLand && !isSubmarine;
return {
isSubmarine,
isLand,
isSurface
};
};
/**
* @return false if this ship (and target ship) can attack at day shelling phase.
*/
KC3Ship.prototype.canDoDayShellingAttack = function(targetShipMasterId = 0) {
if(this.isDummy() || this.isAbsent()) { return false; }
const targetShipType = this.estimateTargetShipType(targetShipMasterId);
const isThisSubmarine = this.isSubmarine();
const isHayasuiKaiWithTorpedoBomber = this.masterId === 352 && this.hasEquipmentType(2, 8);
const isThisCarrier = this.isCarrier() || isHayasuiKaiWithTorpedoBomber;
if(isThisCarrier) {
if(this.isTaiha()) return false;
const isNotCvb = this.master().api_stype !== 18;
if(isNotCvb && this.isStriped()) return false;
if(targetShipType.isSubmarine) return this.canDoASW();
// can not attack land installation if dive bomber equipped
if(targetShipType.isLand && this.hasNonZeroSlotEquipmentType(2, 7)) return false;
// can not attack if no bomber with slot > 0 equipped
return this.equipment().some((g, i) => this.slots[i] > 0 && g.isAirstrikeAircraft());
}
// submarines can only landing attack against land installation
if(isThisSubmarine) return this.estimateLandingAttackType(targetShipMasterId) > 0;
// can attack any enemy ship type by default
return true;
};
/**
* @return true if this ship (and target ship) can do closing torpedo attack.
*/
KC3Ship.prototype.canDoClosingTorpedo = function(targetShipMasterId = 0) {
if(this.isDummy() || this.isAbsent()) { return false; }
if(this.isStriped()) return false;
const targetShipType = this.estimateTargetShipType(targetShipMasterId);
if(targetShipType.isSubmarine || targetShipType.isLand) return false;
// DD, CL, CLT, CA, CAV, AV, SS, SSV, FBB, BB, BBV, CT
const isTorpedoStype = [2, 3, 4, 5, 6, 8, 9, 10, 13, 14, 18, 21].includes(this.master().api_stype);
return isTorpedoStype && this.nakedStats("tp") > 0;
};
/**
* @return the landing attack kind ID, return 0 if can not attack.
*/
KC3Ship.prototype.estimateLandingAttackType = function(targetShipMasterId = 0) {
const targetShip = KC3Master.ship(targetShipMasterId);
if(!this.masterId || !targetShip) return 0;
if(targetShip.api_soku === 0) {
// most priority: Toku Daihatsu + 11th Tank
if(this.hasEquipment(230)) return 5;
// Abyssal hard land installation could be landing attacked
const isTargetLandable =
[1668, 1669, 1670, 1671, 1672, // Isolated Island Princess
1665, 1666, 1667, // Artillery Imp
1653, 1654, 1655, 1656, 1657, 1658, // Supply Depot Princess
// Summer Supply Depot Princess not counted?
].includes(targetShipMasterId);
const isThisSubmarine = this.isSubmarine();
// T2 Tank
if(this.hasEquipment(167)) {
if(isThisSubmarine) return 4;
if(isTargetLandable) return 4;
}
if(isTargetLandable) {
// T89 Tank
if(this.hasEquipment(166)) return 3;
// Toku Daihatsu
if(this.hasEquipment(193)) return 2;
// Daihatsu
if(this.hasEquipment(68)) return 1;
}
}
return 0;
};
/**
* Estimate day time attack type of this ship.
* Only according ship type and equipment, ignoring factors such as ship status, target-able.
* @param {number} targetShipMasterId - a Master ID of being attacked ship, used to indicate some
* special attack types. eg: attacking a submarine, landing attack an installation.
* The ID can be just an example to represent this type of target.
* @param {boolean} trySpTypeFirst - specify true if want to estimate special attack type.
* @param {number} airBattleId - air battle result id, to indicate if special attacks can be triggered,
* special attacks require AS / AS +, default is AS+.
* @return {Array} day time attack type constants tuple:
* [name, regular attack id / cutin id / landing id, cutin name, modifier].
* cutin id is from `api_hougeki?.api_at_type` which indicates the special attacks.
* NOTE: Not take 'can not be targeted' into account yet,
* such as: CV/CVB against submarine; submarine against land installation;
* asw aircraft all lost against submarine; torpedo bomber only against land,
* should not pass targetShipMasterId at all for these scenes.
* @see https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E6%94%BB%E6%92%83%E7%A8%AE%E5%88%A5
* @see BattleMain.swf#battle.models.attack.AttackData#setOptionsAtHougeki - client side codes of day attack type.
* @see BattleMain.swf#battle.phase.hougeki.PhaseHougekiBase - client side hints of special cutin attack type.
* @see estimateNightAttackType
* @see canDoOpeningTorpedo
* @see canDoDayShellingAttack
* @see canDoASW
* @see canDoClosingTorpedo
*/
KC3Ship.prototype.estimateDayAttackType = function(targetShipMasterId = 0, trySpTypeFirst = false,
airBattleId = 1) {
if(this.isDummy()) { return []; }
// if attack target known, will give different attack according target ship
const targetShipType = this.estimateTargetShipType(targetShipMasterId);
const isThisCarrier = this.isCarrier();
const isThisSubmarine = this.isSubmarine();
const isAirSuperiorityBetter = airBattleId === 1 || airBattleId === 2;
const hasRecon = this.hasNonZeroSlotEquipmentType(2, [10, 11]);
if(trySpTypeFirst && hasRecon && isAirSuperiorityBetter) {
/*
* To estimate if can do day time special attacks (aka Artillery Spotting).
* In game, special attack types are judged and given by server API result.
* By equip compos, multiply types are possible to be selected to trigger, such as
* CutinMainMain + Double, CutinMainAPShell + CutinMainRadar + CutinMainSecond.
* Here just check by strictness & modifier desc order and return one of them.
*/
const mainGunCnt = this.countEquipmentType(2, [1, 2, 3]);
const apShellCnt = this.countEquipmentType(2, 19);
if(mainGunCnt >= 2 && apShellCnt >= 1) return ["Cutin", 6, "CutinMainMain", 1.5];
const secondaryCnt = this.countEquipmentType(2, 4);
if(mainGunCnt >= 1 && secondaryCnt >= 1 && apShellCnt >= 1)
return ["Cutin", 5, "CutinMainApshell", 1.3];
const radarCnt = this.countEquipmentType(2, [12, 13]);
if(mainGunCnt >= 1 && secondaryCnt >= 1 && radarCnt >= 1)
return ["Cutin", 4, "CutinMainRadar", 1.2];
if(mainGunCnt >= 1 && secondaryCnt >= 1) return ["Cutin", 3, "CutinMainSecond", 1.1];
if(mainGunCnt >= 2) return ["Cutin", 2, "DoubleAttack", 1.2];
// btw, ["Cutin", 1, "Laser"] no longer exists now
} else if(trySpTypeFirst && isThisCarrier && isAirSuperiorityBetter) {
// day time carrier shelling cut-in
// http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#FAcutin
// https://twitter.com/_Kotoha07/status/907598964098080768
// https://twitter.com/arielugame/status/908343848459317249
const fighterCnt = this.countNonZeroSlotEquipmentType(2, 6);
const diveBomberCnt = this.countNonZeroSlotEquipmentType(2, 7);
const torpedoBomberCnt = this.countNonZeroSlotEquipmentType(2, 8);
if(diveBomberCnt >= 1 && torpedoBomberCnt >= 1 && fighterCnt >= 1)
return ["Cutin", 7, "CutinFDBTB", 1.25];
if(diveBomberCnt >= 2 && torpedoBomberCnt >= 1)
return ["Cutin", 7, "CutinDBDBTB", 1.2];
if(diveBomberCnt >= 1 && torpedoBomberCnt >= 1) return ["Cutin", 7, "CutinDBTB", 1.15];
}
// is target a land installation
if(targetShipType.isLand) {
const landingAttackType = this.estimateLandingAttackType(targetShipMasterId);
if(landingAttackType > 0) {
return ["LandingAttack", landingAttackType];
}
const hasRocketLauncher = this.hasEquipmentType(2, 37);
// no such ID -1, just mean higher priority
if(hasRocketLauncher) return ["Rocket", -1];
}
// is this ship Hayasui Kai
if(this.masterId === 352) {
if(targetShipType.isSubmarine) {
// air attack if asw aircraft equipped
const aswEquip = this.equipment().find(g => g.isAswAircraft(false));
return aswEquip ? ["AirAttack", 1] : ["DepthCharge", 2];
}
// air attack if torpedo bomber equipped, otherwise fall back to shelling
if(this.hasEquipmentType(2, 8))
return ["AirAttack", 1];
else
return ["SingleAttack", 0];
}
if(isThisCarrier) {
return ["AirAttack", 1];
}
// only torpedo attack possible if this ship is submarine (but not shelling phase)
if(isThisSubmarine) {
return ["Torpedo", 3];
}
if(targetShipType.isSubmarine) {
const stype = this.master().api_stype;
// CAV, BBV, AV, LHA can only air attack against submarine
return ([6, 10, 16, 17].includes(stype)) ? ["AirAttack", 1] : ["DepthCharge", 2];
}
// default single shelling fire attack
return ["SingleAttack", 0];
};
/**
* @return true if this ship (and target ship) can attack at night.
*/
KC3Ship.prototype.canDoNightAttack = function(targetShipMasterId = 0) {
// no count for escaped ship too
if(this.isDummy() || this.isAbsent()) { return false; }
// no ship can night attack on taiha
if(this.isTaiha()) return false;
const initYasen = this.master().api_houg[0] + this.master().api_raig[0];
const isThisCarrier = this.isCarrier();
// even carrier can do shelling or air attack if her yasen power > 0 (no matter chuuha)
// currently known ships: Graf / Graf Kai, Saratoga, Taiyou Kai Ni
if(isThisCarrier && initYasen > 0) return true;
// carriers without yasen power can do air attack under some conditions:
if(isThisCarrier) {
// only CVB can air attack on chuuha (taiha already excluded)
const isNotCvb = this.master().api_stype !== 18;
if(isNotCvb && this.isStriped()) return false;
// Ark Royal (Kai) can air attack without NOAP if Swordfish variants equipped and slot > 0
if([515, 393].includes(this.masterId)
&& this.hasNonZeroSlotEquipment([242, 243, 244])) return true;
// night aircraft + NOAP equipped
return this.canCarrierNightAirAttack();
}
// can not night attack for any ship type if initial FP + TP is 0
return initYasen > 0;
};
/**
* @return true if a carrier can do air attack at night thank to night aircraft,
* which should be given via `api_n_mother_list`, not judged by client side.
* @see canDoNightAttack - those yasen power carriers not counted in `api_n_mother_list`.
* @see http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#NightCombatByAircrafts
*/
KC3Ship.prototype.canCarrierNightAirAttack = function() {
if(this.isDummy() || this.isAbsent()) { return false; }
if(this.isCarrier()) {
const hasNightAvPersonnel = this.hasEquipment([258, 259]);
const hasNightAircraft = this.hasEquipmentType(3, KC3GearManager.nightAircraftType3Ids);
const isThisSaratogaMk2 = this.masterId === 545;
const isThisArkRoyal = [515, 393].includes(this.masterId);
const isSwordfishArkRoyal = isThisArkRoyal && this.hasEquipment([242, 243, 244]);
// if night aircraft + (NOAP equipped / on Saratoga Mk.2),
// Swordfish variants are counted as night aircraft for Ark Royal + NOAP
if((hasNightAircraft && (hasNightAvPersonnel || isThisSaratogaMk2))
|| (hasNightAvPersonnel && isSwordfishArkRoyal))
return true;
}
return false;
};
/**
* Estimate night battle attack type of this ship.
* Also just give possible attack type, no responsibility to check can do attack at night,
* or that ship can be targeted or not, etc.
* @param {number} targetShipMasterId - a Master ID of being attacked ship.
* @param {boolean} trySpTypeFirst - specify true if want to estimate special attack type.
* @return {Array} night battle attack type constants tuple: [name, cutin id, cutin name, modifier].
* cutin id is partially from `api_hougeki.api_sp_list` which indicates the special attacks.
* @see BattleMain.swf#battle.models.attack.AttackData#setOptionsAtNight - client side codes of night attack type.
* @see BattleMain.swf#battle.phase.night.PhaseAttack - client side hints of special cutin attack type.
* @see estimateDayAttackType
* @see canDoNightAttack
*/
KC3Ship.prototype.estimateNightAttackType = function(targetShipMasterId = 0, trySpTypeFirst = false) {
if(this.isDummy()) { return []; }
const targetShipType = this.estimateTargetShipType(targetShipMasterId);
const isThisCarrier = this.isCarrier();
const isThisSubmarine = this.isSubmarine();
const stype = this.master().api_stype;
const isThisLightCarrier = stype === 7;
const isThisDestroyer = stype === 2;
const torpedoCnt = this.countEquipmentType(2, [5, 32]);
// simulate server-side night air attack flag: `api_n_mother_list`
const isCarrierNightAirAttack = isThisCarrier && this.canCarrierNightAirAttack();
if(trySpTypeFirst && !targetShipType.isSubmarine) {
// to estimate night special attacks, which should be given by server API result.
// will not trigger if this ship is taiha or targeting submarine.
// carrier night cut-in, NOAP or Saratoga Mk.II needed
if(isCarrierNightAirAttack) {
// http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#x397cac6
// https://twitter.com/Nishisonic/status/911143760544751616
const nightFighterCnt = this.countNonZeroSlotEquipmentType(3, 45);
const nightTBomberCnt = this.countNonZeroSlotEquipmentType(3, 46);
// Fighter Bomber Iwai
const specialDBomberCnt = this.countNonZeroSlotEquipment([154]);
// Swordfish variants
const specialTBomberCnt = this.countNonZeroSlotEquipment([242, 243, 244]);
if(nightFighterCnt >= 2 && nightTBomberCnt >= 1) return ["Cutin", 6, "CutinNFNFNTB", 1.25];
if(nightFighterCnt >= 3) return ["Cutin", 6, "CutinNFNFNF", 1.18];
if(nightFighterCnt >= 2 && specialDBomberCnt >= 1) return ["Cutin", 6, "CutinNFNFFBI", 1.18];
if(nightFighterCnt >= 2 && specialTBomberCnt >= 1) return ["Cutin", 6, "CutinNFNFSF", 1.18];
if(nightFighterCnt >= 1 && specialTBomberCnt >= 2) return ["Cutin", 6, "CutinNFSFSF", 1.18];
if(nightFighterCnt >= 1 && specialDBomberCnt >= 1 && specialTBomberCnt >= 1)
return ["Cutin", 6, "CutinNFFBISF", 1.18];
if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && specialDBomberCnt >= 1)
return ["Cutin", 6, "CutinNFNTBFBI", 1.18];
if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && specialTBomberCnt >= 1)
return ["Cutin", 6, "CutinNFNTBSF", 1.18];
// https://twitter.com/imoDer_Tw/status/968294965745893377
if(nightFighterCnt >= 1 && nightTBomberCnt >= 2) return ["Cutin", 6, "CutinNFNTBNTB", 1.25];
if(nightFighterCnt >= 1 && nightTBomberCnt >= 1) return ["Cutin", 6, "CutinNFNTB", 1.2];
} else {
// special torpedo radar cut-in for destroyers since 2017-10-25
if(isThisDestroyer && torpedoCnt >= 1) {
// according tests, any radar with accuracy stat >= 3 capable,
// even large radars (Kasumi K2 can equip), air radars okay too, see:
// https://twitter.com/nicolai_2501/status/923172168141123584
// https://twitter.com/nicolai_2501/status/923175256092581888
const hasCapableRadar = this.equipment(true).some(gear => gear.isHighAccuracyRadar());
const hasSkilledLookout = this.hasEquipmentType(2, 39);
const smallMainGunCnt = this.countEquipmentType(2, 1);
// http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#dfcb6e1f
if(hasCapableRadar && hasSkilledLookout)
return ["Cutin", 8, "CutinTorpRadarLookout", 1.25];
if(hasCapableRadar && smallMainGunCnt >= 1) {
// https://twitter.com/ayanamist_m2/status/944176834551222272
const has127TwinGunModelD2 = this.hasEquipment(267);
return ["Cutin", 7, "CutinMainTorpRadar", 1.3 * (has127TwinGunModelD2 ? 1.25 : 1)];
}
}
// special torpedo cut-in for late model submarine torpedo
const lateTorpedoCnt = this.countEquipment([213, 214]);
const submarineRadarCnt = this.countEquipmentType(2, 51);
if(lateTorpedoCnt >= 1 && submarineRadarCnt >= 1) return ["Cutin", 3, "CutinTorpTorpTorp", 1.75];
if(lateTorpedoCnt >= 2) return ["Cutin", 3, "CutinTorpTorpTorp", 1.6];
if(torpedoCnt >= 2) return ["Cutin", 3, "CutinTorpTorpTorp", 1.5];
const mainGunCnt = this.countEquipmentType(2, [1, 2, 3, 38]);
if(mainGunCnt >= 3) return ["Cutin", 5, "CutinMainMainMain", 2.0];
const secondaryCnt = this.countEquipmentType(2, 4);
if(mainGunCnt === 2 && secondaryCnt >= 1) return ["Cutin", 4, "CutinMainMainSecond", 1.75];
if((mainGunCnt === 2 && secondaryCnt === 0 && torpedoCnt === 1) ||
(mainGunCnt === 1 && torpedoCnt === 1)) return ["Cutin", 2, "CutinTorpTorpMain", 1.3];
// double attack can be torpedo attack animation if topmost slot is torpedo
if((mainGunCnt === 2 && secondaryCnt === 0 && torpedoCnt === 0) ||
(mainGunCnt === 1 && secondaryCnt >= 1) ||
(secondaryCnt >= 2 && torpedoCnt <= 1)) return ["Cutin", 1, "DoubleAttack", 1.2];
}
}
if(targetShipType.isLand) {
const landingAttackType = this.estimateLandingAttackType(targetShipMasterId);
if(landingAttackType > 0) {
return ["LandingAttack", landingAttackType];
}
const hasRocketLauncher = this.hasEquipmentType(2, 37);
if(hasRocketLauncher) return ["Rocket", -1];
}
// priority to use server flag, but impossible to test on abyssal below for now
if(isCarrierNightAirAttack) {
return ["AirAttack", 1];
}
if(targetShipType.isSubmarine && isThisLightCarrier) {
return ["DepthCharge", 2];
}
if(isThisCarrier) {
// these abyssal ships can only be shelling attacked
const isSpecialAbyssal = [
1679, 1680, 1681, 1682, 1683, // Lycoris Princess
1711, 1712, 1713, // Jellyfish Princess
].includes[targetShipMasterId];
const isSpecialCarrier = [
432, 353, // Graf & Graf Kai
433 // Saratoga (base form)
].includes(this.masterId);
if(isSpecialCarrier || isSpecialAbyssal) return ["SingleAttack", 0];
// here just indicates 'attack type', not 'can attack or not', see canDoNightAttack
// Taiyou Kai Ni fell back to shelling attack if no bomber equipped, but ninja changed by devs.
// now she will air attack against surface ships, but no plane appears if no aircraft equipped.
return ["AirAttack", 1];
}
if(isThisSubmarine) {
return ["Torpedo", 3];
}
if(targetShipType.isSubmarine) {
// CAV, BBV, AV, LHA
return ([6, 10, 16, 17].includes(stype)) ? ["AirAttack", 1] : ["DepthCharge", 2];
}
// torpedo attack if any torpedo equipped at top most, otherwise single shelling fire
const topGear = this.equipment().find(gear => gear.exists() &&
[1, 2, 3].includes(gear.master().api_type[1]));
return topGear && topGear.master().api_type[1] === 3 ? ["Torpedo", 3] : ["SingleAttack", 0];
};
/**
* Get current shelling attack accuracy related info of this ship.
* NOTE: Only attacker accuracy part, not take defender evasion part into account at all, not final hit/critical rate.
* @param {number} formationModifier - see #estimateShellingFormationModifier.
* @param {boolean} applySpAttackModifiers - if special equipment and attack modifiers should be applied.
* @return {Object} accuracy factors of this ship.
* @see http://kancolle.wikia.com/wiki/Combat/Accuracy_and_Evasion
* @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6
* @see https://twitter.com/Nishisonic/status/890202416112480256
*/
KC3Ship.prototype.shellingAccuracy = function(formationModifier = 1, applySpAttackModifiers = true) {
if(this.isDummy()) { return {}; }
const byLevel = 2 * Math.sqrt(this.level - 1);
// formula from PSVita is sqrt(1.5 * lk) anyway,
// but verifications have proved this one gets more accurate
// http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:450#68
const byLuck = 1.5 * Math.sqrt(this.lk[0]);
const byEquip = -this.nakedStats("ac");
const byImprove = this.equipment(true)
.map(g => g.accStatImprovementBonus("fire"))
.sumValues();
const byGunfit = this.shellingGunFitAccuracy();
const battleConds = this.collectBattleConditions();
const moraleModifier = this.moraleEffectLevel([1, 0.5, 0.8, 1, 1.2], battleConds.isOnBattle);
const basic = 90 + byLevel + byLuck + byEquip + byImprove;
const beforeSpModifier = basic * formationModifier * moraleModifier + byGunfit;
let artillerySpottingModifier = 1;
// there is trigger chance rate for Artillery Spotting itself
if(applySpAttackModifiers) {
artillerySpottingModifier = (type => {
if(type[0] === "Cutin") {
// ID from `api_hougeki.api_at_type`, see #estimateDayAttackType:
// [regular attack, Laser, DA, Main Second, Main Radar, Main Second AP, Main Main AP, CVCI]
// modifier for CVCI still unknown
return [0, 0, 1.1, 1.3, 1.5, 1.3, 1.2, 1][type[1]] || 1;
}
return 1;
})(this.estimateDayAttackType(undefined, true, battleConds.airBattleId));
}
const apShellModifier = (() => {
// AP Shell combined with Large cal. main gun only mainly for battleships
const hasApShellAndMainGun = this.hasEquipmentType(2, 19) && this.hasEquipmentType(2, 3);
if(hasApShellAndMainGun) {
const hasSecondaryGun = this.hasEquipmentType(2, 4);
const hasRadar = this.hasEquipmentType(2, [12, 13]);
if(hasRadar && hasSecondaryGun) return 1.3;
if(hasRadar) return 1.25;
if(hasSecondaryGun) return 1.2;
return 1.1;
}
return 1;
})();
// penalty for combined fleets under verification
const accuracy = Math.floor(beforeSpModifier * artillerySpottingModifier * apShellModifier);
return {
accuracy,
basicAccuracy: basic,
preSpAttackAccuracy: beforeSpModifier,
equipmentStats: byEquip,
equipImprovement: byImprove,
equipGunFit: byGunfit,
moraleModifier,
formationModifier,
artillerySpottingModifier,
apShellModifier
};
};
/**
* @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6#hitterm1
* @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6#avoidterm1
*/
KC3Ship.prototype.estimateShellingFormationModifier = function(
playerFormationId = ConfigManager.aaFormation,
enemyFormationId = 0,
type = "accuracy") {
let modifier = 1;
switch(type) {
case "accuracy":
// Default is no bonus for regular fleet
// Still unknown for combined fleet formation
// Line Ahead, Diamond:
modifier = 1;
switch(playerFormationId) {
case 2: // Double Line, cancelled by Line Abreast
modifier = enemyFormationId === 5 ? 1.0 : 1.2;
break;
case 4: // Echelon, cancelled by Line Ahead
modifier = enemyFormationId === 1 ? 1.0 : 1.2;
break;
case 5: // Line Abreast, cancelled by Echelon
modifier = enemyFormationId === 4 ? 1.0 : 1.2;
break;
case 6:{// Vanguard, depends on fleet position
const [shipPos, shipCnt] = this.fleetPosition(),
isGuardian = shipCnt >= 4 && shipPos >= Math.floor(shipCnt / 2);
modifier = isGuardian ? 1.2 : 0.8;
break;
}
}
break;
case "evasion":
// Line Ahead, Double Line:
modifier = 1;
switch(playerFormationId) {
case 3: // Diamond
modifier = 1.1;
break;
case 4: // Echelon, enhanced by Double Line / Echelon unknown
modifier = 1.2;
break;
case 5: // Line Abreast, enhanced by Echelon / Line Abreast unknown
modifier = 1.3;
break;
case 6:{// Vanguard, depends on fleet position and ship type
const [shipPos, shipCnt] = this.fleetPosition(),
isGuardian = shipCnt >= 4 && shipPos >= (Math.floor(shipCnt / 2) + 1),
isThisDestroyer = this.master().api_stype === 2;
modifier = isThisDestroyer ?
(isGuardian ? 1.4 : 1.2) :
(isGuardian ? 1.2 : 1.05);
break;
}
}
break;
default:
console.warn("Unknown modifier type:", type);
}
return modifier;
};
/**
* Get current shelling accuracy bonus (or penalty) from equipped guns.
* @see http://kancolle.wikia.com/wiki/Combat/Overweight_Penalty_and_Fit_Gun_Bonus
* @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6#fitarms
*/
KC3Ship.prototype.shellingGunFitAccuracy = function(time = "day") {
if(this.isDummy()) { return 0; }
var result = 0;
// Fit bonus or overweight penalty for ship types:
const stype = this.master().api_stype;
const ctype = this.master().api_ctype;
switch(stype) {
case 2: // for Destroyers
// fit bonus under verification since 2017-06-23
const singleHighAngleMountCnt = this.countEquipment(229);
// for Satsuki K2
result += (this.masterId === 418 ? 5 : 0) * Math.sqrt(singleHighAngleMountCnt);
// for Mutsuki class, Kamikaze class still unknown
break;
case 3:
case 4:
case 21: // for Light Cruisers
// overhaul implemented in-game since 2017-06-23, still under verification
const singleMountIds = [4, 11];
const twinMountIds = [65, 119, 139];
const tripleMainMountIds = [5, 235];
const singleHighAngleMountId = 229;
const isAganoClass = ctype === 41;
const isOoyodoClass = ctype === 52;
result = -2; // only fit bonus, but -2 fixed
// for all CLs
result += 4 * Math.sqrt(this.countEquipment(singleMountIds));
// for twin mount on Agano class / Ooyodo class / general CLs
result += (isAganoClass ? 8 : isOoyodoClass ? 5 : 3) *
Math.sqrt(this.countEquipment(twinMountIds));
// for 15.5cm triple main mount on Ooyodo class
result += (isOoyodoClass ? 7 : 0) *
Math.sqrt(this.countEquipment(tripleMainMountIds));
// for 12.7cm single HA late model on Yura K2
result += (this.masterId === 488 ? 10 : 0) *
Math.sqrt(this.countEquipment(singleHighAngleMountId));
break;
case 5:
case 6: // for Heavy Cruisers
// fit bonus at night battle for 20.3cm variants
if(time === "night") {
const has203TwinGun = this.hasEquipment(6);
const has203No3TwinGun = this.hasEquipment(50);
const has203No2TwinGun = this.hasEquipment(90);
// 20.3cm priority to No.3, No.2 might also
result += has203TwinGun ? 10 : has203No2TwinGun ? 10 : has203No3TwinGun ? 15 : 0;
}
// for 15.5cm triple main mount on Mogami class
const isMogamiClass = ctype === 9;
if(isMogamiClass) {
const count155TripleMainGun = this.countEquipment(5);
const count155TripleMainGunKai = this.countEquipment(235);
result += 2 * Math.sqrt(count155TripleMainGun) +
5 * Math.sqrt(count155TripleMainGunKai);
}
// for 203mm/53 twin mount on Zara class
const isZaraClass = ctype === 64;
if(isZaraClass) {
result += 1 * Math.sqrt(this.countEquipment(162));
}
break;
case 8:
case 9:
case 10: // for Battleships
// Large cal. main gun gives accuracy bonus if it's fit,
// and accuracy penalty if it's overweight.
const gunCountFitMap = {};
this.equipment(true).forEach(g => {
if(g.itemId && g.masterId && g.master().api_type[2] === 3) {
const fitInfo = KC3Meta.gunfit(this.masterId, g.masterId);
if(fitInfo && !fitInfo.unknown) {
const gunCount = (gunCountFitMap[fitInfo.weight] || [0])[0];
gunCountFitMap[fitInfo.weight] = [gunCount + 1, fitInfo];
}
}
});
$.each(gunCountFitMap, (_, fit) => {
const count = fit[0];
let value = fit[1][time] || 0;
if(this.isMarried()) value *= fit[1].married || 1;
result += value * Math.sqrt(count);
});
break;
default:
// not found for other ships
}
return result;
};
/**
* Get current shelling attack evasion related info of this ship.
* @param {number} formationModifier - see #estimateShellingFormationModifier
* @return {Object} evasion factors of this ship.
* @see http://kancolle.wikia.com/wiki/Combat/Accuracy_and_Evasion
* @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6
*/
KC3Ship.prototype.shellingEvasion = function(formationModifier = 1) {
if(this.isDummy()) { return {}; }
// already naked ev + equipment total ev stats
const byStats = this.ev[0];
const byEquip = this.equipmentTotalStats("houk");
const byLuck = Math.sqrt(2 * this.lk[0]);
const preCap = Math.floor((byStats + byLuck) * formationModifier);
const postCap = preCap >= 65 ? Math.floor(55 + 2 * Math.sqrt(preCap - 65)) :
preCap >= 40 ? Math.floor(40 + 3 * Math.sqrt(preCap - 40)) :
preCap;
const byImprove = this.equipment(true)
.map(g => g.evaStatImprovementBonus("fire"))
.sumValues();
// under verification
const stypeBonus = 0;
const searchlightModifier = this.hasEquipmentType(1, 18) ? 0.2 : 1;
const postCapForYasen = Math.floor(postCap + stypeBonus) * searchlightModifier;
const fuelPercent = Math.floor(this.fuel / this.master().api_fuel_max * 100);
const fuelPenalty = fuelPercent < 75 ? 75 - fuelPercent : 0;
// final hit % = ucap(floor(lcap(attackerAccuracy - defenderEvasion) * defenderMoraleModifier)) + aircraftProficiencyBonus
// capping limits its lower / upper bounds to [10, 96] + 1%, +1 since random number is 0-based, ranged in [0, 99]
// ship morale modifier not applied here since 'evasion' may be looked reduced when sparkle
const battleConds = this.collectBattleConditions();
const moraleModifier = this.moraleEffectLevel([1, 1.4, 1.2, 1, 0.7], battleConds.isOnBattle);
const evasion = Math.floor(postCap + byImprove - fuelPenalty);
const evasionForYasen = Math.floor(postCapForYasen + byImprove - fuelPenalty);
return {
evasion,
evasionForYasen,
preCap,
postCap,
postCapForYasen,
equipmentStats: byEquip,
equipImprovement: byImprove,
fuelPenalty,
moraleModifier,
formationModifier
};
};
KC3Ship.prototype.equipmentAntiAir = function(forFleet) {
return AntiAir.shipEquipmentAntiAir(this, forFleet);
};
KC3Ship.prototype.adjustedAntiAir = function() {
const floor = AntiAir.specialFloor(this);
return floor(AntiAir.shipAdjustedAntiAir(this));
};
KC3Ship.prototype.proportionalShotdownRate = function() {
return AntiAir.shipProportionalShotdownRate(this);
};
KC3Ship.prototype.proportionalShotdown = function(n) {
return AntiAir.shipProportionalShotdown(this, n);
};
// note:
// - fixed shotdown makes no sense if the current ship is not in a fleet.
// - formationId takes one of the following:
// - 1/4/5 (for line ahead / echelon / line abreast)
// - 2 (for double line)
// - 3 (for diamond)
// - 6 (for vanguard)
// - all possible AACIs are considered and the largest AACI modifier
// is used for calculation the maximum number of fixed shotdown
KC3Ship.prototype.fixedShotdownRange = function(formationId) {
if(!this.onFleet()) return false;
const fleetObj = PlayerManager.fleets[ this.onFleet() - 1 ];
return AntiAir.shipFixedShotdownRangeWithAACI(this, fleetObj,
AntiAir.getFormationModifiers(formationId || 1) );
};
KC3Ship.prototype.maxAaciShotdownBonuses = function() {
return AntiAir.shipMaxShotdownAllBonuses( this );
};
/**
* Anti-air Equipment Attack Effect implemented since 2018-02-05 in-game.
* @return a tuple indicates the effect type ID and its term key.
*/
KC3Ship.prototype.estimateAntiAirEffectType = function() {
const aaEquipType = (() => {
// Escaped or sunk ship cannot anti-air
if(this.isDummy() || this.isAbsent()) return -1;
const stype = this.master().api_stype;
// CAV, BBV, CV/CVL/CVB, AV can use Rocket Launcher K2
const isStypeForRockeLaunK2 = [6, 7, 10, 11, 16, 18].includes(stype);
// Type 3 Shell
if(this.hasEquipmentType(2, 18)) {
if(isStypeForRockeLaunK2 && this.hasEquipment(274)) return 5;
return 4;
}
// 12cm 30tube Rocket Launcher Kai Ni
if(isStypeForRockeLaunK2 && this.hasEquipment(274)) return 3;
// 12cm 30tube Rocket Launcher
if(this.hasEquipment(51)) return 2;
// Any HA Mount
if(this.hasEquipmentType(3, 16)) return 1;
// Any AA Machine Gun
if(this.hasEquipmentType(2, 21)) return 0;
// Any Radar plus any Seaplane bomber with AA stat
if(this.hasEquipmentType(3, 11) && this.equipment().some(
g => g.masterId > 0 && g.master().api_type[2] === 11 && g.master().api_tyku > 0
)) return 0;
return -1;
})();
switch(aaEquipType) {
case -1: return [-1, "None"];
case 0: return [0, "Normal"];
case 1: return [1, "HighAngleMount"];
case 2: return [2, "RocketLauncher"];
case 3: return [3, "RocketLauncherK2"];
case 4: return [4, "Type3Shell"];
case 5: return [5, "Type3ShellRockeLaunK2"];
default: return [NaN, "Unknown"];
}
};
/**
* To calculate 12cm 30tube Rocket Launcher Kai Ni (Rosa K2) trigger chance (for now),
* we need adjusted AA of ship, number of Rosa K2, ctype and luck stat.
* @see https://twitter.com/kankenRJ/status/979524073934893056 - current formula
* @see http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:2471 - old formula verifying thread
*/
KC3Ship.prototype.calcAntiAirEffectChance = function() {
if(this.isDummy() || this.isAbsent()) return 0;
// Number of 12cm 30tube Rocket Launcher Kai Ni
let rosaCount = this.countEquipment(274);
if(rosaCount === 0) return 0;
// Not tested yet on more than 3 Rosa K2, capped to 3 just in case of exceptions
rosaCount = rosaCount > 3 ? 3 : rosaCount;
const rosaAdjustedAntiAir = 48;
// 70 for Ise-class, 0 otherwise
const classBonus = this.master().api_ctype === 2 ? 70 : 0;
// Rounding to x%
return Math.qckInt("floor",
(this.adjustedAntiAir() + this.lk[0]) /
(400 - (rosaAdjustedAntiAir + 30 + 40 * rosaCount + classBonus)) * 100,
0);
};
/**
* Check known possible effects on equipment changed.
* @param {Object} newGearObj - the equipment just equipped, pseudo empty object if unequipped.
* @param {Object} oldGearObj - the equipment before changed, pseudo empty object if there was empty.
*/
KC3Ship.prototype.equipmentChangedEffects = function(newGearObj = {}, oldGearObj = {}) {
if(!this.masterId) return {isShow: false};
const gunFit = newGearObj.masterId ? KC3Meta.gunfit(this.masterId, newGearObj.masterId) : false;
let isShow = gunFit !== false;
const shipAacis = AntiAir.sortedPossibleAaciList(AntiAir.shipPossibleAACIs(this));
isShow = isShow || shipAacis.length > 0;
const oldEquipAsw = oldGearObj.masterId > 0 ? oldGearObj.master().api_tais : 0;
const newEquipAsw = newGearObj.masterId > 0 ? newGearObj.master().api_tais : 0;
const aswDiff = newEquipAsw - oldEquipAsw;
const oaswPower = this.canDoOASW(aswDiff) ? this.antiSubWarfarePower(aswDiff) : false;
isShow = isShow || (oaswPower !== false);
// Possible TODO:
// can opening torpedo
// can cut-in (fire / air)
// can night attack for CV
// can night cut-in
return {
isShow,
shipObj: this,
gearObj: newGearObj.masterId ? newGearObj : false,
gunFit,
shipAacis,
oaswPower,
};
};
/* Expedition Supply Change Check */
KC3Ship.prototype.perform = function(command,args) {
try {
args = $.extend({noFuel:0,noAmmo:0},args);
command = command.slice(0,1).toUpperCase() + command.slice(1).toLowerCase();
this["perform"+command].call(this,args);
} catch (e) {
console.error("Failed when perform" + command, e);
return false;
} finally {
return true;
}
};
KC3Ship.prototype.performSupply = function(args) {
consumePending.call(this,0,{0:0,1:1,2:3,c: 1 - (this.isMarried() && 0.15),i: 0},[0,1,2],args);
};
KC3Ship.prototype.performRepair = function(args) {
consumePending.call(this,1,{0:0,1:2,2:6,c: 1,i: 0},[0,1,2],args);
};
function consumePending(index,mapping,clear,args) {
/*jshint validthis: true */
if(!(this instanceof KC3Ship)) {
throw new Error("Cannot modify non-KC3Ship instance!");
}
var
self = this,
mult = mapping.c,
lastN = Object.keys(this.pendingConsumption).length - mapping.i;
delete mapping.c;
delete mapping.i;
if(args.noFuel) delete mapping['0'];
if(args.noAmmo) delete mapping['1'];
/* clear pending consumption, by iterating each keys */
var
rmd = [0,0,0,0,0,0,0,0],
lsFirst = this.lastSortie[0];
Object.keys(this.pendingConsumption).forEach(function(shipConsumption,iterant){
var
dat = self.pendingConsumption[shipConsumption],
rsc = [0,0,0,0,0,0,0,0],
sid = self.lastSortie.indexOf(shipConsumption);
// Iterate supplied ship part
Object.keys(mapping).forEach(function(key){
var val = dat[index][key] * (mapping[key]===3 ? 5 : mult);
// Calibrate for rounding towards zero
rmd[mapping[key]] += val % 1;
rsc[mapping[key]] += Math.ceil(val) + parseInt(rmd[mapping[key]]);
rmd[mapping[key]] %= 1;
// Checks whether current iteration is last N pending item
if((iterant < lastN) && (clear.indexOf(parseInt(key))>=0))
dat[index][key] = 0;
});
console.log("Ship " + self.rosterId + " consumed", shipConsumption, sid,
[iterant, lastN].join('/'), rsc.map(x => -x), dat[index]);
// Store supplied resource count to database by updating the source
KC3Database.Naverall({
data: rsc
},shipConsumption);
if(dat.every(function(consumptionData){
return consumptionData.every(function(resource){ return !resource; });
})) {
delete self.pendingConsumption[shipConsumption];
}
/* Comment Stopper */
});
var
lsi = 1,
lsk = "";
while(lsi < this.lastSortie.length && this.lastSortie[lsi] != 'sortie0') {
lsk = this.lastSortie[lsi];
if(this.pendingConsumption[ lsk ]){
lsi++;
}else{
this.lastSortie.splice(lsi,1);
}
}
if(this.lastSortie.indexOf(lsFirst) < 0) {
this.lastSortie.unshift(lsFirst);
}
KC3ShipManager.save();
}
/**
* Fill data of this Ship into predefined tooltip HTML elements. Used by Panel/Strategy Room.
* @param tooltipBox - the object of predefined tooltip HTML jq element
* @return return back the jq element of param `tooltipBox`
*/
KC3Ship.prototype.htmlTooltip = function(tooltipBox) {
return KC3Ship.buildShipTooltip(this, tooltipBox);
};
KC3Ship.buildShipTooltip = function(shipObj, tooltipBox) {
//const shipDb = WhoCallsTheFleetDb.getShipStat(shipObj.masterId);
const nakedStats = shipObj.nakedStats(),
maxedStats = shipObj.maxedStats(),
maxDiffStats = {},
equipDiffStats = {},
modLeftStats = shipObj.modernizeLeftStats();
Object.keys(maxedStats).map(s => {maxDiffStats[s] = maxedStats[s] - nakedStats[s];});
Object.keys(nakedStats).map(s => {equipDiffStats[s] = nakedStats[s] - (shipObj[s]||[])[0];});
const signedNumber = n => (n > 0 ? '+' : n === 0 ? '\u00b1' : '') + n;
const replaceFilename = (file, newName) => file.slice(0, file.lastIndexOf("/") + 1) + newName;
$(".ship_full_name .ship_masterId", tooltipBox).text("[{0}]".format(shipObj.masterId));
$(".ship_full_name span.value", tooltipBox).text(shipObj.name());
$(".ship_full_name .ship_yomi", tooltipBox).text(ConfigManager.info_ship_class_name ?
KC3Meta.ctypeName(shipObj.master().api_ctype) :
KC3Meta.shipReadingName(shipObj.master().api_yomi)
);
$(".ship_rosterId span", tooltipBox).text(shipObj.rosterId);
$(".ship_stype", tooltipBox).text(shipObj.stype());
$(".ship_level span.value", tooltipBox).text(shipObj.level);
//$(".ship_level span.value", tooltipBox).addClass(shipObj.levelClass());
$(".ship_hp span.hp", tooltipBox).text(shipObj.hp[0]);
$(".ship_hp span.mhp", tooltipBox).text(shipObj.hp[1]);
$(".ship_morale img", tooltipBox).attr("src",
replaceFilename($(".ship_morale img", tooltipBox).attr("src"), shipObj.moraleIcon() + ".png")
);
$(".ship_morale span.value", tooltipBox).text(shipObj.morale);
$(".ship_exp_next span.value", tooltipBox).text(shipObj.exp[1]);
$(".stat_hp .current", tooltipBox).text(shipObj.hp[1]);
$(".stat_hp .mod", tooltipBox).text(signedNumber(modLeftStats.hp))
.toggle(!!modLeftStats.hp);
$(".stat_fp .current", tooltipBox).text(shipObj.fp[0]);
$(".stat_fp .mod", tooltipBox).text(signedNumber(modLeftStats.fp))
.toggle(!!modLeftStats.fp);
$(".stat_fp .equip", tooltipBox).text("({0})".format(nakedStats.fp))
.toggle(!!equipDiffStats.fp);
$(".stat_ar .current", tooltipBox).text(shipObj.ar[0]);
$(".stat_ar .mod", tooltipBox).text(signedNumber(modLeftStats.ar))
.toggle(!!modLeftStats.ar);
$(".stat_ar .equip", tooltipBox).text("({0})".format(nakedStats.ar))
.toggle(!!equipDiffStats.ar);
$(".stat_tp .current", tooltipBox).text(shipObj.tp[0]);
$(".stat_tp .mod", tooltipBox).text(signedNumber(modLeftStats.tp))
.toggle(!!modLeftStats.tp);
$(".stat_tp .equip", tooltipBox).text("({0})".format(nakedStats.tp))
.toggle(!!equipDiffStats.tp);
$(".stat_ev .current", tooltipBox).text(shipObj.ev[0]);
$(".stat_ev .level", tooltipBox).text(signedNumber(maxDiffStats.ev))
.toggle(!!maxDiffStats.ev);
$(".stat_ev .equip", tooltipBox).text("({0})".format(nakedStats.ev))
.toggle(!!equipDiffStats.ev);
$(".stat_aa .current", tooltipBox).text(shipObj.aa[0]);
$(".stat_aa .mod", tooltipBox).text(signedNumber(modLeftStats.aa))
.toggle(!!modLeftStats.aa);
$(".stat_aa .equip", tooltipBox).text("({0})".format(nakedStats.aa))
.toggle(!!equipDiffStats.aa);
$(".stat_ac .current", tooltipBox).text(shipObj.carrySlots());
const canOasw = shipObj.canDoOASW();
$(".stat_as .current", tooltipBox).text(shipObj.as[0])
.toggleClass("oasw", canOasw);
$(".stat_as .level", tooltipBox).text(signedNumber(maxDiffStats.as))
.toggle(!!maxDiffStats.as);
$(".stat_as .equip", tooltipBox).text("({0})".format(nakedStats.as))
.toggle(!!equipDiffStats.as);
$(".stat_as .mod", tooltipBox).text(signedNumber(modLeftStats.as))
.toggle(!!modLeftStats.as);
$(".stat_sp", tooltipBox).text(shipObj.speedName())
.addClass(KC3Meta.shipSpeed(shipObj.speed, true));
$(".stat_ls .current", tooltipBox).text(shipObj.ls[0]);
$(".stat_ls .level", tooltipBox).text(signedNumber(maxDiffStats.ls))
.toggle(!!maxDiffStats.ls);
$(".stat_ls .equip", tooltipBox).text("({0})".format(nakedStats.ls))
.toggle(!!equipDiffStats.ls);
$(".stat_rn", tooltipBox).text(shipObj.rangeName())
.toggleClass("RangeChanged", shipObj.range != shipObj.master().api_leng);
$(".stat_lk .current", tooltipBox).text(shipObj.lk[0]);
$(".stat_lk .luck", tooltipBox).text(signedNumber(modLeftStats.lk));
$(".stat_lk .equip", tooltipBox).text("({0})".format(nakedStats.lk))
.toggle(!!equipDiffStats.lk);
if(!(ConfigManager.info_stats_diff & 1)){
$(".equip", tooltipBox).hide();
}
if(!(ConfigManager.info_stats_diff & 2)){
$(".mod,.level,.luck", tooltipBox).hide();
}
// Fill more stats need complex calculations
KC3Ship.fillShipTooltipWideStats(shipObj, tooltipBox, canOasw);
return tooltipBox;
};
KC3Ship.fillShipTooltipWideStats = function(shipObj, tooltipBox, canOasw = false) {
const signedNumber = n => (n > 0 ? '+' : n === 0 ? '\u00b1' : '') + n;
const optionalModifier = (m, showX1) => (showX1 || m !== 1 ? 'x' + m : "");
// show possible critical power and mark capped power with different color
const joinPowerAndCritical = (p, cp, cap) => (cap ? '<span class="power_capped">{0}</span>' : "{0}")
.format(String(Math.qckInt("floor", p, 0))) + (!cp ? "" :
(cap ? '(<span class="power_capped">{0}</span>)' : "({0})")
.format(Math.qckInt("floor", cp, 0))
);
const onFleetNum = shipObj.onFleet();
const battleConds = shipObj.collectBattleConditions();
const attackTypeDay = shipObj.estimateDayAttackType();
const warfareTypeDay = {
"Torpedo" : "Torpedo",
"DepthCharge" : "Antisub",
"LandingAttack" : "AntiLand",
"Rocket" : "AntiLand"
}[attackTypeDay[0]] || "Shelling";
const isAswPowerShown = (canOasw && !shipObj.isOaswShip())
|| (shipObj.canDoASW() && shipObj.onlyHasEquipmentType(1, [10, 15, 16, 32]));
// Show ASW power if Opening ASW conditions met, or only ASW equipment equipped
if(isAswPowerShown){
let power = shipObj.antiSubWarfarePower();
let criticalPower = false;
let isCapped = false;
const canShellingAttack = shipObj.canDoDayShellingAttack();
const canOpeningTorp = shipObj.canDoOpeningTorpedo();
const canClosingTorp = shipObj.canDoClosingTorpedo();
if(ConfigManager.powerCapApplyLevel >= 1) {
({power} = shipObj.applyPrecapModifiers(power, "Antisub",
battleConds.engagementId, battleConds.formationId || 5));
}
if(ConfigManager.powerCapApplyLevel >= 2) {
({power, isCapped} = shipObj.applyPowerCap(power, "Day", "Antisub"));
}
if(ConfigManager.powerCapApplyLevel >= 3) {
if(ConfigManager.powerCritical) {
criticalPower = shipObj.applyPostcapModifiers(
power, "Antisub", undefined, undefined,
true, attackTypeDay[0] === "AirAttack").power;
}
({power} = shipObj.applyPostcapModifiers(power, "Antisub"));
}
let attackTypeIndicators = !canShellingAttack ?
KC3Meta.term("ShipAttackTypeNone") :
KC3Meta.term("ShipAttackType" + attackTypeDay[0]);
if(canOpeningTorp) attackTypeIndicators += ", {0}"
.format(KC3Meta.term("ShipExtraPhaseOpeningTorpedo"));
if(canClosingTorp) attackTypeIndicators += ", {0}"
.format(KC3Meta.term("ShipExtraPhaseClosingTorpedo"));
$(".dayAttack", tooltipBox).html(
KC3Meta.term("ShipDayAttack").format(
KC3Meta.term("ShipWarfareAntisub"),
joinPowerAndCritical(power, criticalPower, isCapped),
attackTypeIndicators
)
);
} else {
let combinedFleetBonus = 0;
if(onFleetNum) {
const powerBonus = shipObj.combinedFleetPowerBonus(
battleConds.playerCombinedFleetType, battleConds.isEnemyCombined, warfareTypeDay
);
combinedFleetBonus = onFleetNum === 1 ? powerBonus.main :
onFleetNum === 2 ? powerBonus.escort : 0;
}
let power = warfareTypeDay === "Torpedo" ?
shipObj.shellingTorpedoPower(combinedFleetBonus) :
shipObj.shellingFirePower(combinedFleetBonus);
let criticalPower = false;
let isCapped = false;
const canShellingAttack = warfareTypeDay === "Torpedo" ||
shipObj.canDoDayShellingAttack();
const canOpeningTorp = shipObj.canDoOpeningTorpedo();
const canClosingTorp = shipObj.canDoClosingTorpedo();
const spAttackType = shipObj.estimateDayAttackType(undefined, true, battleConds.airBattleId);
// Apply power cap by configured level
if(ConfigManager.powerCapApplyLevel >= 1) {
({power} = shipObj.applyPrecapModifiers(power, warfareTypeDay,
battleConds.engagementId, battleConds.formationId));
}
if(ConfigManager.powerCapApplyLevel >= 2) {
({power, isCapped} = shipObj.applyPowerCap(power, "Day", warfareTypeDay));
}
if(ConfigManager.powerCapApplyLevel >= 3) {
if(ConfigManager.powerCritical) {
criticalPower = shipObj.applyPostcapModifiers(
power, warfareTypeDay, spAttackType, undefined,
true, attackTypeDay[0] === "AirAttack").power;
}
({power} = shipObj.applyPostcapModifiers(power, warfareTypeDay,
spAttackType));
}
let attackTypeIndicators = !canShellingAttack ? KC3Meta.term("ShipAttackTypeNone") :
spAttackType[0] === "Cutin" ?
KC3Meta.cutinTypeDay(spAttackType[1]) :
KC3Meta.term("ShipAttackType" + attackTypeDay[0]);
if(canOpeningTorp) attackTypeIndicators += ", {0}"
.format(KC3Meta.term("ShipExtraPhaseOpeningTorpedo"));
if(canClosingTorp) attackTypeIndicators += ", {0}"
.format(KC3Meta.term("ShipExtraPhaseClosingTorpedo"));
$(".dayAttack", tooltipBox).html(
KC3Meta.term("ShipDayAttack").format(
KC3Meta.term("ShipWarfare" + warfareTypeDay),
joinPowerAndCritical(power, criticalPower, isCapped),
attackTypeIndicators
)
);
}
const attackTypeNight = shipObj.estimateNightAttackType();
const canNightAttack = shipObj.canDoNightAttack();
const warfareTypeNight = {
"Torpedo" : "Torpedo",
"DepthCharge" : "Antisub",
"LandingAttack" : "AntiLand",
"Rocket" : "AntiLand"
}[attackTypeNight[0]] || "Shelling";
if(attackTypeNight[0] === "AirAttack" && canNightAttack){
let power = shipObj.nightAirAttackPower(battleConds.contactPlaneId == 102);
let criticalPower = false;
let isCapped = false;
const spAttackType = shipObj.estimateNightAttackType(undefined, true);
if(ConfigManager.powerCapApplyLevel >= 1) {
({power} = shipObj.applyPrecapModifiers(power, "Shelling",
battleConds.engagementId, battleConds.formationId, spAttackType,
battleConds.isStartFromNight, battleConds.playerCombinedFleetType > 0));
}
if(ConfigManager.powerCapApplyLevel >= 2) {
({power, isCapped} = shipObj.applyPowerCap(power, "Night", "Shelling"));
}
if(ConfigManager.powerCapApplyLevel >= 3) {
if(ConfigManager.powerCritical) {
criticalPower = shipObj.applyPostcapModifiers(
power, "Shelling", undefined, undefined, true, true).power;
}
({power} = shipObj.applyPostcapModifiers(power, "Shelling"));
}
$(".nightAttack", tooltipBox).html(
KC3Meta.term("ShipNightAttack").format(
KC3Meta.term("ShipWarfareShelling"),
joinPowerAndCritical(power, criticalPower, isCapped),
spAttackType[0] === "Cutin" ?
KC3Meta.cutinTypeNight(spAttackType[1]) :
KC3Meta.term("ShipAttackType" + spAttackType[0])
)
);
} else {
let power = shipObj.nightBattlePower(battleConds.contactPlaneId == 102);
let criticalPower = false;
let isCapped = false;
const spAttackType = shipObj.estimateNightAttackType(undefined, true);
// Apply power cap by configured level
if(ConfigManager.powerCapApplyLevel >= 1) {
({power} = shipObj.applyPrecapModifiers(power, warfareTypeNight,
battleConds.engagementId, battleConds.formationId, spAttackType,
battleConds.isStartFromNight, battleConds.playerCombinedFleetType > 0));
}
if(ConfigManager.powerCapApplyLevel >= 2) {
({power, isCapped} = shipObj.applyPowerCap(power, "Night", warfareTypeNight));
}
if(ConfigManager.powerCapApplyLevel >= 3) {
if(ConfigManager.powerCritical) {
criticalPower = shipObj.applyPostcapModifiers(
power, warfareTypeNight, undefined, undefined, true).power;
}
({power} = shipObj.applyPostcapModifiers(power, warfareTypeNight));
}
let attackTypeIndicators = !canNightAttack ? KC3Meta.term("ShipAttackTypeNone") :
spAttackType[0] === "Cutin" ?
KC3Meta.cutinTypeNight(spAttackType[1]) :
KC3Meta.term("ShipAttackType" + spAttackType[0]);
$(".nightAttack", tooltipBox).html(
KC3Meta.term("ShipNightAttack").format(
KC3Meta.term("ShipWarfare" + warfareTypeNight),
joinPowerAndCritical(power, criticalPower, isCapped),
attackTypeIndicators
)
);
}
// TODO implement other types of accuracy
const shellingAccuracy = shipObj.shellingAccuracy(
shipObj.estimateShellingFormationModifier(battleConds.formationId, battleConds.enemyFormationId),
true
);
$(".shellingAccuracy", tooltipBox).text(
KC3Meta.term("ShipAccShelling").format(
Math.qckInt("floor", shellingAccuracy.accuracy, 1),
signedNumber(shellingAccuracy.equipmentStats),
signedNumber(Math.qckInt("floor", shellingAccuracy.equipImprovement, 1)),
signedNumber(Math.qckInt("floor", shellingAccuracy.equipGunFit, 1)),
optionalModifier(shellingAccuracy.moraleModifier, true),
optionalModifier(shellingAccuracy.artillerySpottingModifier),
optionalModifier(shellingAccuracy.apShellModifier)
)
);
const shellingEvasion = shipObj.shellingEvasion(
shipObj.estimateShellingFormationModifier(battleConds.formationId, battleConds.enemyFormationId, "evasion")
);
$(".shellingEvasion", tooltipBox).text(
KC3Meta.term("ShipEvaShelling").format(
Math.qckInt("floor", shellingEvasion.evasion, 1),
signedNumber(shellingEvasion.equipmentStats),
signedNumber(Math.qckInt("floor", shellingEvasion.equipImprovement, 1)),
signedNumber(-shellingEvasion.fuelPenalty),
optionalModifier(shellingEvasion.moraleModifier, true)
)
);
const [aaEffectTypeId, aaEffectTypeTerm] = shipObj.estimateAntiAirEffectType();
$(".adjustedAntiAir", tooltipBox).text(
KC3Meta.term("ShipAAAdjusted").format(
"{0}{1}".format(
shipObj.adjustedAntiAir(),
/* Here indicates the type of AA ability, not the real attack animation in-game,
* only special AA effect types will show a banner text in-game,
* like the T3 Shell shoots or Rockets shoots,
* regular AA gun animation triggered by equipping AA gun, Radar+SPB or HA mount.
* btw1, 12cm Rocket Launcher non-Kai belongs to AA guns, no irregular attack effect.
* btw2, flagship will fall-back to the effect user if none has any attack effect.
*/
aaEffectTypeId > -1 ?
" ({0})".format(
aaEffectTypeId === 3 ?
// Show a trigger chance for RosaK2 Defense, still unknown if with Type3 Shell
"{0}:{1}%".format(KC3Meta.term("ShipAAEffect" + aaEffectTypeTerm), shipObj.calcAntiAirEffectChance()) :
KC3Meta.term("ShipAAEffect" + aaEffectTypeTerm)
) : ""
)
)
);
$(".propShotdownRate", tooltipBox).text(
KC3Meta.term("ShipAAShotdownRate").format(
Math.qckInt("floor", shipObj.proportionalShotdownRate() * 100, 1)
)
);
const maxAaciParams = shipObj.maxAaciShotdownBonuses();
if(maxAaciParams[0] > 0){
$(".aaciMaxBonus", tooltipBox).text(
KC3Meta.term("ShipAACIMaxBonus").format(
"+{0} (x{1})".format(maxAaciParams[1], maxAaciParams[2])
)
);
} else {
$(".aaciMaxBonus", tooltipBox).text(
KC3Meta.term("ShipAACIMaxBonus").format(KC3Meta.term("None"))
);
}
// Not able to get following anti-air things if not on a fleet
if(onFleetNum){
const fixedShotdownRange = shipObj.fixedShotdownRange(ConfigManager.aaFormation);
const fleetPossibleAaci = fixedShotdownRange[2];
if(fleetPossibleAaci > 0){
$(".fixedShotdown", tooltipBox).text(
KC3Meta.term("ShipAAFixedShotdown").format(
"{0}~{1} (x{2})".format(fixedShotdownRange[0], fixedShotdownRange[1],
AntiAir.AACITable[fleetPossibleAaci].modifier)
)
);
} else {
$(".fixedShotdown", tooltipBox).text(
KC3Meta.term("ShipAAFixedShotdown").format(fixedShotdownRange[0])
);
}
const propShotdown = shipObj.proportionalShotdown(ConfigManager.imaginaryEnemySlot);
const aaciFixedShotdown = fleetPossibleAaci > 0 ? AntiAir.AACITable[fleetPossibleAaci].fixed : 0;
$.each($(".sd_title .aa_col", tooltipBox), function(idx, col){
$(col).text(KC3Meta.term("ShipAAShotdownTitles").split("/")[idx] || "");
});
$(".bomberSlot span", tooltipBox).text(ConfigManager.imaginaryEnemySlot);
$(".sd_both span", tooltipBox).text(
// Both succeeded
propShotdown + fixedShotdownRange[1] + aaciFixedShotdown + 1
);
$(".sd_prop span", tooltipBox).text(
// Proportional succeeded only
propShotdown + aaciFixedShotdown + 1
);
$(".sd_fixed span", tooltipBox).text(
// Fixed succeeded only
fixedShotdownRange[1] + aaciFixedShotdown + 1
);
$(".sd_fail span", tooltipBox).text(
// Both failed
aaciFixedShotdown + 1
);
} else {
$(".fixedShotdown", tooltipBox).text(
KC3Meta.term("ShipAAFixedShotdown").format("-"));
$.each($(".sd_title .aa_col", tooltipBox), function(idx, col){
$(col).text(KC3Meta.term("ShipAAShotdownTitles").split("/")[idx] || "");
});
}
return tooltipBox;
};
KC3Ship.onShipTooltipOpen = function(event, ui) {
const setStyleVar = (name, value) => {
const shipTooltipStyle = $(ui.tooltip).children().children().get(0).style;
shipTooltipStyle.removeProperty(name);
shipTooltipStyle.setProperty(name, value);
};
// find which width of wide rows overflow, add slide animation to them
// but animation might cost 10% more or less CPU even accelerated with GPU
let maxOverflow = 0;
$(".stat_wide div", ui.tooltip).each(function() {
// scroll width only works if element is visible
const sw = $(this).prop('scrollWidth'),
w = $(this).width(),
over = w - sw;
maxOverflow = Math.min(maxOverflow, over);
// allow overflow some pixels
if(over < -8) { $(this).addClass("use-gpu slide"); }
});
setStyleVar("--maxOverflow", maxOverflow + "px");
return true;
};
KC3Ship.prototype.deckbuilder = function() {
var itemsInfo = {};
var result = {
id: this.masterId,
lv: this.level,
luck: this.lk[0],
items: itemsInfo
};
var gearInfo;
for(var i=0; i<5; ++i) {
gearInfo = this.equipment(i).deckbuilder();
if (gearInfo)
itemsInfo["i".concat(i+1)] = gearInfo;
else
break;
}
gearInfo = this.exItem().deckbuilder();
if (gearInfo) {
// #1726 Deckbuilder: if max slot not reach 5, `ix` will not be used,
// which means i? > ship.api_slot_num will be considered as the ex-slot.
var usedSlot = Object.keys(itemsInfo).length;
if(usedSlot < 5) {
itemsInfo["i".concat(usedSlot+1)] = gearInfo;
} else {
itemsInfo.ix = gearInfo;
}
}
return result;
};
})();
|
'use strict';
/**
* Module dependencies
*/
var _ = require('lodash'),
path = require('path'),
mongoose = require('mongoose'),
util = require('util'),
Listing = mongoose.model('Listing'),
Category = mongoose.model('Category'),
// emails = require(path.resolve('./modules/emails/server/controllers/emails.server.controller')),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
http = require('http'),
https = require('https'),
async = require('async'),
config = require(path.resolve('./config/config'));
/**
* Create an listing
*/
exports.create = function (req, res) {
var listing = new Listing(req.body);
listing.user = req.user;
var geo = new Array();
geo[0] = req.body.address.geo[0];
geo[1] = req.body.address.geo[1];
listing.address.geo = geo;
listing.save(function (err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(listing);
}
});
};
/**
* Show the current Listing
*/
exports.read = function(req, res) {
// stats increase VIEWs per day
req.listing.save();
// convert mongoose document to JSON
var listing = req.listing ? req.listing.toJSON() : {};
// Add a custom field to the Article, for determining if the current User is the "owner".
// NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
listing.isCurrentUserOwner = req.user && listing.user && listing.user._id.toString() === req.user._id.toString();
res.jsonp(listing);
};
/**
* Update a Listing
*/
exports.update = function(req, res) {
var listing = req.listing;
listing = _.extend(listing, req.body);
listing.save(req, function(err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(listing);
}
});
};
/**
* Delete an listing
*/
exports.delete = function (req, res) {
var listing = req.listing;
listing.remove(function (err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(listing);
}
});
};
/**
* List of Listings
*/
exports.list = function (req, res) {
Listing.find({ status: { $ne: 'deleted' } })
.populate({
path: 'user',
select: 'displayName'
})
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'images',
select: 'thumbnail'
})
.exec(function (err, listings) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(listings);
}
});
};
/**
* List of Draft Listings
*/
exports.draft = function (req, res) {
Listing.find({ status: { $ne: 'deleted' } })
.where('status').equals('draft')
.populate({
path: 'user',
select: 'displayName'
})
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'images',
select: 'thumbnail'
})
.exec(function (err, listings) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(listings);
}
});
};
/**
* List of Pending Listings
*/
exports.pending = function (req, res) {
Listing.find({ status: { $ne: 'deleted' } })
.where('status').equals('pending approval')
.populate({
path: 'user',
select: 'displayName'
})
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'images',
select: 'thumbnail'
})
.exec(function (err, listings) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(listings);
}
});
};
/**
* List of Featured Listings
*/
exports.ordination = function (req, res) {
Listing.find({ status: { $ne: 'deleted' } })
.where('ordination').equals(10)
.populate({
path: 'user',
populate: { path: 'profileImage', select: 'url' },
select: 'displayName email profileImageURL profileImage'
})
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'images',
select: 'thumbnail extra_small medium'
})
.exec(function (err, listings) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(listings);
}
});
};
/**
* List of listings by Advanced search category and location
*/
exports.advancedSearch = function(req, res) {
var qLocation = req.params.qLocation;
var qCategory = req.params.qCategory;
var categoryId;
var getCategoryId = function(callback) {
Category.find({ 'name': qCategory }).exec(function(err, categories) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// findByCategoryId(categories);
callback(null, categories);
}
});
};
var getGeoLocation = function(callback) {
// get lat long for the location
// https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY
var mapsUrl = 'https://maps.googleapis.com/maps/api/geocode/json';
var addressUrl = '?address=' + qLocation;
var keyUrl = '&key=AIzaSyAq_CqCdUptAgsfsQWFYcPEAV8MH0Fi81Y';
var reqUrl = encodeURI(mapsUrl + addressUrl + keyUrl);
https.get(reqUrl, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var mapsResponse = JSON.parse(body);
console.log('\naddress: ' + reqUrl);
var geo = new Array();
geo[0] = mapsResponse.results[0].geometry.location.lat;
geo[1] = mapsResponse.results[0].geometry.location.lng;
// findByGeo(geo);
var dist = distance(
mapsResponse.results[0].geometry.bounds.northeast.lat,
mapsResponse.results[0].geometry.bounds.northeast.lng,
mapsResponse.results[0].geometry.bounds.southwest.lat,
mapsResponse.results[0].geometry.bounds.southwest.lng);
var ret = {};
ret.geo = geo;
ret.dist = dist / 2;
// findByGeo(geo, dist / 2);
callback(null, ret);
});
}).on('error', function(e) {
console.log('Got an error: ', e);
});
};
// Here the magician happen
async.parallel([
getGeoLocation,
getCategoryId
], function(err, results) {
findByCategoryAndLocation(results[0], results[1]);
});
function findByCategoryAndLocation(locat, categories) {
var geo = locat.geo;
categoryId = categories[0]._id;
var maxDistance = locat.dist / 111; // transformed to degrees - 0.0015696123
Listing.find({
'address.geo': {
$near: geo,
$maxDistance: maxDistance
},
category: { $in: [categoryId] },
status: 'active'
}, { category: 1, title: 1, period: 1, price: 1, user: 1, address: 1, featuredImage: 1 })
.sort({ featured: -1, created: -1 })
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'user',
populate: { path: 'profileImage', select: 'url' },
select: 'displayName email profileImageURL profileImage'
})
.exec(function(err, listings) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(listings);
}
});
}
};
exports.advancedSearchCategory = function(req, res) {
var qCategory = req.params.qCategory;
var origRes = res;
var categoryId;
var getCategoryId = function() {
Category.find({ 'name': qCategory }).exec(function(err, categories) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// findByCategoryId(categories);
findByCategoryId(categories);
}
});
};
function findByCategoryId(categories) {
categoryId = categories[0]._id;
Listing.find({
category: { $in: [categoryId] }
})
.where('status').equals('active')
.sort({ featured: -1, created: -1 })
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'user',
populate: { path: 'profileImage', select: 'url' },
select: 'displayName email profileImageURL profileImage'
})
.exec(function(err, listings) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
origRes.jsonp(listings);
}
});
}
getCategoryId();
};
exports.advancedSearchLocation = function(req, res) {
var qLocation = req.params.qLocation;
var origRes = res;
var getGeoLocation = function() {
var mapsUrl = 'https://maps.googleapis.com/maps/api/geocode/json';
var addressUrl = '?address=' + qLocation;
var keyUrl = '&key=AIzaSyAq_CqCdUptAgsfsQWFYcPEAV8MH0Fi81Y';
var reqUrl = encodeURI(mapsUrl + addressUrl + keyUrl);
https.get(reqUrl, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var mapsResponse = JSON.parse(body);
console.log('\naddress: ' + reqUrl);
var geo = new Array();
geo[0] = mapsResponse.results[0].geometry.location.lat;
geo[1] = mapsResponse.results[0].geometry.location.lng;
var dist = distance(
mapsResponse.results[0].geometry.bounds.northeast.lat,
mapsResponse.results[0].geometry.bounds.northeast.lng,
mapsResponse.results[0].geometry.bounds.southwest.lat,
mapsResponse.results[0].geometry.bounds.southwest.lng);
findByGeo(geo, dist / 2);
});
}).on('error', function(e) {
console.log('Got an error: ', e);
});
};
function findByGeo(geo, kmDistance) {
var maxDistance = kmDistance / 111; // kms transformed to degrees - 0.0015696123
Listing.find({
'address.geo': {
$near: geo,
$maxDistance: maxDistance
},
status: 'active'
})
.where('status').equals('active')
.sort({ featured: -1, created: -1 })
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'user',
populate: { path: 'profileImage', select: 'url' },
select: 'displayName email profileImageURL profileImage'
})
.exec(function(err, listings) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// stats increase listing impression
// for (var x = 0; x < listings.length; x ++) {
// listings[x].incImpressionsPerDay(new Date());
// listings[x].save();
// }
origRes.jsonp(listings);
}
});
}
getGeoLocation();
};
exports.searchAll = function(req, res) {
Listing.find({ status: 'active' }).sort({ featured: -1, created: -1 })
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'images',
select: 'thumbnail extra_small thumbnail'
})
.populate({
path: 'user',
populate: { path: 'profileImage', select: 'url' },
select: 'displayName email profileImageURL profileImage'
})
.exec(function(err, listings) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(listings);
}
});
};
/**
* Save as a favorite
*/
exports.saveFavorite = function(req, res) {
var listing = req.listing;
var userId = mongoose.Types.ObjectId(req.user._id);
var isUserExist = false;
listing.listUserLikes.map(function(user) {
if (user.id === userId.id)
isUserExist = true;
return user;
});
if (isUserExist) {
return res.status(208).send({
message: 'Already Favorited',
isSave: true
});
} else {
listing.listUserLikes.push(userId);
listing.stats.clicks += 1;
listing.save(req, function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err),
isSave: false
});
} else {
return res.status(200).send({
message: 'Listing is favorited',
isSave: true
});
}
});
}
};
/**
* Update favorite count
*/
exports.unsaveFavorite = function(req, res) {
var listing = req.listing;
var userId = mongoose.Types.ObjectId(req.user._id);
var isUserExist = false;
var i = 0;
var userIndex = -1;
listing.listUserLikes.map(function(user) {
if (user.id === userId.id) {
isUserExist = true;
userIndex = i;
}
i++;
return user;
});
if (isUserExist) {
listing.listUserLikes.splice(userIndex, 1);
listing.stats.clicks -= 1;
listing.save(req, function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err),
isSave: true
});
} else {
return res.status(200).send({
message: 'Listing is removed from favorites',
isSave: false
});
}
});
} else {
return res.status(208).send({
message: 'Already removed from favorites',
isSave: false
});
}
};
/**
* List of Favorites
*/
exports.listFavorites = function(req, res) {
Listing.find({ 'stats.clicks': { $gt: 1 } })
.sort('-created')
.populate({
path: 'category',
select: 'name'
})
.populate('user', 'displayName')
.exec(function(err, listings) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(listings);
}
});
};
/**
* Similar listings
*/
exports.listSimilar = function(req, res) {
var categoryId = req.listing.category._id;
var listingId = req.listing._id;
var location = req.listing.address.geo;
var maxDistance = 15 / 111.12; // transformed to radians - 0.0015696123
Listing.find({
'address.geo': {
$near: location,
$maxDistance: maxDistance
},
category: { $in: [categoryId] },
status: 'active',
'_id': { $ne: listingId }
})
.limit(3)
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'images',
select: 'thumbnail extra_small thumbnail'
})
.populate({
path: 'user',
populate: { path: 'profileImage', select: 'url' },
select: 'displayName email profileImageURL profileImage'
})
.exec(function(err, listings) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(listings);
}
});
};
/**
* Listing middleware
*/
exports.listingByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Listing is invalid'
});
}
Listing.findById(id)
.populate({
path: 'user',
select: 'displayName'
})
.populate({
path: 'category',
select: 'name'
})
.populate({
path: 'images',
select: 'thumbnail double_extra_small extra_small small medium large'
})
.exec(function (err, listing) {
if (err) {
return next(err);
} else if (!listing) {
return res.status(404).send({
message: 'No Listing with that identifier has been found'
});
}
listing.address.geo.lat = listing.address.geo[0];
listing.address.geo.lng = listing.address.geo[1];
req.listing = listing;
req.oldListing = JSON.parse(JSON.stringify(listing));
next();
});
};
|
/* eslint-disable object-curly-newline */
const { createBulkTest } = require('./bulkTest');
const request = require('request');
// The maximum number of iterations to check the status of given bulk tests (4 hours).
const MAX_INTERVAL_ITERATIONS = 480;
// The number of milliseconds to wait until the next bulk test is created (5 minutes).
const NEW_TEST_WAITING_MILLIS = 300000;
// A list of test parameters to test.
const TOP_LIST =
[
{ url: 'http://www.alibaba.com/', location: 'us-east-1:Chrome.Native', whitelist: 'i.alicdn.com, img.alicdn.com, sc01.alicdn.com, sc02.alicdn.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.condenast.com/', location: 'eu-central-1:Chrome.Native', whitelist: 'netdna-cdn.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://diply.com/', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.espn.com/', location: 'us-east-1:Chrome.Native', whitelist: 'espncdn.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://fandom.wikia.com/explore', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.golem.de/', location: 'eu-central-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://imgur.com/', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.kicker.de/', location: 'eu-central-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.molsoncoors.com/en', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.msn.com/de-de/', location: 'us-east-1:Chrome.Native', whitelist: 'static-global-s-msn-com.akamaized.net', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.realtor.com/', location: 'us-east-1:Chrome.Native', whitelist: 'krxd.net', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.reddit.com/', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.theguardian.com/international', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.tumblr.com/', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.walmart.com/', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.yelp.com/sf', location: 'us-east-1:Chrome.Native', whitelist: 'yelpcdn.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.ebay.com/', location: 'us-east-1:Chrome.Native', whitelist: 'i.ebayimg.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.office.com/', location: 'us-east-1:Chrome.Native', whitelist: 'weuofficehome.msocdn.com, assets.onestore.ms', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.imdb.com/', location: 'us-east-1:Chrome.Native', whitelist: 'ia.media-imdb.com, images-na.ssl-images-amazon.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.wellsfargo.com/', location: 'us-east-1:Chrome.Native', whitelist: 'wellsfargomedia.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.breitbart.com/', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.microsoft.com/en-us/', location: 'us-east-1:Chrome.Native', whitelist: 'img-prod-cms-rt-microsoft-com.akamaized.net', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.upworthy.com/', location: 'us-east-1:Chrome.Native', whitelist: 'f1.media.brightcove.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.wsj.com/news/us', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.usatoday.com/', location: 'us-east-1:Chrome.Native', whitelist: 'gannett-cdn.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.booking.com/', location: 'us-east-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'https://www.tripadvisor.com/', location: 'us-east-1:Chrome.Native', whitelist: 'static.tacdn.com', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.computerbild.de/', location: 'eu-central-1:Chrome.Native', whitelist: 'i.computer-bild.de', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.bild.de/', location: 'eu-central-1:Chrome.Native', whitelist: 'code.bildstatic.de', isCachingEnabled: false, runs: 10, mobile: false },
{ url: 'http://www.spiegel.de/', location: 'eu-central-1:Chrome.Native', whitelist: '', isCachingEnabled: false, runs: 10, mobile: false },
];
/**
* Verifies display color for a given factor
*
* @param factor A number to be colored
*/
function factorColor(factor) {
// very good result
if (factor > 3) {
return '#00cc66';
}
// good result
if (factor > 2) {
return '#86bc00';
}
// ok result
if (factor >= 1) {
return '#cc9a00';
}
// bad result
return '#ad0900';
}
/**
* Verifies display color for a given diff
*
* @param diff A number to be colored
*/
function diffColor(diff) {
// very good result
if (diff > 1) {
return '#00cc66';
}
// good result
if (diff > 0.5) {
return '#86bc00';
}
// ok result
if (diff >= 0) {
return '#cc9a00';
}
// bad result
return '#ad0900';
}
/**
* Create table data cell (td) with optional color style
*
* @param data The data to be displayed
* @param withoutColor Boolean to decide whether to display a colored result or not
* @param isFactor Boolean to decide how to generate the display color
*/
function createTableDataCell(data, withoutColor = false, isFactor = true) {
if (withoutColor) {
return `<td>${data}</td>`;
}
return `<td style="color: ${isFactor ? factorColor(data) : diffColor(data)};">${data}</td>`;
}
/**
* Create the mail template to be send
*
* @param bulkTestMap A mapping of new and previous bulkTest objects
*/
function createMailTemplate(bulkTestMap) {
const totalValues = { SIPrevious: 0, SILatest: 0, FMPPrevious: 0, FMPLatest: 0 };
let templateString = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>' +
'<body><table border="1" width="100%"><tr><th>URL</th><th>SI Ø Previous</th><th>SI Ø Latest</th><th>SI ∆</th>' +
'<th>FMP Ø Previous</th><th>FMP Ø Latest</th><th>FMP ∆</th></tr>';
bulkTestMap.forEach((previous, latest) => {
// dummy object to ensure that factors is available
const ensurePrevious = previous || { factors: {} };
const ensureLatest = latest || { factors: {} };
const speedIndexDiff = (ensureLatest.factors.speedIndex || 0) - (ensurePrevious.factors.speedIndex || 0);
const firstMeaningfulPaintDiff =
(ensureLatest.factors.firstMeaningfulPaint || 0) - (ensurePrevious.factors.firstMeaningfulPaint || 0);
// calculate total values
totalValues.SIPrevious += ensurePrevious.factors.speedIndex || 0;
totalValues.SILatest += ensureLatest.factors.speedIndex || 0;
totalValues.FMPPrevious += ensurePrevious.factors.firstMeaningfulPaint || 0;
totalValues.FMPLatest += ensureLatest.factors.firstMeaningfulPaint || 0;
templateString +=
`<tr>
${createTableDataCell(latest.url, true)}
${ensurePrevious.factors.speedIndex ? createTableDataCell(ensurePrevious.factors.speedIndex.toFixed(2)) : createTableDataCell('-', true)}
${ensureLatest.factors.speedIndex ? createTableDataCell(ensureLatest.factors.speedIndex.toFixed(2)) : createTableDataCell('-', true)}
${createTableDataCell(speedIndexDiff.toFixed(2), false, false)}
${ensurePrevious.factors.firstMeaningfulPaint ? createTableDataCell(ensurePrevious.factors.firstMeaningfulPaint.toFixed(2)) : createTableDataCell('-', true)}
${ensureLatest.factors.firstMeaningfulPaint ? createTableDataCell(ensureLatest.factors.firstMeaningfulPaint.toFixed(2)) : createTableDataCell('-', true)}
${createTableDataCell(firstMeaningfulPaintDiff.toFixed(2), false, false)}
</tr>`;
});
const totalSpedIndexPrevious = (totalValues.SIPrevious / bulkTestMap.size).toFixed(2);
const totalSpedIndexLatest = (totalValues.SILatest / bulkTestMap.size).toFixed(2);
const totalSpeedIndexDiff = (totalSpedIndexLatest - totalSpedIndexPrevious).toFixed(2);
const totalFMPPrevious = (totalValues.FMPPrevious / bulkTestMap.size).toFixed(2);
const totalFMPLatest = (totalValues.FMPLatest / bulkTestMap.size).toFixed(2);
const totalFirstMeaningfulPaintDiff = (totalFMPLatest - totalFMPPrevious).toFixed(2);
templateString +=
`<tr>
<td>
<strong>Total</strong>
</td>
${createTableDataCell(totalSpedIndexPrevious)}
${createTableDataCell(totalSpedIndexLatest)}
${createTableDataCell(totalSpeedIndexDiff, false, false)}
${createTableDataCell(totalFMPPrevious)}
${createTableDataCell(totalFMPLatest)}
${createTableDataCell(totalFirstMeaningfulPaintDiff, false, false)}
</tr></table></body></html>`;
return templateString;
}
/**
* Load previous bulk test of a given bulk test (created by the cronjob)
*
* @param db The Baqend instance.
* @param bulkTest The latest bulk test .
*/
function loadPreviousBulkTest(db, bulkTest) {
return db.BulkTest.find()
.eq('url', bulkTest.url)
.eq('createdBy', 'cronjob')
.lt('createdAt', bulkTest.createdAt)
.descending('createdAt')
.singleResult();
}
/**
* Send a notification mail.
*
* @param template A template string to be send as email.
*/
function sendMail(template) {
const options = {
method: 'post',
body: { template },
json: true,
url: 'https://bbq.app.baqend.com/v1/code/top30Mail',
};
// sendMail
request(options, () => {});
}
/**
* Send a notification mail.
*
* @param db The Baqend instance.
* @param bulkTests An array of bulkTest objects.
*/
function sendSuccessMail(db, bulkTests) {
const bulkTestMap = new Map();
const loadPromises = bulkTests.map(bulkTest => loadPreviousBulkTest(db, bulkTest)
.then(latestBulkTest => bulkTestMap.set(bulkTest, latestBulkTest)));
Promise.all(loadPromises).then(() => {
const template = createMailTemplate(bulkTestMap);
sendMail(template);
});
}
/**
* Starts an interval to check whether all passed bulk test have finished.
*
* @param db The Baqend instance.
* @param bulkTests An array of bulkTest objects.
*/
function startCheckStateInterval(db, bulkTests) {
let iterations = 0;
const finishedBulkTests = [];
const interval = setInterval(() => {
iterations += 1;
bulkTests.forEach((bulkTest) => {
bulkTest.load().then(() => {
if (bulkTest.hasFinished) {
finishedBulkTests.push(bulkTest);
bulkTests.splice(bulkTests.indexOf(bulkTest), 1);
}
});
});
if (finishedBulkTests.length === TOP_LIST.length) {
db.log.info('Clear interval because of success');
clearInterval(interval);
sendSuccessMail(db, finishedBulkTests);
} else if (iterations >= MAX_INTERVAL_ITERATIONS) {
db.log.error('Clear interval because of failure');
clearInterval(interval);
}
}, 30000);
}
/**
* Starts a number of bulk tests and initiates the state checking process.
*
* @param db The Baqend instance.
* @param n The number of the iteration.
* @param bulkTests An array of bulkTest objects.
*/
function startBulkTests(db, n = 0, bulkTests = []) {
if (n < TOP_LIST.length) {
createBulkTest(db, 'cronjob', TOP_LIST[n]).then((bulkTest) => {
bulkTests.push(bulkTest);
setTimeout(startBulkTests, NEW_TEST_WAITING_MILLIS, db, n + 1, bulkTests);
});
} else {
startCheckStateInterval(db, bulkTests);
}
}
exports.call = function callQueueTest(db, data, req) {
startBulkTests(db);
};
|
tabOverride.set(document.getElementsByTagName('textarea')); |
var fs = require('fs');
function reloadCustomAvatars() {
var path = require('path');
var newCustomAvatars = {};
fs.readdirSync('./config/avatars').forEach(function (file) {
var ext = path.extname(file);
if (ext !== '.png' && ext !== '.gif')
return;
var user = toId(path.basename(file, ext));
newCustomAvatars[user] = file;
delete Config.customavatars[user];
});
// Make sure the manually entered avatars exist
for (var a in Config.customavatars)
if (typeof Config.customavatars[a] === 'number')
newCustomAvatars[a] = Config.customavatars[a];
else
fs.exists('./config/avatars/' + Config.customavatars[a], function (user, file, isExists) {
if (isExists)
Config.customavatars[user] = file;
}.bind(null, a, Config.customavatars[a]));
Config.customavatars = newCustomAvatars;
}
reloadCustomAvatars();
if (Config.watchConfig) {
fs.watchFile('./config/config.js', function (curr, prev) {
if (curr.mtime <= prev.mtime) return;
reloadCustomAvatars();
});
}
const script = function () {
/*
FILENAME=`mktemp`
function cleanup {
rm -f $FILENAME
}
trap cleanup EXIT
set -xe
timeout 10 wget "$1" -nv -O $FILENAME
FRAMES=`identify $FILENAME | wc -l`
if [ $FRAMES -gt 1 ]; then
EXT=".gif"
else
EXT=".png"
fi
timeout 10 convert $FILENAME -layers TrimBounds -coalesce -adaptive-resize 80x80\> -background transparent -gravity center -extent 80x80 "$2$EXT"
*/
}.toString().match(/[^]*\/\*([^]*)\*\//)[1];
var pendingAdds = {};
exports.commands = {
sca: 'customavatar',
customavatars: 'customavatar',
customavatar: function (target, room, user) {
var parts = target.split(',');
var cmd = parts[0].trim().toLowerCase();
if (cmd in {'':1, show:1, view:1, display:1}) {
var message = "";
for (var a in Config.customavatars)
message += "<strong>" + Tools.escapeHTML(a) + ":</strong> " + Tools.escapeHTML(Config.customavatars[a]) + "<br />";
return this.sendReplyBox(message);
}
if (!this.can('pban') && !Gold.hasBadge(toId(user.name),'vip')) return false;
switch (cmd) {
case 'set':
var userid = toId(parts[1]);
var targetUser = Users.getExact(userid);
var avatar = parts.slice(2).join(',').trim();
if (!this.can('pban') && Gold.hasBadge(toId(user.name),'vip') && userid !== user.userid) return false;
if (!userid) return this.sendReply("You didn't specify a user.");
if (Config.customavatars[userid]) return this.sendReply(userid + " already has a custom avatar.");
var hash = require('crypto').createHash('sha512').update(userid + '\u0000' + avatar).digest('hex').slice(0, 8);
pendingAdds[hash] = {userid: userid, avatar: avatar};
parts[1] = hash;
if (!targetUser) {
this.sendReply("Warning: " + userid + " is not online.");
this.sendReply("If you want to continue, use: /customavatar forceset, " + hash);
return;
}
/* falls through */
case 'forceset':
if (user.avatarCooldown && !this.can('pban')) {
var milliseconds = (Date.now() - user.avatarCooldown);
var seconds = ((milliseconds / 1000) % 60);
var minutes = ((seconds / 60) % 60);
var remainingTime = Math.round(seconds - (5 * 60));
if (((Date.now() - user.avatarCooldown) <= 5 * 60 * 1000)) return this.sendReply("You must wait " + (remainingTime - remainingTime * 2) + " seconds before setting another avatar.");
}
user.avatarCooldown = Date.now();
var hash = parts[1].trim();
if (!pendingAdds[hash]) return this.sendReply("Invalid hash.");
var userid = pendingAdds[hash].userid;
var avatar = pendingAdds[hash].avatar;
delete pendingAdds[hash];
require('child_process').execFile('bash', ['-c', script, '-', avatar, './config/avatars/' + userid], function (e, out, err) {
if (e) {
this.sendReply(userid + "'s custom avatar failed to be set. Script output:");
(out + err).split('\n').forEach(this.sendReply.bind(this));
return;
}
reloadCustomAvatars();
var targetUser = Users.getExact(userid);
if (targetUser) targetUser.avatar = Config.customavatars[userid];
this.sendReply(userid + "'s custom avatar has been set.");
//Users.messageSeniorStaff(userid+' has received a custom avatar from '+user.name);
Rooms.rooms.staff.add(userid+' has received a custom avatar from '+user.name);
room.update();
}.bind(this));
break;
case 'remove':
case 'delete':
var userid = toId(parts[1]);
if (!this.can('pban') && Gold.hasBadge(toId(user.name),'vip') && userid !== user.userid) return false;
if (!Config.customavatars[userid]) return this.sendReply(userid + " does not have a custom avatar.");
if (Config.customavatars[userid].toString().split('.').slice(0, -1).join('.') !== userid)
return this.sendReply(userid + "'s custom avatar (" + Config.customavatars[userid] + ") cannot be removed with this script.");
var targetUser = Users.getExact(userid);
if (targetUser) targetUser.avatar = 1;
fs.unlink('./config/avatars/' + Config.customavatars[userid], function (e) {
if (e) return this.sendReply(userid + "'s custom avatar (" + Config.customavatars[userid] + ") could not be removed: " + e.toString());
delete Config.customavatars[userid];
this.sendReply(userid + "'s custom avatar removed successfully");
}.bind(this));
break;
default:
return this.sendReply("Invalid command. Valid commands are `/customavatar set, user, avatar` and `/customavatar delete, user`.");
}
}
};
|
'use strict';
angular.module("ngLocale", [], ["$provide", function ($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"\u043a\u04c0\u0438\u0440\u0430\u043d\u0430\u043d \u0434\u0435",
"\u043e\u0440\u0448\u043e\u0442\u0430\u043d \u0434\u0435",
"\u0448\u0438\u043d\u0430\u0440\u0438\u043d \u0434\u0435",
"\u043a\u0445\u0430\u0430\u0440\u0438\u043d \u0434\u0435",
"\u0435\u0430\u0440\u0438\u043d \u0434\u0435",
"\u043f\u04c0\u0435\u0440\u0430\u0441\u043a\u0430\u043d \u0434\u0435",
"\u0448\u043e\u0442 \u0434\u0435"
],
"ERANAMES": [
"BCE",
"CE"
],
"ERAS": [
"BCE",
"CE"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u044f\u043d\u0432\u0430\u0440\u044c",
"\u0444\u0435\u0432\u0440\u0430\u043b\u044c",
"\u043c\u0430\u0440\u0442",
"\u0430\u043f\u0440\u0435\u043b\u044c",
"\u043c\u0430\u0439",
"\u0438\u044e\u043d\u044c",
"\u0438\u044e\u043b\u044c",
"\u0430\u0432\u0433\u0443\u0441\u0442",
"\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044c",
"\u043e\u043a\u0442\u044f\u0431\u0440\u044c",
"\u043d\u043e\u044f\u0431\u0440\u044c",
"\u0434\u0435\u043a\u0430\u0431\u0440\u044c"
],
"SHORTDAY": [
"\u043a\u04c0\u0438\u0440\u0430\u043d\u0430\u043d \u0434\u0435",
"\u043e\u0440\u0448\u043e\u0442\u0430\u043d \u0434\u0435",
"\u0448\u0438\u043d\u0430\u0440\u0438\u043d \u0434\u0435",
"\u043a\u0445\u0430\u0430\u0440\u0438\u043d \u0434\u0435",
"\u0435\u0430\u0440\u0438\u043d \u0434\u0435",
"\u043f\u04c0\u0435\u0440\u0430\u0441\u043a\u0430\u043d \u0434\u0435",
"\u0448\u043e\u0442 \u0434\u0435"
],
"SHORTMONTH": [
"\u044f\u043d\u0432",
"\u0444\u0435\u0432",
"\u043c\u0430\u0440",
"\u0430\u043f\u0440",
"\u043c\u0430\u0439",
"\u0438\u044e\u043d",
"\u0438\u044e\u043b",
"\u0430\u0432\u0433",
"\u0441\u0435\u043d",
"\u043e\u043a\u0442",
"\u043d\u043e\u044f",
"\u0434\u0435\u043a"
],
"STANDALONEMONTH": [
"\u044f\u043d\u0432\u0430\u0440\u044c",
"\u0444\u0435\u0432\u0440\u0430\u043b\u044c",
"\u043c\u0430\u0440\u0442",
"\u0430\u043f\u0440\u0435\u043b\u044c",
"\u043c\u0430\u0439",
"\u0438\u044e\u043d\u044c",
"\u0438\u044e\u043b\u044c",
"\u0430\u0432\u0433\u0443\u0441\u0442",
"\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044c",
"\u043e\u043a\u0442\u044f\u0431\u0440\u044c",
"\u043d\u043e\u044f\u0431\u0440\u044c",
"\u0434\u0435\u043a\u0430\u0431\u0440\u044c"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "y MMMM d, EEEE",
"longDate": "y MMMM d",
"medium": "y MMM d HH:mm:ss",
"mediumDate": "y MMM d",
"mediumTime": "HH:mm:ss",
"short": "y-MM-dd HH:mm",
"shortDate": "y-MM-dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20bd",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "ce-ru",
"localeID": "ce_RU",
"pluralCat": function (n, opt_precision) {
var i = n | 0;
var vf = getVF(n, opt_precision);
if (i == 1 && vf.v == 0) {
return PLURAL_CATEGORY.ONE;
}
return PLURAL_CATEGORY.OTHER;
}
});
}]);
|
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
src: '<%= jshint.src %>'
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
src: [
'src/**/*.js',
'*.js'
],
json: [
'src/**/*.json',
'*.json'
]
}
});
require('load-grunt-tasks')(grunt);
// Set's up linting task
grunt.registerTask('lint', [
'jshint:src',
'jshint:json',
'jscs:src'
]);
// Test task, to run tests for the project
grunt.registerTask('test', ['lint']);
grunt.registerTask('default', ['test']);
};
|
// @flow
import { round } from 'lodash';
import type { MeasurablePercentile, MeasurablePercentilePoint, GraphData } from './types/graphing';
export default (percentiles: MeasurablePercentile[], scale: number): GraphData => {
const angleIncrement = (2 * Math.PI) / percentiles.length;
const startAngle = (3 * Math.PI) / 2;
const points: MeasurablePercentilePoint[] = [];
const factors = [];
let i = 0;
percentiles.forEach((percentile) => {
const angle = startAngle + (i * angleIncrement);
i += 1;
points.push(Object.assign({}, percentile, {
point: {
x: round(scale * Math.cos(angle), 2),
y: round(scale * Math.sin(angle), 2),
},
}));
factors.push(percentile.percentile / 100);
});
return {
points,
factors,
};
};
|
define("ARE.RectAdjust", {
ctor: function (option) {
this.min = option.min;
this.max = option.max;
this.value = option.value;
this.change = option.change;
this.renderTo = option.renderTo;
this.fillStyle = option.fillStyle;
this.canvas = document.createElement("canvas");
this.canvas.width = 140;
this.canvas.height = 16;
this.canvas.style.cssText = "border:1px solid black;";
this.ctx = this.canvas.getContext("2d");
this.renderTo.appendChild(this.canvas);
this.render(160 * (this.value - this.min) / (this.max - this.min));
this.offset = this.canvas.getBoundingClientRect();
var self = this;
var isMouseDown = false;
this.canvas.addEventListener("mousedown", function (evt) {
isMouseDown = true;
var x = evt.pageX - self.offset.left;
var y = evt.pageY - self.offset.top;
self.value = self.min + (self.max - self.min ) * x / 140;
if (self.value > self.max) self.value = self.max;
if (self.value < self.min) self.value = self.min;
self.change(self.value);
self.render(x);
evt.preventDefault();
evt.stopPropagation();
}, false)
this.canvas.addEventListener("mousemove", function (evt) {
if (isMouseDown) {
var x = evt.pageX - self.offset.left;
var y = evt.pageY - self.offset.top;
self.value = self.min +(self.max - self.min ) * x / 140;
if (self.value > self.max) self.value = self.max;
if (self.value < self.min) self.value = self.min;
self.change(self.value);
self.render(x);
evt.preventDefault();
evt.stopPropagation();
}
}, false)
document.addEventListener("mouseup", function (evt) {
isMouseDown = false;
}, false)
},
render: function (x) {
this.ctx.fillStyle = this.fillStyle;
this.ctx.clearRect(0, 0, 500, 500)
this.ctx.beginPath();
this.ctx.fillRect(0, 0, x, 60)
}
})
|
/* globals console, document, Image, window, L */
/* globals enableTooltips, pmapShared */
/* exported pmapLayerControl */
const pmapLayerControl = (function() {
'use strict';
const {loadJSON, popupHTML, setPopupGlobals, weatherLink} = pmapShared;
const BLM_CA_NLCS_Prefix = 'https://www.blm.gov/nlcs_web/sites/ca/st/en/prog/nlcs/';
const USFS_Prefix = 'https://www.fs.usda.gov/';
const USFS_NM_Prefix = 'https://www.fs.fed.us/visit/';
const Wikipedia_Prefix = 'https://en.wikipedia.org/wiki/';
const Wilderness_Prefix = 'https://wilderness.net/visit-wilderness/?ID=';
let globalMap;
let currentBaseLayer;
let lcItemFitLink;
const lcItemHoverColor = 'rgb(255, 255, 224)';
const menuDisplayedIcon = ' \u25BC';
/*
\uFE0E is a variation selector to indicate that the preceding character - the
black right-pointing triangle (\u25B6) - should be rendered text-style rather
than emoji-style. If the variation selector isn't specified, desktop browsers
seem to default to text-style while mobile browsers seem to default to emoji-
style. [http://www.unicode.org/Public/UNIDATA/StandardizedVariants.txt]
*/
const menuCollapsedIcon = ' \u25B6\uFE0E';
const addFunctions = {};
function textLink(url, text)
{
const link = document.createElement('a');
link.href = url;
link.appendChild(document.createTextNode(text));
return link;
}
function wikipediaLink(w)
{
return textLink(Wikipedia_Prefix + w, 'W');
}
function fitLink(fitBounds, className)
{
const img = new Image();
img.alt = 'Zoom To Fit';
img.src = 'ztf.svg';
img.className = className;
img.addEventListener('click', fitBounds);
return img;
}
function popupFitLink(layer)
{
function fitBounds(event)
{
event.preventDefault();
globalMap.fitBounds(layer.closePopup().getBounds());
}
return fitLink(fitBounds, 'popupZtf');
}
function raiseLink(layer)
{
function bringToFront(event)
{
event.preventDefault();
layer.closePopup().bringToFront();
}
const a = document.createElement('a');
a.href = '#';
a.className = 'bringToFront';
a.appendChild(document.createTextNode('\u2B06\uFE0F'));
a.addEventListener('click', bringToFront);
return a;
}
function lowerLink(layer)
{
function bringToBack(event)
{
event.preventDefault();
layer.closePopup().bringToBack();
}
const a = document.createElement('a');
a.href = '#';
a.className = 'bringToBack';
a.appendChild(document.createTextNode('\u2B07\uFE0F'));
a.addEventListener('click', bringToBack);
return a;
}
function dynamicWeatherLink(layer)
{
const a = document.createElement('a');
function setWxLink()
{
const ll = layer.getPopup().getLatLng();
a.href = weatherLink(ll.lng.toFixed(6), ll.lat.toFixed(6));
}
a.href = '#';
a.className = 'wxLink';
a.appendChild(document.createTextNode('\u26C5'));
a.addEventListener('click', setWxLink);
return a;
}
function bindPopup(popupDiv, layer)
{
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(popupFitLink(layer));
popupDiv.appendChild(dynamicWeatherLink(layer));
popupDiv.appendChild(lowerLink(layer));
popupDiv.appendChild(raiseLink(layer));
layer.bindPopup(popupDiv, {maxWidth: 600});
}
function addNameMap(item)
{
if (item.order)
{
item.nameMap = {};
for (const id of item.order)
{
const child = item.items[id];
item.nameMap[child.name] = child;
addNameMap(child);
}
}
}
function delNameMap(item)
{
if (item.order)
{
delete item.nameMap;
for (const id of item.order)
delNameMap(item.items[id]);
}
}
function extendBounds(item, layer)
{
const bounds = layer.getBounds();
if (item.bounds)
item.bounds.extend(bounds);
else
item.bounds = L.latLngBounds(bounds.getSouthWest(), bounds.getNorthEast());
}
function assignLayer(item, namePath, layer, featureProperties)
{
let nextItem;
const lastName = namePath.pop();
const flags = featureProperties && featureProperties.flags || 0;
const setBounds = (flags & 1) !== 0;
const skipBounds = (flags & 2) !== 0;
if (!item.nameMap) {
console.log('assignLayer failed: "' + item.name + '" doesn\'t have a name map!');
return;
}
for (const name of namePath)
{
if (!(nextItem = item.nameMap[name])) {
console.log('assignLayer failed to get from "' + item.name + '" to "' + name + '"');
return;
}
item = nextItem;
if (!item.nameMap) {
console.log('assignLayer failed: "' + item.name + '" doesn\'t have a name map!');
return;
}
if (!skipBounds)
extendBounds(item, layer);
}
if (!(nextItem = item.nameMap[lastName])) {
console.log('assignLayer failed to get from "' + item.name + '" to "' + lastName + '"');
return;
}
item = nextItem;
if (setBounds) {
if (!item.nameMap) {
console.log('assignLayer failed: "' + item.name + '" doesn\'t have a name map!');
return;
}
extendBounds(item, layer);
}
else if (item.nameMap) {
console.log('assignLayer failed: "' + item.name + '" has a name map!');
return;
}
if (item.layer) {
console.log('assignLayer failed: "' + item.name + '" already has a layer!');
return;
}
item.layer = layer;
}
addFunctions.default = function(geojson)
{
return L.geoJSON(geojson, {style: {color: '#FF4500'/* OrangeRed */}});
};
addFunctions.add_BLM_CA_Districts = function(geojson, lcItem)
{
const style = {
'Northern California District': {color: '#4169E1'}, // RoyalBlue
'Central California District': {color: '#1E90FF'}, // DodgerBlue
'California Desert District': {color: '#00BFFF'}, // DeepSkyBlue
};
function getStyle(feature)
{
return style[feature.properties.parent] || {};
}
function addPopup(feature, layer)
{
const name = feature.properties.name.slice(0, -13); // strip trailing " Field Office"
const parent = feature.properties.parent;
const bold = document.createElement('b');
bold.appendChild(document.createTextNode('BLM ' + name));
const popupDiv = document.createElement('div');
popupDiv.className = 'popupDiv blmPopup';
popupDiv.appendChild(bold);
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(document.createTextNode('(' + parent + ')'));
bindPopup(popupDiv, layer);
assignLayer(lcItem, [parent, feature.properties.name], layer);
}
return L.geoJSON(geojson, {onEachFeature: addPopup, style: getStyle});
};
function officeIcon()
{
return L.divIcon({
className: 'officeIcon',
iconSize: [26, 20],
popupAnchor: [0, -4],
html: '<svg xmlns="http://www.w3.org/2000/svg" width="26" height="20" viewBox="0 0 26 20">' +
'<path fill="cyan" stroke="blue" stroke-width="2" ' +
'd="M 13,1 L 1,10 3,10 3,19 11,19 11,10 15,10 15,19 23,19 23,10 25,10 Z" /></svg>'
});
}
function zoomTo(ll)
{
return function() {
globalMap.setView(ll, Math.min(globalMap.getMaxZoom(), 18));
};
}
addFunctions.add_BLM_Offices = function(geojson)
{
function addPopup(feature, latlng)
{
const name = feature.properties.name;
const html = '<div class="popupDiv blmPopup"><b>BLM ' + name + '</b></div>';
return L.marker(latlng, {icon: officeIcon()})
.bindPopup(html, {maxWidth: 600})
.on('dblclick', zoomTo(latlng));
}
return L.geoJSON(geojson, {pointToLayer: addPopup});
};
addFunctions.add_BLM_Lands = function(geojson, lcItem)
{
const USFS_Style = {color: '#008000'}; // Green
const BLM_Style = {color: '#00008B'}; // DarkBlue
function getStyle(feature)
{
if (feature.properties.agency === 'USFS')
return USFS_Style;
return BLM_Style;
}
function addPopup(feature, layer)
{
const p = feature.properties;
const name = p.name;
const agency = p.agency;
const link = document.createElement('a');
link.href = BLM_CA_NLCS_Prefix + p.BLM;
if (name.length < 23) {
link.appendChild(document.createTextNode(name + ' ' + p.D));
} else {
link.appendChild(document.createTextNode(name));
link.appendChild(document.createElement('br'));
link.appendChild(document.createTextNode(p.D));
}
const bold = document.createElement('b');
bold.appendChild(link);
bold.appendChild(document.createTextNode(' ['));
bold.appendChild(wikipediaLink(p.W));
bold.appendChild(document.createTextNode(']'));
const popupDiv = document.createElement('div');
popupDiv.className = 'popupDiv blmPopup';
popupDiv.appendChild(bold);
const namePath = [name + ' ' + p.D];
if (agency) {
popupDiv.appendChild(document.createElement('br'));
if (agency === 'USFS') {
namePath.push('Forest Service Lands');
if (p.FS) {
popupDiv.appendChild(document.createTextNode(
'This part is managed by the '));
popupDiv.appendChild(textLink(USFS_NM_Prefix + p.FS, 'Forest Service'));
popupDiv.appendChild(document.createTextNode(':'));
} else
popupDiv.appendChild(document.createTextNode(
'This part is managed by the Forest Service:'));
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(textLink(USFS_Prefix + p.NF, p.NFW.replace(/_/g, ' ')));
popupDiv.appendChild(document.createTextNode(' ['));
popupDiv.appendChild(wikipediaLink(p.NFW));
popupDiv.appendChild(document.createTextNode(']'));
} else {
namePath.push(agency + ' Lands');
popupDiv.appendChild(document.createTextNode(
'This part is managed by the ' + agency + '.'));
}
}
bindPopup(popupDiv, layer);
assignLayer(lcItem, namePath, layer);
}
return L.geoJSON(geojson, {onEachFeature: addPopup, style: getStyle});
};
addFunctions.add_BLM_Wilderness = function(geojson, lcItem)
{
const style = {
BLM: {color: '#FF8C00'}, // DarkOrange
FWS: {color: '#FFA07A'}, // LightSalmon
NPS: {color: '#FFD700'}, // Gold
USFS: {color: '#808000'}, // Olive
};
function getStyle(feature)
{
return style[feature.properties.agency] || {};
}
function addPopup(feature, layer)
{
const p = feature.properties;
const name = p.name + ' Wilderness';
const agency = p.agency;
const date = p.D;
const namePath = [name];
if (p.m)
namePath.push(date + ' ' + agency);
const bold = document.createElement('b');
bold.appendChild(textLink(Wilderness_Prefix + p.id, name));
const popupDiv = document.createElement('div');
popupDiv.className = 'popupDiv blmPopup';
popupDiv.appendChild(bold);
popupDiv.appendChild(document.createTextNode(' (' + agency + ')'));
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(document.createTextNode('Designated ' + date));
bindPopup(popupDiv, layer);
assignLayer(lcItem, namePath, layer);
}
return L.geoJSON(geojson, {onEachFeature: addPopup, style: getStyle});
};
addFunctions.add_BLM_WSA = function(geojson, lcItem)
{
function addPopup(feature, layer)
{
const p = feature.properties;
const bold = document.createElement('b');
bold.appendChild(document.createTextNode(p.name + ' Wilderness Study Area'));
const popupDiv = document.createElement('div');
popupDiv.className = 'popupDiv blmPopup';
popupDiv.appendChild(bold);
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(document.createTextNode('(' + p.code + ')'));
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(document.createTextNode('BLM Recommendation: ' + p.rcmnd));
bindPopup(popupDiv, layer);
assignLayer(lcItem, [p.name], layer);
}
return L.geoJSON(geojson, {onEachFeature: addPopup, style: {color: '#000000'}});
};
addFunctions.add_BLM_WSA_Released = function(geojson, lcItem)
{
function addPopup(feature, layer)
{
const p = feature.properties;
const bold = document.createElement('b');
bold.appendChild(document.createTextNode(p.name + ' WSA (Released)'));
const popupDiv = document.createElement('div');
popupDiv.className = 'popupDiv blmPopup';
popupDiv.appendChild(bold);
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(document.createTextNode('(' + p.code + ')'));
bindPopup(popupDiv, layer);
assignLayer(lcItem, [p.name], layer);
}
return L.geoJSON(geojson, {onEachFeature: addPopup, style: {color: '#A52A2A'/* Brown */}});
};
function appendName(name, node)
{
const parts = name.split('|');
let lineBreak = node.lastChild !== null;
for (const part of parts)
{
if (lineBreak)
node.appendChild(document.createElement('br'));
else
lineBreak = true;
node.appendChild(document.createTextNode(part));
}
return parts.join(' ');
}
addFunctions.add_NPS = function(geojson, lcItem)
{
function addPopup(feature, layer)
{
const p = feature.properties;
const link = document.createElement('a');
link.href = 'https://www.nps.gov/' + p.code + '/index.htm';
p.name = appendName(p.name, link);
const bold = document.createElement('b');
bold.appendChild(link);
bold.appendChild(document.createTextNode(' ['));
bold.appendChild(wikipediaLink(p.W || p.name.replace(/ /g, '_')));
bold.appendChild(document.createTextNode(']'));
const popupDiv = document.createElement('div');
popupDiv.className = 'popupDiv blmPopup';
popupDiv.appendChild(bold);
const namePath = [p.name];
if (p.name2) {
p.name2 = appendName(p.name2, popupDiv);
namePath.push(p.name2);
if (p.W2) {
popupDiv.appendChild(document.createTextNode(' ['));
popupDiv.appendChild(wikipediaLink(p.W2));
popupDiv.appendChild(document.createTextNode(']'));
}
}
bindPopup(popupDiv, layer);
assignLayer(lcItem, namePath, layer, p);
}
return L.geoJSON(geojson, {onEachFeature: addPopup, style: {color: '#FFFF00'/* Yellow */}});
};
function peakIcon(p)
{
const fill = p.emblem ? 'magenta' : p.mtneer ? 'cyan' : 'white';
const stroke = p.climbed ? 'green' : 'red';
return L.divIcon({
className: 'peakIcon',
iconSize: [20, 26],
popupAnchor: [0, -8],
html: '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="26" viewBox="0 0 20 26">' +
'<path fill="' + fill + '" stroke="' + stroke + '" stroke-width="3" ' +
'd="M 10,2 L 1,19 19,19 Z" /></svg>'
});
}
addFunctions.addPeakOverlay = function(geojson)
{
setPopupGlobals(geojson);
function addPeak(feature, latlng)
{
const p = feature.properties;
return L.marker(latlng, {icon: peakIcon(p)})
.bindPopup(popupHTML(latlng.lng, latlng.lat, p))
.on('popupopen', e => enableTooltips(e.popup.getElement(), true))
.on('dblclick', zoomTo(latlng));
}
return L.geoJSON(geojson, {pointToLayer: addPeak});
};
addFunctions.add_UC_Reserve = function(geojson)
{
function addPopup(feature, layer)
{
const p = feature.properties;
const bold = document.createElement('b');
bold.appendChild(document.createTextNode(p.name));
if (p.name2) {
bold.appendChild(document.createElement('br'));
bold.appendChild(document.createTextNode(p.name2));
}
const popupDiv = document.createElement('div');
popupDiv.className = 'popupDiv blmPopup';
popupDiv.appendChild(bold);
popupDiv.appendChild(document.createElement('br'));
popupDiv.appendChild(document.createTextNode('(' + p.campus + ')'));
bindPopup(popupDiv, layer);
}
return L.geoJSON(geojson, {onEachFeature: addPopup, style: {color: '#FF00FF'/* Magenta */}});
};
function getTop(div)
{
let top = div.offsetTop;
const body = document.body;
while (div.offsetParent !== body)
{
div = div.offsetParent;
top += div.offsetTop;
}
return top;
}
function toggleLayerMenu(event)
{
const arrow = event.currentTarget;
const menu = arrow.parentNode.nextSibling;
const lcDiv = document.getElementById('layerControl');
const scDiv = document.getElementById('scaleControl');
const lcTop = getTop(lcDiv);
const scTop = getTop(scDiv);
const maxHeight = Math.max(scTop - lcTop - 20, 100);
const scrollTop = lcDiv.scrollTop;
lcDiv.style.height = 'auto';
if (menu.style.display === 'block') {
menu.style.display = 'none';
arrow.firstChild.nodeValue = menuCollapsedIcon;
} else {
menu.style.display = 'block';
arrow.firstChild.nodeValue = menuDisplayedIcon;
}
if (lcDiv.offsetHeight > maxHeight) {
lcDiv.style.height = maxHeight + 'px';
lcDiv.scrollTop = scrollTop;
}
}
function clickArrow(event)
{
event.currentTarget.parentNode.firstChild.click();
}
function addArrow(nameSpan)
{
const arrow = document.createElement('span');
arrow.className = 'lcArrow';
arrow.appendChild(document.createTextNode(menuCollapsedIcon));
arrow.addEventListener('click', toggleLayerMenu);
const parent = nameSpan.parentNode;
parent.insertBefore(arrow, parent.firstChild);
nameSpan.addEventListener('click', clickArrow);
}
function menuHeader(parent, text)
{
const span = document.createElement('span');
span.className = 'lcName';
span.appendChild(document.createTextNode(text));
const header = parent.appendChild(document.createElement('div'));
header.className = 'lcHeader lcItem';
header.appendChild(span);
addArrow(span);
const section = parent.appendChild(document.createElement('div'));
section.className = 'lcSection';
return section;
}
function lcItemFitBounds(event)
{
event.preventDefault();
const item = event.currentTarget.parentNode.lcItem;
if (item.bounds)
globalMap.fitBounds(item.bounds);
else if (item.layer)
globalMap.fitBounds(item.layer.closePopup().getBounds());
else if (item.featureGroup)
globalMap.fitBounds(item.featureGroup.getBounds());
}
function showZoomToFit(event)
{
const div = event.currentTarget;
if (lcItemFitLink.parentNode !== div)
{
div.style.paddingRight = '8px';
div.appendChild(lcItemFitLink);
}
}
function hideZoomToFit(event)
{
const div = event.currentTarget;
if (lcItemFitLink.parentNode === div)
{
div.style.paddingRight = '23px';
div.removeChild(lcItemFitLink);
}
}
function addZoomToFitHandlers(item)
{
const itemDiv = item.div;
const bgColor = window.getComputedStyle(itemDiv).backgroundColor;
if (bgColor === lcItemHoverColor)
itemDiv.appendChild(lcItemFitLink);
else
itemDiv.style.paddingRight = '23px';
itemDiv.addEventListener('mouseenter', showZoomToFit);
itemDiv.addEventListener('mouseleave', hideZoomToFit);
/*
Tapping an element in a mobile browser triggers the following sequence
of events: touchstart, touchmove, touchend, mouseover, mouseenter,
mousemove, mousedown, mouseup, and click. However, "if the contents of
the page changes" during the handling of the mouseover, mouseenter, or
mousemove events, the subsequent events (mousedown, mouseup, and click)
are not fired!
So in a mobile environment, when a menu item is first tapped, the
mouseenter handler (showZoomToFit) would append the zoom-to-fit link
to the menu item's div, and since that changes the contents of the
page, the click event would not occur and any associated submenu would
not open or close. When the item is tapped again, the zoom-to-fit link
will already have been added, and so the click will fire, and the
submenu will open or close.
To avoid having to tap twice, we'll handle the initial touchstart event
and add the zoom-to-fit link in that handler so that the subsequent
mouseenter handler won't change the page, thus allowing the click to fire.
Note that currently (3/10/2017), it is sometimes possible to tap an
element such that only the mouse events fire but not the touch events!
This occurs in mobile versions of both Firefox and Safari (I haven't
checked other browsers), and it appears to occur only with menu items
whose text spans more than one line, e.g. Berryessa Snow Mountain
National Monument, and especially when tapping the second line of such
items. When that happens, a second tap will be necessary to open or
close any associated submenu.
*/
itemDiv.addEventListener('touchstart', showZoomToFit);
if (item.order)
for (const id of item.order)
addZoomToFitHandlers(item.items[id]);
}
function checkUpToFileParent(item)
{
while (item !== item.fileParent)
{
item = item.parent;
item.checkbox.checked = true;
}
}
function checkSubtree(topItem)
{
for (const id of topItem.order)
{
const item = topItem.items[id];
if (item.order)
checkSubtree(item);
item.checkbox.checked = true;
}
}
function isCheckedToFileParent(item)
{
while (item !== item.fileParent)
{
item = item.parent;
if (!item.checkbox.checked)
return false;
}
return true;
}
function addLayersToMap(item, extendBounds)
{
if (item.layer) {
item.layer.addTo(globalMap);
if (extendBounds)
extendBounds(item.layer.getBounds());
}
if (item.order) {
for (const id of item.order)
{
const child = item.items[id];
if (child.checkbox.checked)
addLayersToMap(child, extendBounds);
}
} else if (item.featureGroup) {
item.featureGroup.addTo(globalMap);
if (extendBounds)
extendBounds(item.featureGroup.getBounds());
}
}
function removeLayersFromMap(item)
{
if (item.layer)
item.layer.remove();
if (item.order) {
for (const id of item.order)
{
const child = item.items[id];
if (child.checkbox.checked)
removeLayersFromMap(child);
}
} else if (item.featureGroup)
item.featureGroup.remove();
}
function addCheckboxClickHandler(item)
{
const checkbox = item.checkbox;
const fileParent = item.fileParent;
function addWrapper(geojson)
{
addNameMap(fileParent);
fileParent.featureGroup = fileParent.add(geojson, fileParent);
delNameMap(fileParent);
const sizeSpan = fileParent.div.lastChild;
sizeSpan.parentNode.removeChild(sizeSpan);
if (!lcItemFitLink)
lcItemFitLink = fitLink(lcItemFitBounds, 'lcZtf');
addZoomToFitHandlers(fileParent);
if (fileParent.checkbox.checked)
if (item.mapBounds) {
addLayersToMap(fileParent, item.mapBounds.extend);
item.mapBounds.delSetter(item);
} else
addLayersToMap(fileParent);
}
function clickHandler()
{
if (fileParent.featureGroup)
{
if (!isCheckedToFileParent(item))
return;
if (checkbox.checked)
addLayersToMap(item);
else
removeLayersFromMap(item);
}
else if (!checkbox.checked)
return;
else if (fileParent.featureGroup === undefined)
{
checkUpToFileParent(item);
if (item.order)
checkSubtree(item);
const progressBar = document.createElement('progress');
fileParent.div.insertBefore(progressBar, fileParent.div.lastChild);
progressBar.max = 100;
progressBar.value = 0;
loadJSON(fileParent.fileName, addWrapper, undefined, progressBar);
fileParent.featureGroup = null;
}
else if (item.mapBounds)
item.mapBounds.delSetter(item);
}
checkbox.addEventListener('click', clickHandler);
}
function getPathStr(path, id)
{
path.push(id);
const pathStr = path.join('/');
path.pop();
return pathStr;
}
function validateItem(item, path, id)
{
if (item.parent.fileParent)
{
if (item.add) {
console.log(getPathStr(path, id) + ': Cannot have an add function within a file!');
return false;
}
if (item.size) {
console.log(getPathStr(path, id) + ': Cannot have a file within a file!');
return false;
}
item.fileParent = item.parent.fileParent;
return true;
}
if (item.add)
{
const funcName = 'add' + item.add;
const addFunc = addFunctions[funcName];
if (typeof addFunc !== 'function') {
console.log(getPathStr(path, id) + ': "' + funcName + '" is not a function!');
return false;
}
item.add = addFunc;
}
else if (item.parent.add)
item.add = item.parent.add;
if (item.size)
{
item.fileName = 'json/' + getPathStr(path, id) + '.json';
item.fileParent = item;
if (!item.add)
item.add = addFunctions.default;
}
return true;
}
function addOverlays(parentItem, parentDiv, path)
{
for (const id of parentItem.order)
{
const item = parentItem.items[id];
item.parent = parentItem;
if (!validateItem(item, path, id)) continue;
const nameSpan = document.createElement('span');
nameSpan.className = 'lcName';
item.name = appendName(item.name, nameSpan);
const itemDiv = document.createElement('div');
itemDiv.className = 'lcItem';
itemDiv.appendChild(nameSpan);
if (item.size)
{
const sizeSpan = document.createElement('span');
sizeSpan.appendChild(document.createTextNode('(' + item.size + ')'));
itemDiv.appendChild(sizeSpan);
}
if (item.fileParent)
{
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = false;
itemDiv.insertBefore(checkbox, nameSpan);
if (!item.items)
itemDiv.style.paddingLeft = '18px';
itemDiv.lcItem = item;
item.div = itemDiv;
item.checkbox = checkbox;
addCheckboxClickHandler(item);
}
parentDiv.appendChild(itemDiv);
if (item.items)
{
const childDiv = document.createElement('div');
childDiv.className = 'lcMenu';
path.push(id);
addOverlays(item, childDiv, path);
path.pop();
parentDiv.appendChild(childDiv);
addArrow(nameSpan);
}
}
}
function getItem(path, item)
{
for (const id of path)
{
if (!item.items)
return null;
let nextItem = item.items[id];
if (!nextItem)
return null;
if (typeof nextItem === 'string') {
const subPath = nextItem.split('/');
subPath.push(id);
nextItem = getItem(subPath, item);
if (!nextItem)
return null;
}
item = nextItem;
}
return item;
}
function getItemFromPath(path, root)
{
const aliases = root.aliases;
if (aliases && aliases.hasOwnProperty(path))
path = aliases[path];
return getItem(path.split('_'), root);
}
function selectOverlays(root, paths, mapBounds)
{
for (const path of paths)
{
const item = getItem(path.split('_'), root);
if (item && item.checkbox && !item.checkbox.checked) {
mapBounds.addSetter(item);
item.checkbox.click();
}
}
}
function makeChangeBaseLayer(item)
{
return function() {
if (currentBaseLayer === item.layer) return;
if (currentBaseLayer)
currentBaseLayer.remove();
currentBaseLayer = item.layer.addTo(globalMap);
globalMap.setMaxZoom(item.maxZoom || 23);
item.input.checked = true;
};
}
function addBaseLayers(parentItem, parentDiv, path, parentMakeLayer)
{
for (const id of parentItem.order)
{
const item = parentItem.items[id];
if (!item) continue;
const nameSpan = document.createElement('span');
nameSpan.className = 'lcName';
appendName(item.name, nameSpan);
const itemDiv = document.createElement('div');
itemDiv.className = 'lcItem';
itemDiv.appendChild(nameSpan);
parentDiv.appendChild(itemDiv);
const makeLayer = item.makeLayer || parentMakeLayer;
if (item.items) {
const childDiv = document.createElement('div');
childDiv.className = 'lcMenu';
path.push(id);
addBaseLayers(item, childDiv, path, makeLayer);
path.pop();
parentDiv.appendChild(childDiv);
addArrow(nameSpan);
} else {
const input = document.createElement('input');
input.type = 'radio';
input.name = 'baselayer';
input.checked = false;
itemDiv.insertBefore(input, nameSpan);
item.input = input;
item.layer = makeLayer(item);
if (item.layer) {
const changeBaseLayer = makeChangeBaseLayer(item);
nameSpan.addEventListener('click', changeBaseLayer);
input.addEventListener('click', changeBaseLayer);
} else {
input.disabled = true;
nameSpan.style.color = 'rgb(128,128,128)';
}
}
}
}
function selectBaseLayer(root, path, defaultPath)
{
let item = getItem(path.split('_'), root);
if (!item || !item.layer) {
item = getItem(defaultPath.split('_'), root);
if (!item || !item.layer) return;
}
item.input.click();
}
function makeVersionSpec(parent, version)
{
const spec = {};
for (const k of ['attribution', 'dynamicLayers', 'exportLayers', 'opacity', 'url'])
{
if (version.hasOwnProperty(k))
spec[k] = version[k];
else if (parent.hasOwnProperty(k))
spec[k] = parent[k];
}
return spec;
}
function makeChangeVersion(parent, version)
{
return function() {
if (parent.layer === version.layer) return;
if (parent.input.checked) {
parent.layer.remove();
version.layer.addTo(globalMap);
}
parent.layer = version.layer;
version.input.checked = true;
};
}
function makeToggleTileOverlay(item)
{
const input = item.input;
return function(event)
{
if (event.currentTarget !== input)
input.checked = !input.checked;
if (input.checked)
item.layer.addTo(globalMap);
else
item.layer.remove();
};
}
function addTileOverlays(parentItem, parentDiv, path, parentMakeLayer, versionParent)
{
for (const id of parentItem.order)
{
const item = parentItem.items[id];
if (!item) continue;
const nameSpan = document.createElement('span');
nameSpan.className = 'lcName';
appendName(item.name, nameSpan);
const itemDiv = document.createElement('div');
itemDiv.className = 'lcItem';
itemDiv.appendChild(nameSpan);
const makeLayer = item.makeLayer || parentMakeLayer;
if (versionParent) {
if (!item.items) {
const input = document.createElement('input');
input.type = 'radio';
input.name = versionParent.versionID;
item.input = input;
if (item.layer) {
input.checked = true;
} else {
input.checked = false;
item.layer = makeLayer(makeVersionSpec(versionParent, item));
}
const changeVersion = makeChangeVersion(versionParent, item);
input.addEventListener('click', changeVersion);
nameSpan.addEventListener('click', changeVersion);
itemDiv.insertBefore(input, nameSpan);
itemDiv.style.paddingLeft = '18px';
}
} else if (item.url) {
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = false;
item.input = input;
item.layer = makeLayer(item);
const toggleOverlay = makeToggleTileOverlay(item);
input.addEventListener('click', toggleOverlay);
itemDiv.insertBefore(input, nameSpan);
if (!item.items) {
itemDiv.style.paddingLeft = '18px';
nameSpan.addEventListener('click', toggleOverlay);
}
}
parentDiv.appendChild(itemDiv);
if (item.items) {
const childDiv = document.createElement('div');
childDiv.className = 'lcMenu';
path.push(id);
if (versionParent)
addTileOverlays(item, childDiv, path, makeLayer, versionParent);
else if (item.url) {
item.versionID = 'V_' + path.join('_');
item.items[''] = {name: item.versionName || 'Default Rendering', layer: item.layer};
item.order.unshift('');
addTileOverlays(item, childDiv, path, makeLayer, item);
} else
addTileOverlays(item, childDiv, path, makeLayer);
path.pop();
parentDiv.appendChild(childDiv);
addArrow(nameSpan);
}
}
}
function selectTileOverlays(root, paths)
{
for (const path of paths)
{
const item = getItemFromPath(path, root);
if (item && item.input && !item.input.checked)
item.input.click();
}
}
function addPointQueries(parentItem, parentDiv)
{
let hasInput = false;
for (const id of parentItem.order)
{
const item = parentItem.items[id];
if (!item || !item.toggleQuery && !(item.items && !item.url)) continue;
const nameSpan = document.createElement('span');
nameSpan.className = 'lcName';
appendName(item.name, nameSpan);
const itemDiv = document.createElement('div');
itemDiv.className = 'lcItem';
itemDiv.appendChild(nameSpan);
if (item.toggleQuery) {
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = false;
item.queryToggle = input;
itemDiv.insertBefore(input, nameSpan);
itemDiv.style.paddingLeft = '18px';
parentDiv.appendChild(itemDiv);
nameSpan.addEventListener('click', item.toggleQuery);
input.addEventListener('click', item.toggleQuery);
hasInput = true;
} else {
const childDiv = document.createElement('div');
childDiv.className = 'lcMenu';
if (!addPointQueries(item, childDiv)) continue;
parentDiv.appendChild(itemDiv);
parentDiv.appendChild(childDiv);
addArrow(nameSpan);
}
}
return hasInput;
}
function selectGeometryQueries(root, paths)
{
for (const [path, color] of paths)
{
const item = getItemFromPath(path, root);
if (item && item.popup) {
item.popup.runGeometryQuery = true;
if (color)
item.popup.color = '#' + color.toLowerCase();
}
}
}
function selectPointQueries(root, paths)
{
for (const path of paths)
{
const item = getItemFromPath(path, root);
if (item && item.queryToggle && !item.queryToggle.checked)
item.toggleQuery();
}
}
return function(map)
{
globalMap = map;
const div = document.getElementById('layerControl');
const icon = document.getElementById('layerControlIcon');
function show()
{
div.style.display = 'block';
}
function hide()
{
div.style.display = 'none';
}
function documentTouch(event)
{
let node = event.target;
while (node && node !== div)
node = node.parentNode;
if (!node) {
document.removeEventListener('touchstart', documentTouch);
icon.addEventListener('touchstart', iconTouch);
hide();
}
}
function iconTouch(event)
{
event.preventDefault();
event.stopPropagation();
icon.removeEventListener('touchstart', iconTouch);
document.addEventListener('touchstart', documentTouch);
show();
}
icon.addEventListener('mouseenter', show);
icon.addEventListener('mouseleave', hide);
icon.addEventListener('touchstart', iconTouch);
return {
addBaseLayers(root, path, defaultPath)
{
addBaseLayers(root, menuHeader(div, 'Base Layers'), [], root.makeLayer);
selectBaseLayer(root, path, defaultPath);
},
addTileOverlays(root, overlays)
{
addTileOverlays(root, menuHeader(div, 'Tile Overlays'), [], root.makeLayer);
selectTileOverlays(root, overlays);
},
addPointQueries(root, pointQueries, geometryQueries)
{
addPointQueries(root, menuHeader(div, 'Point Queries'));
selectGeometryQueries(root, geometryQueries);
selectPointQueries(root, pointQueries);
},
addOverlays(root, overlays, mapBounds)
{
addOverlays(root, menuHeader(div, 'GeoJSON Overlays'), []);
selectOverlays(root, overlays, mapBounds);
},
};
};
})();
|
'use strict';
// Wrapper will prevent calls > n
const limit = (count, fn) => {
let counter = 0;
return (...args) => {
if (counter === count) return;
const res = fn(...args);
counter++;
return res;
};
};
// Usage
const fn = (par) => {
console.log('Function called, par: ' + par);
};
const fn2 = limit(5, fn);
fn2('first');
fn2('second');
fn2('third');
fn2('four');
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" />
, 'Group');
|
'use strict';
var util = require('util');
var assert = require('assert');
var Mysql = function(config) {
this.output = [];
this.params = [];
this.config = config || {};
};
var Postgres = require(__dirname + '/postgres');
util.inherits(Mysql, Postgres);
Mysql.prototype._myClass = Mysql;
Mysql.prototype._quoteCharacter = '`';
Mysql.prototype._arrayAggFunctionName = 'GROUP_CONCAT';
Mysql.prototype._getParameterPlaceholder = function() {
return '?';
};
Mysql.prototype._getParameterValue = function(value) {
if (Buffer.isBuffer(value)) {
value = 'x' + this._getParameterValue(value.toString('hex'));
} else {
value = Postgres.prototype._getParameterValue.call(this, value);
}
return value;
};
Mysql.prototype.visitOnDuplicate = function(onDuplicate) {
var params = [];
/* jshint boss: true */
for(var i = 0, node; node = onDuplicate.nodes[i]; i++) {
var target_col = this.visit(node);
params = params.concat(target_col + ' = ' + this.visit(node.value));
}
var result = [
'ON DUPLICATE KEY UPDATE',
params.join(', ')
];
return result;
};
Mysql.prototype.visitReturning = function() {
throw new Error('MySQL does not allow returning clause.');
};
Mysql.prototype.visitForShare = function() {
throw new Error('MySQL does not allow FOR SHARE clause.');
};
Mysql.prototype.visitCreate = function(create) {
var result = Mysql.super_.prototype.visitCreate.call(this, create);
var engine = this._queryNode.table._initialConfig.engine;
var charset = this._queryNode.table._initialConfig.charset;
if ( !! engine) {
result.push('ENGINE=' + engine);
}
if ( !! charset) {
result.push('DEFAULT CHARSET=' + charset);
}
return result;
};
Mysql.prototype.visitRenameColumn = function(renameColumn) {
var dataType = renameColumn.nodes[1].dataType || renameColumn.nodes[0].dataType;
assert(dataType, 'dataType missing for column ' + (renameColumn.nodes[1].name || renameColumn.nodes[0].name || '') +
' (CHANGE COLUMN statements require a dataType)');
return ['CHANGE COLUMN ' + this.visit(renameColumn.nodes[0]) + ' ' + this.visit(renameColumn.nodes[1]) + ' ' + dataType];
};
Mysql.prototype.visitInsert = function(insert) {
var result = Postgres.prototype.visitInsert.call(this, insert);
if (result[2] === 'DEFAULT VALUES') {
result[2] = '() VALUES ()';
}
return result;
};
Mysql.prototype.visitIndexes = function(node) {
var tableName = this.visit(this._queryNode.table.toNode())[0];
return "SHOW INDEX FROM " + tableName;
};
Mysql.prototype.visitBinary = function(binary) {
if (binary.operator === '@@') {
var self = this;
var text = '(MATCH ' + this.visit(binary.left) + ' AGAINST ';
text += this.visit(binary.right);
text += ')';
return [text];
}
return Mysql.super_.prototype.visitBinary.call(this, binary);
};
module.exports = Mysql;
|
//~ name a263
alert(a263);
//~ component a264.js
|
import { injectReducer } from 'store/reducers'
import MatchReplay from './containers/MatchContainer';
export default (store) => ({
path: 'replay-match/:matchId',
///* Async getComponent is only invoked when route matches */
getComponent (nextState, cb) {
/* Webpack - use 'require.ensure' to create a split point
and embed an async module loader (jsonp) when bundling */
require.ensure([], (require) => {
/* Webpack - use require callback to define
dependencies for bundling */
const Match = require('./containers/MatchContainer').default
const reducer = require('./modules/match').default
/* Add the reducer to the store on key 'counter' */
injectReducer(store, { key: 'match', reducer })
/* Return getComponent */
cb(null, Match)
/* Webpack named bundle */
}, 'replay-match')
}
});
|
import GraphicObject from './GraphicObject.js';
/* *********************************************************************************************** *
* Circle
* =============================================================================================== *
* REQUIRE: GraphicObject
* *********************************************************************************************** */
export default Circle;
function Circle(settings) {
settings = settings || {};
this.radius = settings.radius || 10;
GraphicObject.call(this, settings);
}
//--------------------------------------------------------------------------------------------------
Circle.prototype = Object.create(GraphicObject.prototype);
//--------------------------------------------------------------------------------------------------
Circle.prototype.constructor = Circle;
//--------------------------------------------------------------------------------------------------
Circle.prototype.shaped = function(sprite) {
this.sprite = sprite || this.sprite;
this.sprite.beginPath();
this.sprite.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
this.sprite.closePath();
}; |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define(["require","exports"],function(e,b){function c(a){"boolean"===typeof a.read?a.read={enabled:a.read}:"function"===typeof a.read?a.read={enabled:!0,reader:a.read}:a.read&&"object"===typeof a.read&&void 0===a.read.enabled&&(a.read.enabled=!0)}function d(a){"boolean"===typeof a.write?a.write={enabled:a.write}:"function"===typeof a.write?a.write={enabled:!0,writer:a.write}:a.write&&"object"===typeof a.write&&void 0===a.write.enabled&&(a.write.enabled=!0)}Object.defineProperty(b,"__esModule",{value:!0});
b.process=function(a){a.json||(a.json={});c(a.json);d(a.json);if(a.json.origins)for(var b in a.json.origins)c(a.json.origins[b]),d(a.json.origins[b]);return!0}}); |
/**
* @name appBody.controller
* @description
* The entry for the appBody component
*/
class AppBodyController {
/**
* This is initializes the appBody controller
* @param {*} AppBodyService
*/
constructor(AppBodyService) {
'ngInject';
// refs
this.AppBodyService = AppBodyService;
}
/**
* Fetch the api and get data for the searched query
*/
fetchAPI() {
this.AppBodyService
.fetchAPI(this.query)
.then((resp) => {
resp.forEach((item) => {
item.getMoreDetails = item.name.toUpperCase() === 'ARTISTS' ?
this.fetchAlbum.bind(this) : null;
});
this.musicTabs = resp;
}).catch((err) => err);
}
/**
* Fetch albums for artists
* @param {*} [artist]
* @return {promise}
*/
fetchAlbum(artist) {
return this.AppBodyService
.fetchAlbum(artist.id)
.then((resp) => {
artist.albums = resp;
}).catch((err) => {
// log error or do nothing
});
}
}
export default AppBodyController;
|
/* global app */
var log = require('bows')('topics')
var PageView = require('ampersand-infinite-scroll')
var templates = require('../../templates')
var TopicView = require('../../views/topic')
var Topic = require('../../models/topic')
var AmpersandCollection = require('ampersand-collection')
var topicKinds = require('../../../../options').kinds.topics
var _ = require('../../helpers/underscore')
var $ = require('../../helpers/jquery')
var selectedKind = 'showall'
var selectedTag = 'showall'
var selectedClosed = 'open'
var tempCollection
function filterClosed (collection, filter) {
return collection.filter(function (topic) {
return topic.closed === filter
})
}
function filterKind (collection, filter) {
if (filter !== 'showall') {
return collection.filter(function (topic) {
return topic.kind === filter
})
} else {
return collection
}
}
function filterTag (collection, filter) {
if (filter !== 'showall') {
return collection.filter(function (topic) {
return topic.tags.indexOf(filter) !== -1
})
} else {
return collection
}
}
module.exports = PageView.extend({
pageTitle: 'Topics',
template: templates.pages.topics.list,
events: {
'click [data-hook~=showall]': 'showall',
'click [data-hook~=kind-filters]': 'handleKindFilter',
'click [data-hook~=tag-filters]': 'handleTagFilter',
'click [data-hook~=closed-filters]': 'handleClosed',
'click [data-hook~=me]': 'me',
'click [data-hook~=hide]': 'hide'
},
hidden: false,
initialize: function () {
var self = this
selectedTag = 'showall'
selectedKind = 'showall'
if (this.collection.length < this.collection.data.limit) {
this.fetchCollection()
}
if (!app.tags.length) {
app.tags.fetch({success: function () {
log('got tags', app.tags.serialize())
self.render()
}})
}
},
render: function () {
var self = this
this.renderWithTemplate()
if (app.tags.length) {
self.renderTagFilters()
}
self.renderCards(tempCollection)
this.renderKindFilters()
this.renderClosedFilters()
this.queryByHook(selectedKind).classList.add('selected')
this.queryByHook(selectedTag).classList.add('selected')
tempCollection = this.collection
this.showall()
},
fetchCollection: function () {
log('Fetching topics')
var self = this
this.collection.fetchPage({
reset: true,
success: function () {
var aux = self.collection.filter(function (topic) {
return topic.closed === false
})
tempCollection = new AmpersandCollection(aux, {model: Topic})
self.render()
}
})
return false
},
renderCards: function (collection) {
if (!collection || !collection.length) {
return
}
var groups = $(this.queryByHook('topics-list')).children('div')
for (var i = 0; i < groups.length; i++) {
var columns = $(groups[i]).children('div')
columns.children('*').remove()
var collections = []
for (var j = 0; j < columns.length; j++) {
var o = new AmpersandCollection()
for (var key in collection) {
o[key] = collection[key]
}
o.models = []
collections.push(o)
}
for (var k = 0, l = 0; k < collection.models.length; k++, l = (l + 1) % collections.length) {
collections[l].models.push(collection.models[k])
}
for (var m = 0; m < columns.length; m++) {
this.renderCollection(collections[m], TopicView, columns[m])
}
}
},
renderKindFilters: function () {
var self = this
var filterContainer = $(self.queryByHook('kind-filters')) // $.hook('kind-filters')
_.each(topicKinds, function (kind) {
filterContainer.append("<li><div class='ink-button' data-hook='" + kind.id + "'>" + kind.name + '</div></li>')
})
},
handleKindFilter: function (ev) {
var kind = ev.target.getAttribute('data-hook')
tempCollection = this.collection
log('filtering by kind', kind)
var aux = filterKind(tempCollection, kind)
aux = filterClosed(aux, selectedClosed === 'closed')
aux = filterTag(aux, selectedTag)
tempCollection = new AmpersandCollection(aux, {model: Topic})
this.renderCards(tempCollection)
this.queryByHook(selectedKind).classList.remove('selected')
this.queryByHook(kind).classList.add('selected')
selectedKind = kind
return false
},
renderTagFilters: function () {
var self = this
var filterContainer = $(self.queryByHook('tag-filters'))
_.each(app.tags.serialize(), function (tag) {
filterContainer.append("<li><div class='ink-button' data-hook='" + tag.id + "'>" + tag.name + '</div></li>')
})
},
handleTagFilter: function (ev) {
var tag = ev.target.getAttribute('data-hook')
tempCollection = this.collection
log('filtering by tag', tag)
var aux = filterKind(tempCollection, selectedKind)
aux = filterClosed(aux, selectedClosed === 'closed')
aux = filterTag(aux, tag)
tempCollection = new AmpersandCollection(aux, {model: Topic})
this.renderCards(tempCollection)
this.queryByHook(selectedTag).classList.remove('selected')
this.queryByHook(tag).classList.add('selected')
selectedTag = tag
return false
},
renderClosedFilters: function () {
var self = this
var filterContainer = $(self.queryByHook('closed-filters'))
filterContainer.append("<li><div class='ink-button' data-hook='open'>Open</div></li>")
filterContainer.append("<li><div class='ink-button' data-hook='closed'>Closed</div></li>")
},
handleClosed: function (ev) {
var closed = ev.target.getAttribute('data-hook')
tempCollection = this.collection
log('filtering by closed', closed)
var aux = filterKind(tempCollection, selectedKind)
aux = filterClosed(aux, closed === 'closed')
aux = filterTag(aux, selectedTag)
tempCollection = new AmpersandCollection(aux, {model: Topic})
this.renderCards(tempCollection)
this.queryByHook(selectedClosed).classList.remove('selected')
this.queryByHook(closed).classList.add('selected')
selectedClosed = closed
return false
},
me: function () {
log('Fetching my topics')
var aux = this.collection.filter(function (topic) {
return topic.targets && topic.targets.indexOf(app.me.id) !== -1
})
aux = new AmpersandCollection(aux, {model: Topic})
this.renderCards(aux)
return false
},
showall: function () {
tempCollection = this.collection
this.renderCards(this.collection)
this.queryByHook(selectedTag).classList.remove('selected')
this.queryByHook(selectedKind).classList.remove('selected')
this.queryByHook(selectedClosed).classList.remove('selected')
this.queryByHook('showall').classList.add('selected')
selectedTag = 'showall'
selectedKind = 'showall'
return false
},
hide: function () {
if (!this.hidden) {
this.queryByHook('awesome-sidebar').style.display = 'none'
this.hidden = true
} else {
this.queryByHook('awesome-sidebar').style.display = 'block'
this.hidden = false
}
}
})
|
/* globals EmberDev */
import { context } from 'ember-environment';
import { run } from 'ember-metal';
import {
Controller,
Service,
Object as EmberObject,
Namespace
} from 'ember-runtime';
import { Route } from 'ember-routing';
import Application from '../../../system/application';
import {
Component,
setTemplates,
setTemplate,
Helper,
helper as makeHelper,
makeBoundHelper as makeHTMLBarsBoundHelper
} from 'ember-glimmer';
import { compile } from 'ember-template-compiler';
import { getDebugFunction, setDebugFunction } from 'ember-debug';
let registry, locator, application, originalLookup, originalInfo;
QUnit.module('Ember.Application Dependency Injection - default resolver', {
setup() {
originalLookup = context.lookup;
application = run(Application, 'create');
registry = application.__registry__;
locator = application.__container__;
originalInfo = getDebugFunction('info');
},
teardown() {
setTemplates({});
context.lookup = originalLookup;
run(application, 'destroy');
let UserInterfaceNamespace = Namespace.NAMESPACES_BY_ID['UserInterface'];
if (UserInterfaceNamespace) { run(UserInterfaceNamespace, 'destroy'); }
setDebugFunction('info', originalInfo);
}
});
QUnit.test('the default resolver can look things up in other namespaces', function() {
let UserInterface = context.lookup.UserInterface = Namespace.create();
UserInterface.NavigationController = Controller.extend();
let nav = locator.lookup('controller:userInterface/navigation');
ok(nav instanceof UserInterface.NavigationController, 'the result should be an instance of the specified class');
});
QUnit.test('the default resolver looks up templates in Ember.TEMPLATES', function() {
let fooTemplate = compile('foo template');
let fooBarTemplate = compile('fooBar template');
let fooBarBazTemplate = compile('fooBar/baz template');
setTemplate('foo', fooTemplate);
setTemplate('fooBar', fooBarTemplate);
setTemplate('fooBar/baz', fooBarBazTemplate);
ignoreDeprecation(() => {
equal(locator.lookupFactory('template:foo'), fooTemplate, 'resolves template:foo');
equal(locator.lookupFactory('template:fooBar'), fooBarTemplate, 'resolves template:foo_bar');
equal(locator.lookupFactory('template:fooBar.baz'), fooBarBazTemplate, 'resolves template:foo_bar.baz');
});
equal(locator.factoryFor('template:foo').class, fooTemplate, 'resolves template:foo');
equal(locator.factoryFor('template:fooBar').class, fooBarTemplate, 'resolves template:foo_bar');
equal(locator.factoryFor('template:fooBar.baz').class, fooBarBazTemplate, 'resolves template:foo_bar.baz');
});
QUnit.test('the default resolver looks up basic name as no prefix', function() {
ok(Controller.detect(locator.lookup('controller:basic')), 'locator looks up correct controller');
});
function detectEqual(first, second, message) {
ok(first.detect(second), message);
}
QUnit.test('the default resolver looks up arbitrary types on the namespace', function() {
application.FooManager = EmberObject.extend({});
detectEqual(application.FooManager, registry.resolve('manager:foo'), 'looks up FooManager on application');
});
QUnit.test('the default resolver resolves models on the namespace', function() {
application.Post = EmberObject.extend({});
ignoreDeprecation(() => {
detectEqual(application.Post, locator.lookupFactory('model:post'), 'looks up Post model on application');
});
detectEqual(application.Post, locator.factoryFor('model:post').class, 'looks up Post model on application');
});
QUnit.test('the default resolver resolves *:main on the namespace', function() {
application.FooBar = EmberObject.extend({});
ignoreDeprecation(() => {
detectEqual(application.FooBar, locator.lookupFactory('foo-bar:main'), 'looks up FooBar type without name on application');
});
detectEqual(application.FooBar, locator.factoryFor('foo-bar:main').class, 'looks up FooBar type without name on application');
});
QUnit.test('the default resolver resolves container-registered helpers', function() {
let shorthandHelper = makeHelper(() => {});
let helper = Helper.extend();
application.register('helper:shorthand', shorthandHelper);
application.register('helper:complete', helper);
let lookedUpShorthandHelper = locator.factoryFor('helper:shorthand').class;
ok(lookedUpShorthandHelper.isHelperInstance, 'shorthand helper isHelper');
let lookedUpHelper = locator.factoryFor('helper:complete').class;
ok(lookedUpHelper.isHelperFactory, 'complete helper is factory');
ok(helper.detect(lookedUpHelper), 'looked up complete helper');
});
QUnit.test('the default resolver resolves container-registered helpers via lookupFor', function() {
let shorthandHelper = makeHelper(() => {});
let helper = Helper.extend();
application.register('helper:shorthand', shorthandHelper);
application.register('helper:complete', helper);
ignoreDeprecation(() => {
let lookedUpShorthandHelper = locator.lookupFactory('helper:shorthand');
ok(lookedUpShorthandHelper.isHelperInstance, 'shorthand helper isHelper');
let lookedUpHelper = locator.lookupFactory('helper:complete');
ok(lookedUpHelper.isHelperFactory, 'complete helper is factory');
ok(helper.detect(lookedUpHelper), 'looked up complete helper');
});
});
QUnit.test('the default resolver resolves helpers on the namespace', function() {
let ShorthandHelper = makeHelper(() => {});
let CompleteHelper = Helper.extend();
let LegacyHTMLBarsBoundHelper;
expectDeprecation(() => {
LegacyHTMLBarsBoundHelper = makeHTMLBarsBoundHelper(() => {});
}, 'Using `Ember.HTMLBars.makeBoundHelper` is deprecated. Please refactor to use `Ember.Helper` or `Ember.Helper.helper`.');
application.ShorthandHelper = ShorthandHelper;
application.CompleteHelper = CompleteHelper;
application.LegacyHtmlBarsBoundHelper = LegacyHTMLBarsBoundHelper; // Must use lowered "tml" in "HTMLBars" for resolver to find this
let resolvedShorthand = registry.resolve('helper:shorthand');
let resolvedComplete = registry.resolve('helper:complete');
let resolvedLegacyHTMLBars = registry.resolve('helper:legacy-html-bars-bound');
equal(resolvedShorthand, ShorthandHelper, 'resolve fetches the shorthand helper factory');
equal(resolvedComplete, CompleteHelper, 'resolve fetches the complete helper factory');
equal(resolvedLegacyHTMLBars, LegacyHTMLBarsBoundHelper, 'resolves legacy HTMLBars bound helper');
});
QUnit.test('the default resolver resolves to the same instance, no matter the notation ', function() {
application.NestedPostController = Controller.extend({});
equal(locator.lookup('controller:nested-post'), locator.lookup('controller:nested_post'), 'looks up NestedPost controller on application');
});
QUnit.test('the default resolver throws an error if the fullName to resolve is invalid', function() {
throws(() => { registry.resolve(undefined);}, TypeError, /Invalid fullName/);
throws(() => { registry.resolve(null); }, TypeError, /Invalid fullName/);
throws(() => { registry.resolve(''); }, TypeError, /Invalid fullName/);
throws(() => { registry.resolve(''); }, TypeError, /Invalid fullName/);
throws(() => { registry.resolve(':'); }, TypeError, /Invalid fullName/);
throws(() => { registry.resolve('model'); }, TypeError, /Invalid fullName/);
throws(() => { registry.resolve('model:'); }, TypeError, /Invalid fullName/);
throws(() => { registry.resolve(':type'); }, TypeError, /Invalid fullName/);
});
QUnit.test('the default resolver logs hits if `LOG_RESOLVER` is set', function() {
if (EmberDev && EmberDev.runningProdBuild) {
ok(true, 'Logging does not occur in production builds');
return;
}
expect(3);
application.LOG_RESOLVER = true;
application.ScoobyDoo = EmberObject.extend();
application.toString = () => 'App';
setDebugFunction('info', function(symbol, name, padding, lookupDescription) {
equal(symbol, '[✓]', 'proper symbol is printed when a module is found');
equal(name, 'doo:scooby', 'proper lookup value is logged');
equal(lookupDescription, 'App.ScoobyDoo');
});
registry.resolve('doo:scooby');
});
QUnit.test('the default resolver logs misses if `LOG_RESOLVER` is set', function() {
if (EmberDev && EmberDev.runningProdBuild) {
ok(true, 'Logging does not occur in production builds');
return;
}
expect(3);
application.LOG_RESOLVER = true;
application.toString = () => 'App';
setDebugFunction('info', function(symbol, name, padding, lookupDescription) {
equal(symbol, '[ ]', 'proper symbol is printed when a module is not found');
equal(name, 'doo:scooby', 'proper lookup value is logged');
equal(lookupDescription, 'App.ScoobyDoo');
});
registry.resolve('doo:scooby');
});
QUnit.test('doesn\'t log without LOG_RESOLVER', function() {
if (EmberDev && EmberDev.runningProdBuild) {
ok(true, 'Logging does not occur in production builds');
return;
}
let infoCount = 0;
application.ScoobyDoo = EmberObject.extend();
setDebugFunction('info', (symbol, name) => infoCount = infoCount + 1);
registry.resolve('doo:scooby');
registry.resolve('doo:scrappy');
equal(infoCount, 0, 'Logger.info should not be called if LOG_RESOLVER is not set');
});
QUnit.test('lookup description', function() {
application.toString = () => 'App';
equal(registry.describe('controller:foo'), 'App.FooController', 'Type gets appended at the end');
equal(registry.describe('controller:foo.bar'), 'App.FooBarController', 'dots are removed');
equal(registry.describe('model:foo'), 'App.Foo', 'models don\'t get appended at the end');
});
QUnit.test('assertion for routes without isRouteFactory property', function() {
application.FooRoute = Component.extend();
expectAssertion(() => registry.resolve(`route:foo`), /to resolve to an Ember.Route/, 'Should assert');
});
QUnit.test('no assertion for routes that extend from Ember.Route', function() {
expect(0);
application.FooRoute = Route.extend();
registry.resolve(`route:foo`);
});
QUnit.test('deprecation warning for service factories without isServiceFactory property', function() {
expectDeprecation(/service factories must have an `isServiceFactory` property/);
application.FooService = EmberObject.extend();
registry.resolve('service:foo');
});
QUnit.test('no deprecation warning for service factories that extend from Ember.Service', function() {
expectNoDeprecation();
application.FooService = Service.extend();
registry.resolve('service:foo');
});
QUnit.test('deprecation warning for component factories without isComponentFactory property', function() {
expectDeprecation(/component factories must have an `isComponentFactory` property/);
application.FooComponent = EmberObject.extend();
registry.resolve('component:foo');
});
QUnit.test('no deprecation warning for component factories that extend from Ember.Component', function() {
expectNoDeprecation();
application.FooView = Component.extend();
registry.resolve('component:foo');
});
QUnit.test('knownForType returns each item for a given type found', function() {
application.FooBarHelper = 'foo';
application.BazQuxHelper = 'bar';
let found = registry.resolver.knownForType('helper');
// using `Object.keys` and manually confirming values over using `deepEqual`
// due to an issue in QUnit (through at least 1.20.0) that are unable to properly compare
// objects with an `undefined` constructor (like ember-metal/empty_object)
let foundKeys = Object.keys(found);
deepEqual(foundKeys, ['helper:foo-bar', 'helper:baz-qux']);
ok(found['helper:foo-bar']);
ok(found['helper:baz-qux']);
});
QUnit.test('knownForType is not required to be present on the resolver', function() {
delete registry.resolver.knownForType;
registry.resolver.knownForType('helper', () => { });
ok(true, 'does not error');
});
|
module.exports = {
assets: {
src: './src',
dist: './dist'
},
js: {
src: './src/js',
dist: './dist/js',
vendor: {
dist: 'dist/js/vendor.min.js'
}
},
webpack: {
src: './src/js/controllers',
dist: '/dist/js/controllers'
},
css: {
src: './src/sass',
dist: './dist/css'
},
jade: {
src: './views',
dist: './dist/views'
}
} |
'use strict';
function groupDataByYear() {
var dataByYear = {};
//order by year
$.each(pubdb, function(key, publication) {
if (dataByYear[publication.year] === undefined) {
dataByYear[publication.year] = [];
}
dataByYear[publication.year].push(publication);
});
//count unique people per year
$.each(dataByYear, function(year, publicationsInYear) {
var namesPerYear = [],
tmpStats = {};
$.each(publicationsInYear, function(key, publication) {
//Filter publications with only one author
if (publication.authors.length > 1) {
$.each(publication.authors, function(index, scientist) {
namesPerYear.push(scientist.name);
//calculate collaborations
// "-1" to remove author himself
if (tmpStats[scientist.name] === undefined) {
tmpStats[scientist.name] = {
'collaborations': publication.authors.length - 1,
'url': scientist.url
};
} else {
tmpStats[scientist.name].collaborations += publication.authors.length - 1;
}
});
}
});
var uniqueNamesPerYear = [],
stats = {};
$.each(namesPerYear, function(i, el) {
//add name, if it is not already in uniqueNamesPerYear
if ($.inArray(el, uniqueNamesPerYear) === -1) {
uniqueNamesPerYear.push(el);
stats[el] = {
'publications': 1,
'collaborations': tmpStats[el].collaborations,
'url': tmpStats[el].url
};
} else {
stats[el].publications++;
}
});
dataByYear[year].peoplePerYear = uniqueNamesPerYear;
dataByYear[year].stats = stats;
});
//DEBUG/DEV: print json to page to allow static file creation
//console.log(JSON.stringify(dataByYear['1995']));
return dataByYear;
}
//generate chord diagram
function drawDiagram(matrix, namesArray, stats, cb) {
//create a tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.attr('id', 'd3tooltip')
.html(function(d) {
$('#d3tooltip').css('background-color', fill(d.index));
//console.log(namesArray[d.index]);
//console.log(d.index);
var name = namesArray[d.index],
websiteHtml = (stats[name].url === undefined) ? '' : '<strong>Website: </strong><a href="' + stats[name].url + ' ">' + stats[name].url + '</a>',
tip = '<strong>Author: </strong><span>' + name + '</span></br>' +
'<strong>Publications: </strong><span>' + stats[name].publications + '</span></br>' +
'<strong>Collaborations: </strong><span>' + stats[name].collaborations + '</span></br>' +
websiteHtml;
return tip;
})
.offset([0, 0]);
//set the svg width and height and the chord radius
var vizWidth = $('.jumbotron').width();
var width = vizWidth,
height = vizWidth,
innerRadius = height * 0.31,
outerRadius = innerRadius * 1.1;
//append the svg to the #viz element
var svg = d3.select('#viz').append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
$(document).click(function(d) {
tip.hide(d);
});
svg.call(tip);
//create an chord element
var chord = d3.layout.chord()
.matrix(matrix)
.sortSubgroups(d3.descending);
//generate colors
var fill = d3.scale.category20c();
var click;
//add to g
var g = svg.selectAll('g.group')
.data(chord.groups)
.enter().append('svg:g')
.attr('class', 'group')
.on('click', function(d) {
if (d !== click) {
d3.select('.d3-tip')
.transition()
.delay(10)
.duration(200)
.style('opacity', 1);
click = d;
tip.show(d);
} else {
click = null;
}
});
//create link arcs
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
//add color and the arc to g
g.append('path')
.attr('d', arc)
.style('fill', function(d) {
return fill(d.index);
})
.style('stroke', function(d) {
return fill(d.index);
})
.attr('id', function(d) {
return d.index;
});
//color chords
function chordColor(d) {
return fill(d.source.index);
}
//add g to the svg
svg.append('g')
.attr('class', 'chord')
.selectAll('path')
.data(chord.chords)
.enter().append('path')
.attr('d', d3.svg.chord().radius(innerRadius))
.style('fill', chordColor)
.style('opacity', 1);
//fade function for the chord paths
function fade(opacity) {
return function(g, i) {
svg.selectAll('.chord path')
.filter(function(d) {
if (document.getElementById(d.source.index).id == i || document.getElementById(d.target.index).id == i) {
document.getElementById(d.source.index).nextSibling.firstChild.style.opacity = Math.abs(opacity - 1);
document.getElementById(d.target.index).nextSibling.firstChild.style.opacity = Math.abs(opacity - 1);
document.getElementById(d.source.index).nextSibling.firstChild.nextSibling.style.opacity = Math.abs(opacity - 1);
document.getElementById(d.target.index).nextSibling.firstChild.nextSibling.style.opacity = Math.abs(opacity - 1);
}
return null;
});
//.style('opacity', 1);
svg.selectAll('.chord path')
.filter(function(d) {
return d.source.index !== i &&
d.target.index !== i;
})
.transition()
.style('opacity', opacity);
};
}
function splitFunc(g, i) {
var fadeF = fade(0.1);
fadeF(g, i);
}
//call fade function on mouseover
g.on('mouseover', splitFunc)
.on('mouseout', fade(1));
var c = -1;
//erstellt Liste von Werten mit Namen als Label
//zusätzlich wird der Winkel des Labels zurückgegeben
function groupNames(d) {
c++;
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, 1, 1).map(function(v) {
return {
angle: v * k + d.startAngle + (d.endAngle - d.startAngle) / 2,
label: namesArray[c]
};
});
}
//die Namen werden um den Kreis angeordnet
var names = g.selectAll('g')
.data(groupNames)
.enter().append('g')
.attr('transform', function(d) {
return 'rotate(' + (d.angle * 180 / Math.PI - 90) + ')' + 'translate(' + outerRadius + ',0)';
});
//der Text wird hinzugefügt
names.append('text')
.attr('dx', 8)
.attr('dy', 0)
.attr('opacity', 0)
.attr('transform', function(d) {
// Beschriftung drehen wenn Kreiswinkel > 180°
return d.angle > Math.PI ?
'rotate(180)translate(-16, 0)' : null;
})
.style('text-anchor', function(d) {
return d.angle > Math.PI ? 'end' : null;
})
.text(function(d) {
if (!isNaN(d.angle)) {
return d.label;
}
return null;
});
names.append('svg:line')
.attr('x1', 1)
.attr('y1', 0)
.attr('x2', 5)
.attr('y2', 0)
.attr('opacity', 0)
.attr('stroke', '#000');
cb();
}
//redraw if sliders are used
function redrawDiagramWithFilter(isResized) {
//hide error msg
$('#error').hide();
//prevent viz from being 0
if (isResized === undefined) {
$('#viz').height(viz);
}
d3.select('#d3tooltip').remove();
d3.select('#viz svg').remove();
$('#fa-spinner').show();
//get filter values
var year = yearSlider.slider('getValue'),
numPubs = pubSlider.slider('getValue'),
collabs = collabSlider.slider('getValue');
var matrix = getStatisticsForYear(dataByYear[year], numPubs, collabs);
//check if matrix is empty
var isMatrixEmpty = true;
$.each(matrix, function(index, row) {
if (!isMatrixEmpty){
return false;
}
$.each(row, function(rowIndex, element){
if (element !== 0){
isMatrixEmpty = false;
return false;
}
});
});
if (isMatrixEmpty) {
$('#error').show();
}else {
//draw new diagram
drawDiagram(matrix, names, dataByYear[year].stats, function() {
$('#fa-spinner').hide();
viz = $('#viz').height();
});
}
}
//helperfunction, creating an array filled with values
function newFilledArray(len, val) {
var rv = new Array(len);
while (--len >= 0) {
rv[len] = val;
}
return rv;
}
var names, dataByYear, viz;
//Returns the relationship-matrix filtered by
//the number of publications numPubs and number
//of collaborations collabs
function getStatisticsForYear(dataOfYear, numPubs, numCollabs) {
var matrix = [];
//pre-fill array with zeros
for (var i = 0; i < dataOfYear.peoplePerYear.length; i++) {
matrix[i] = newFilledArray(dataOfYear.peoplePerYear.length, 0);
}
names = new Array(dataOfYear.peoplePerYear.length);
$.each(dataOfYear, function(index, publication) {
$.each(publication.authors, function(index, author) {
//add a link from each author to each other of the pub exactly ONCE
for (var i = index + 1; i < publication.authors.length; i++) {
var authorIndex = $.inArray(author.name, dataOfYear.peoplePerYear),
collaboratorIndex = $.inArray(publication.authors[i].name, dataOfYear.peoplePerYear),
authorName = author.name,
collabName = publication.authors[i].name,
authorPubs = dataOfYear.stats[authorName].publications,
collabPubs = dataOfYear.stats[collabName].publications,
authorCollabs = dataOfYear.stats[authorName].collaborations,
collabCollabs = dataOfYear.stats[collabName].collaborations;
//filter publications and collaborations
if (authorPubs >= numPubs && collabPubs >= collabPubs &&
authorCollabs >= numCollabs && collabCollabs >= numCollabs) {
//increment relation counter with each paper
matrix[authorIndex][collaboratorIndex] ++;
matrix[collaboratorIndex][authorIndex] ++;
//set names
if (names[authorIndex] === undefined) {
names[authorIndex] = authorName;
}
if (names[collaboratorIndex] === undefined) {
names[collaboratorIndex] = collabName;
}
}
}
});
});
return matrix;
}
$(document).ready(function() {
//TODO: SAVE TO FILE!
dataByYear = groupDataByYear();
redrawDiagramWithFilter();
$('[data-toggle="popover"]').popover();
});
//ignored @param 'event'
function redraw() {
redrawDiagramWithFilter();
}
// Slider init
var yearSlider = $('#yearFilter').slider({}),
pubSlider = $('#pubFilter').slider({}),
collabSlider = $('#collabFilter').slider({});
yearSlider.on('slide', redraw);
pubSlider.on('slide', redraw);
collabSlider.on('slide', redraw);
$('#redraw').click(redraw);
$('#about').click(function() {
$('#viz').hide();
$('#home').removeClass('active');
$('#about').addClass('active');
$('#filterRow').hide();
$('#aboutText').show();
});
$('#home').click(function() {
$('#aboutText').hide();
$('#viz').show();
$('#filterRow').show();
$('#about').removeClass('active');
$('#home').addClass('active');
});
$(window).resize(function() {
redrawDiagramWithFilter(true);
});
|
import {OVERVIEW, GROUP_REPORT, ASSET_REPORT, TILE_OVERVIEW, ASSET_ANALYTICS, GROUP_ANALYTICS, SENSOR_LOG, EVENT_LOG,ALERTS} from './../../constants/routes';
import {RegionListId, ChartConfigutratorId, RoutesListId, TimeFrameId, WSHLFrameId, SwitchListId, AnalysisTypeId, AxelXId, AxelYId, AddNewFilterId} from './../../constants/filterItemId';
const initialState = {
items: null
};
export default (state = initialState, action) => {
// console.log('action', action);
switch(action.type) {
case "/":
case OVERVIEW:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | SwitchListId | WSHLFrameId});
case TILE_OVERVIEW:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | SwitchListId | WSHLFrameId});
case GROUP_REPORT:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | TimeFrameId | WSHLFrameId});
case ASSET_REPORT:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | TimeFrameId | WSHLFrameId});
case ASSET_ANALYTICS:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | TimeFrameId | WSHLFrameId | SwitchListId | AnalysisTypeId | ChartConfigutratorId});
case GROUP_ANALYTICS:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | TimeFrameId | WSHLFrameId | SwitchListId | AnalysisTypeId | ChartConfigutratorId});
case SENSOR_LOG:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | SwitchListId | WSHLFrameId});
case EVENT_LOG:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | SwitchListId | WSHLFrameId});
case ALERTS:
state = Object.assign({}, state, {items: RegionListId | RoutesListId | SwitchListId | WSHLFrameId});
}
return state;
}; |
var Promise = require("bluebird")
module.exports = ReadableStreamState
function ReadableStreamState(options) {
this.buffer = []
this.started = false
this.draining = false
this.pulling = false
this.state = "waiting"
this.storedError = null
this.readablePromise = new Promise()
this.closedPromise = new Promise()
this.startedPromise = new Promise()
this.onAbort = options.abort
this.onPull = options.pull
}
|
const NefitEasyClient = require('..');
// Instantiate client
const client = NefitEasyClient({
serialNumber : process.env.NEFIT_SERIAL_NUMBER,
accessKey : process.env.NEFIT_ACCESS_KEY,
password : process.env.NEFIT_PASSWORD,
});
// Connect client and retrieve status and pressure.
client.connect().then( () => {
return Promise.all([ client.status(), client.pressure() ]);
}).then(response => {
const status = response[0];
const pressure = response[1];
console.log(
'Temperature is set to %s°C, current is %s°C.\n' +
'Outside temperature is %s°C.\n' +
'System pressure is %s %s.',
status['temp setpoint'].toFixed(1),
status['in house temp'].toFixed(1),
status['outdoor temp'].toFixed(1),
pressure.pressure,
pressure.unit
);
}).catch(e => {
console.error('error', e)
}).finally(() => {
client.end();
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:1582026d3962f524ce66c24200c201dff7e5465aa12894fe5fc52cc4339f747a
size 2544
|
// Regular expression that matches all symbols in the Javanese block as per Unicode v6.3.0:
/[\uA980-\uA9DF]/; |
import React from 'react';
import { mount } from 'enzyme';
import { spy } from 'sinon';
import update from 'immutability-helper';
import defaultRules from '../src/defaultRules';
import Form from './components/Form';
import Input from './components/Input';
/* global describe it expect jasmine beforeEach afterEach */
describe('Test form with dynamic inputs', () => {
let FromTestRender;
let handlerSubmit;
let instance;
let HOCForm;
let onUnRegistered;
let onRegistered;
beforeEach(() => {
handlerSubmit = spy();
onUnRegistered = spy();
onRegistered = spy();
class DynamicExample extends React.Component {
constructor(props) {
super(props);
this.state = {
inputs: [
{
id: Math.random(),
label: 'Choose your user name',
errorClassName: 'error-message',
wrapClassName: 'input-group',
type: 'text',
name: 'userName',
defaultValue: '1234',
rule: 'notEmpty|minLength,4',
},
],
};
}
addInput = (name, valid) => {
this.setState(
(state) => {
const id = Math.random();
return update(state, {
inputs: {
$push: [{
id,
label: `Choose your user name (${id})`,
errorClassName: 'error-message',
wrapClassName: 'input-group',
type: 'text',
name,
defaultValue: valid ? '1234' : '123',
rule: 'notEmpty|minLength,4',
}],
},
});
},
);
};
removeInput = () => {
this.setState(
(state) => {
const newInputs = state.inputs.splice(0);
newInputs.pop();
return update(state, {
inputs: {
$set: newInputs,
},
});
},
);
};
render() {
return (
<Form
ref={(form) => { this.form = form; }}
validateLang="en"
submitCallback={handlerSubmit}
rules={defaultRules}
hasResetButton
>
{
this.state.inputs.map(test => <Input onUnRegistered={onUnRegistered} onRegistered={onRegistered} {...test} key={test.id} />)
}
</Form>
);
}
}
FromTestRender = mount(
<DynamicExample />,
);
instance = FromTestRender.instance();
HOCForm = instance.form;
});
describe('Test dynamic register and un register input', () => {
it('Should register new input success', () => {
instance.addInput('newAdded');
expect(onRegistered.called).toEqual(true);
expect(HOCForm.state.inputs.hasOwnProperty('newAdded')).toEqual(true);
});
it('Should un register new input success', () => {
instance.addInput('newAdded');
expect(HOCForm.state.inputs.hasOwnProperty('newAdded')).toEqual(true);
instance.removeInput();
expect(onUnRegistered.called).toEqual(true);
expect(HOCForm.state.inputs.hasOwnProperty('newAdded')).toEqual(false);
});
});
describe('Test submit the form after added or removed input', () => {
it('Should submit the form successfully after added a input', () => {
instance.addInput('newAdded', true);
FromTestRender.find('form').simulate('submit');
expect(handlerSubmit.called).toEqual(true);
});
it('Should submit the form successfully after remove a input', () => {
instance.removeInput();
FromTestRender.find('form').simulate('submit');
expect(handlerSubmit.called).toEqual(true);
});
it('Should not submit the form successfully after added a input because has error', () => {
instance.addInput('newAdded');
FromTestRender.find('form').simulate('submit');
expect(HOCForm.state.hasError).toEqual(true);
expect(handlerSubmit.called).toEqual(false);
});
});
});
|
BasicGame.MainMenu = function (game) {
this.music = null;
this.playButton = null;
};
BasicGame.MainMenu.prototype = {
create: function () {
// We've already preloaded our assets, so let's kick right into the Main Menu itself.
// Here all we're doing is playing some music and adding a picture and button
// Naturally I expect you to do something significantly better :)
this.add.sprite(0, 0, 'titlepage');
this.loadingText = this.add.text(this.game.width / 2, this.game.height / 2 + 80, "Press Z or tap/click game to start", { font: "20px monospace", fill: "#fff" });
this.loadingText.anchor.setTo(0.5, 0.5);
this.add.text(this.game.width / 2, this.game.height - 90, "image assets Copyright (c) 2002 Ari Feldman", { font: "12px monospace", fill: "#fff", align: "center"}).anchor.setTo(0.5, 0.5);
this.add.text(this.game.width / 2, this.game.height - 75, "sound assets Copyright (c) 2012 - 2013 Devin Watson", { font: "12px monospace", fill: "#fff", align: "center"}).anchor.setTo(0.5, 0.5);
},
update: function () {
if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) {
this.startGame();
}
// Do some nice funky main menu effect here
},
startGame: function () {
// Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing)
// this.music.stop();
// And start the actual game
this.state.start('Game');
}
};
|
var runTests = function(){
var noMsg = function(){
console.info("-----------NO Message should follow---------------");
};
var oneMsg = function(){
console.info("-----------ONE Message should follow---------------");
};
var twoMsg = function(){
console.info("-----------TWO Messages should follow:---------------");
}
var Player = function(name){
this.name = name;
this.friend = null;
this.friendIndex = null;
this.setFriend = function(friend){
this.friend = friend;
this.friendIndex = friend.on("hit", function(obj){
console.log("oh no my friend", friend.name, "has been hit!", obj.info);
});
};
this.removeFriend = function(){
this.friend.ignore("hit", this.friendIndex);
};
this.hit = function(){
console.log("I'm", this.name, "and I've been hit!");
this.emit("hit", {info: "ok!"});
};
};
var p1 = new Player("Arnold");
var p2 = new Player("Brutus");
var eventHandler = new MtEventHandler();
eventHandler.makeEvented(p1);
eventHandler.makeEvented(p2);
p1.setFriend(p2);
p2.setFriend(p1);
twoMsg();
p1.hit();
twoMsg();
p2.hit();
p1.removeFriend();
p2.removeFriend();
oneMsg();
p1.hit();
oneMsg();
p2.hit();
//----------------------------------------------------------------------------
console.log("..............................................................");
var c1 = eventHandler.createChannel("one");
var c1a = c1.listen(function(obj){
console.log("listening to channel1 playing", obj.info);
});
var c1b = c1.listen(function(obj){
console.log("ALSO listening to channel1 playing", obj.info);
});
twoMsg();
c1.broadcast({info: "wonderwall"});
oneMsg();
c1.ignore(c1a);
c1.broadcast({info: "wonderwall"});
var c2 = eventHandler.createChannel("two");
var c2a = c2.listen(function(obj){
console.log("c2 and listening to channel1 playing", obj.info);
});
var c2b = c2.listen(function(obj){
console.log("ALSO c2 and listening to channel1 playing", obj.info);
});
twoMsg();
c2.broadcast({info: "nickelback"});
oneMsg();
c2.ignore(c2a);
c2.broadcast({info: "nickelback"});
noMsg();
c2.ignore(c2b);
c2.broadcast({info: "nothing"});
};
|
define("states/<%=nameCamel%>", ["app", "controllers/<%=nameCamel%>"], function (app) {
"use strict";
return app.config(["$stateProvider", function ($stateProvider) {
$stateProvider.state("<%=nameCamel%>", {
// "abstract": true,
// parent: "parentState",
url: "/{someProp}{anotherProp:(?:/[^/]+)?}",
// template: "<div></div>",
// templateProvider: function ($stateParams) { },
templateUrl: __webApp_ResourceRoot+"/templates/<%=nameCamel%>.html",
onEnter: ["$state", "$translate", "$translatePartialLoader", function ($state, $translate, $translatePartialLoader) {
$translatePartialLoader.deletePart("<%=nameCamel%>", true);
$translatePartialLoader.addPart("<%=nameCamel%>");
$translate.refresh();
}],
onExit: ["$state", "$translate", "$translatePartialLoader", function ($state, $translate, $translatePartialLoader) {
//$translatePartialLoader.deletePart("<%=nameCamel%>", true);
$translate.refresh();
}],
controller: "<%=nameCamel%>"/*,*/
// views: {
// "view1@": {
// template: "<div></div>",
// templateProvider: function ($stateParams) { },
// templateUrl: "template.html",
// controller: "controllerName"
// }
// }
});
}]);
});
|
const path = require('path')
// 日志类型配置
module.exports = {
appenders: {
// WS日志,请求日志
ws: {
type: 'dateFile',
filename: `${path.resolve(__dirname, '../logs/wsLogs/logs')}Ws.log`,
maxLogSize: 102400,
backups: 1024,
},
// HTTP日志,请求日志
http: {
type: 'dateFile',
filename: `${path.resolve(__dirname, '../logs/httpLogs/logs')}Http.log`,
maxLogSize: 102400,
backups: 1024,
},
// 系统日志,如:程序启动和db链接日志,框架错误,catch框架错误,db连接错误等
sys: {
type: 'dateFile',
filename: `${path.resolve(__dirname, '../logs/sysLogs/logs')}Sys.log`,
maxLogSize: 102400,
backups: 1024,
},
// 登陆日志,所有登录登出等的日志
login: {
type: 'dateFile',
filename: `${path.resolve(__dirname, '../logs/loginLogs/logs')}Login.log`,
maxLogSize: 102400,
backups: 1024,
},
// APIERROR日志,所有API请求产生的程序错误日志
apiError: {
type: 'dateFile',
filename: `${path.resolve(__dirname, '../logs/apiErrorLogs/logs')}apiError.log`,
maxLogSize: 102400,
backups: 1024,
},
// 错误日志,所有的错误日志
errorsFile: {
type: 'dateFile',
filename: `${path.resolve(__dirname, '../logs/errorsFileLogs/logs')}ErrorsFile.log`,
maxLogSize: 102400,
backups: 1024,
},
errors: {
type: 'logLevelFilter',
appender: 'errorsFile',
level: 'error',
},
console: { type: 'console' },
},
categories: {
default: { appenders: ['console'], level: 'info' },
ws: { appenders: ['ws', 'errors'], level: 'info' },
http: { appenders: ['http', 'errors'], level: 'info' },
sys: { appenders: ['sys', 'console', 'errors'], level: 'info' },
login: { appenders: ['login'], level: 'info' },
apiError: { appenders: ['apiError', 'errors'], level: 'info' },
},
}
|
// knockout-amd-helpers 1.1.0 | (c) 2020 Ryan Niemeyer | http://www.opensource.org/licenses/mit-license
define(["knockout", "require"], function(ko, require) {
//helper functions to support the binding and template engine (whole lib is wrapped in an IIFE)
var unwrap = ko.utils.unwrapObservable,
//call a constructor function with a variable number of arguments
construct = function(Constructor, args) {
var instance,
Wrapper = function() {
return Constructor.apply(this, args || []);
};
Wrapper.prototype = Constructor.prototype;
instance = new Wrapper();
instance.constructor = Constructor;
return instance;
},
addTrailingSlash = function(path) {
return path && path.replace(/\/?$/, "/");
},
isAnonymous = function(node) {
var el = ko.virtualElements.firstChild(node);
while (el) {
if (el.nodeType === 1 || el.nodeType === 8) {
return true;
}
el = ko.virtualElements.nextSibling(el);
}
return false;
};
function defaultModuleLoader(moduleName, done) {
require([addTrailingSlash(ko.bindingHandlers.module.baseDir) + moduleName], done);
}
//an AMD helper binding that allows declarative module loading/binding
ko.bindingHandlers.module = {
init: function(element, valueAccessor, allBindingsAccessor, data, context) {
var extendedContext, extractedNodes, disposeModule,
options = unwrap(valueAccessor()),
templateBinding = {},
initializer = ko.bindingHandlers.module.initializer,
disposeMethod = ko.bindingHandlers.module.disposeMethod;
//build up a proper template binding object
templateBinding.templateEngine = options && options.templateEngine;
//allow binding template to a string on module (can override in binding)
templateBinding.templateProperty = ko.bindingHandlers.module.templateProperty;
//afterRender could be different for each module, create a wrapper
templateBinding.afterRender = function(nodes, data) {
var handler,
options = unwrap(valueAccessor());
if (options && options.afterRender) {
handler = typeof options.afterRender === "string" ? data && data[options.afterRender] : options.afterRender;
if (typeof handler === "function") {
handler.apply(this, arguments);
}
}
};
if (options && options.moveNodesToContext) {
extractedNodes = Array.prototype.slice.call(ko.virtualElements.childNodes(element));
ko.virtualElements.emptyNode(element);
}
//if this is not an anonymous template, then build a function to properly return the template name
if (!isAnonymous(element)) {
templateBinding.name = function() {
var template = unwrap(valueAccessor());
return ((template && typeof template === "object") ? unwrap(template.template || template.name) : template) || "";
};
}
//set the data to an observable, that we will fill when the module is ready
templateBinding.data = ko.observable();
templateBinding["if"] = templateBinding.data;
//actually apply the template binding that we built. extend the context to include a $module property
ko.applyBindingsToNode(element, { template: templateBinding }, extendedContext = context.extend({ $module: null, $moduleTemplateNodes: extractedNodes }));
//disposal function to use when a module is swapped or element is removed
disposeModule = function() {
//avoid any dependencies
ko.computed(function() {
var currentData = templateBinding.data();
if (currentData) {
if (typeof currentData[disposeMethod] === "function") {
currentData[disposeMethod].call(currentData);
currentData = null;
}
templateBinding.data(null);
}
}).dispose();
extractedNodes = null;
};
//now that we have bound our element using the template binding, pull the module and populate the observable.
ko.computed({
read: function() {
//module name could be in an observable
var initialArgs,
moduleLoader = ko.bindingHandlers.module.loader || defaultModuleLoader,
moduleName = unwrap(valueAccessor());
//observable could return an object that contains a name property
if (moduleName && typeof moduleName === "object") {
//initializer/dispose function name can be overridden
initializer = moduleName.initializer || initializer;
disposeMethod = moduleName.disposeMethod || disposeMethod;
templateBinding.templateProperty = ko.unwrap(moduleName.templateProperty) || templateBinding.templateProperty;
//get the current copy of data to pass into module
initialArgs = [].concat(unwrap(moduleName.data));
//name property could be observable
moduleName = unwrap(moduleName.name);
}
//if there is a current module and it has a dispose callback, execute it and clear the data
disposeModule();
//at this point, if we have a module name, then require it dynamically
if (moduleName) {
moduleLoader(moduleName, function(mod) {
//if it is a constructor function then create a new instance
if (typeof mod === "function") {
mod = construct(mod, initialArgs);
}
else {
//if it has an appropriate initializer function, then call it
if (mod && mod[initializer]) {
//if the function has a return value, then use it as the data
mod = mod[initializer].apply(mod, initialArgs || []) || mod;
}
}
//update the data that we are binding against
extendedContext.$module = mod;
templateBinding.data(mod);
});
}
},
disposeWhenNodeIsRemoved: element
});
//optionally call module disposal when removing an element
ko.utils.domNodeDisposal.addDisposeCallback(element, disposeModule);
return { controlsDescendantBindings: true };
},
baseDir: "",
initializer: "initialize",
disposeMethod: "dispose",
templateProperty: ""
};
//support KO 2.0 that did not export ko.virtualElements
if (ko.virtualElements) {
ko.virtualElements.allowedBindings.module = true;
}
//an AMD template engine that uses the text plugin to pull templates
(function(ko, require) {
//get a new native template engine to start with
var engine = new ko.nativeTemplateEngine(),
sources = {};
engine.defaultPath = "templates";
engine.defaultSuffix = ".tmpl.html";
engine.defaultRequireTextPluginName = "text";
engine.loader = function(templateName, done) {
require([engine.defaultRequireTextPluginName + "!" + addTrailingSlash(engine.defaultPath) + templateName + engine.defaultSuffix], done);
};
//create a template source that loads its template using the require.js text plugin
ko.templateSources.requireTemplate = function(key) {
this.key = key;
this.template = ko.observable(" "); //content has to be non-falsey to start with
this.requested = false;
this.retrieved = false;
};
ko.templateSources.requireTemplate.prototype.text = function(value) {
//when the template is retrieved, check if we need to load it
if (!this.requested && this.key) {
engine.loader(this.key, function(templateContent) {
this.retrieved = true;
this.template(templateContent);
}.bind(this));
this.requested = true;
}
//if template is currently empty, then clear it
if (!this.key) {
this.template("");
}
//always return the current template
if (arguments.length === 0) {
return this.template();
}
};
//our engine needs to understand when to create a "requireTemplate" template source
engine.makeTemplateSource = function(template, doc) {
var el;
//if a name is specified
if (typeof template === "string") {
//if there is an element with this id and it is a script tag, then use it
el = (doc || document).getElementById(template);
if (el && el.tagName.toLowerCase() === "script") {
return new ko.templateSources.domElement(el);
}
//otherwise pull the template in using the AMD loader's text plugin
if (!(template in sources)) {
sources[template] = new ko.templateSources.requireTemplate(template);
}
//keep a single template source instance for each key, so everyone depends on the same observable
return sources[template];
}
//if there is no name (foreach/with) use the elements as the template, as normal
else if (template && (template.nodeType === 1 || template.nodeType === 8)) {
return new ko.templateSources.anonymousTemplate(template);
}
};
//override renderTemplate to properly handle afterRender prior to template being available
engine.renderTemplate = function(template, bindingContext, options, templateDocument) {
var templateSource,
existingAfterRender = options && options.afterRender,
localTemplate = options && options.templateProperty && bindingContext.$module && bindingContext.$module[options.templateProperty];
//restore the original afterRender, if necessary
if (existingAfterRender) {
existingAfterRender = options.afterRender = options.afterRender.original || options.afterRender;
}
//if a module is being loaded, and that module has the template property (of type `string` or `function`) - use that as the source of the template.
if (localTemplate && (typeof localTemplate === "function" || typeof localTemplate === "string")) {
templateSource = {
text: function() {
return typeof localTemplate === "function" ? localTemplate.call(bindingContext.$module) : localTemplate;
}
};
}
else {
templateSource = engine.makeTemplateSource(template, templateDocument);
}
//wrap the existing afterRender, so it is not called until template is actually retrieved
if (typeof existingAfterRender === "function" && templateSource instanceof ko.templateSources.requireTemplate && !templateSource.retrieved) {
options.afterRender = function() {
if (templateSource.retrieved) {
existingAfterRender.apply(this, arguments);
}
};
//keep track of the original, so we don't double-wrap the function when template name changes
options.afterRender.original = existingAfterRender;
}
return engine.renderTemplateSource(templateSource, bindingContext, options, templateDocument);
};
//expose the template engine at least to be able to customize the path/suffix/plugin at run-time
ko.amdTemplateEngine = engine;
//make this new template engine our default engine
ko.setTemplateEngine(engine);
})(ko, require);
}); |
'use strict';
var MQ = require('./lib').MultiQueue;
module.exports = function() {
return new MQ();
};
|
var Dispatcher = require('flux').Dispatcher;
var copyProperties = require('react/lib/copyProperties');
var AppDispatcher = copyProperties(new Dispatcher(), {
handleViewAction: function(action) {
this.dispatch({
source: 'VIEW_ACTION',
action: action
});
}
});
module.exports = AppDispatcher;
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var sidebar_routes_config_1 = require('./sidebar-routes.config');
var SidebarComponent = (function () {
function SidebarComponent() {
}
SidebarComponent.prototype.ngOnInit = function () {
$.getScript('../../assets/js/sidebar-moving-tab.js');
this.menuItems = sidebar_routes_config_1.ROUTES.filter(function (menuItem) { return menuItem; });
};
SidebarComponent = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'sidebar-cmp',
templateUrl: 'sidebar.component.html',
}),
__metadata('design:paramtypes', [])
], SidebarComponent);
return SidebarComponent;
}());
exports.SidebarComponent = SidebarComponent;
//# sourceMappingURL=sidebar.component.js.map |
'use strict';
const db = require('./db');
const _ = require('lodash');
module.exports = function(seat_id) {
var data = db.neighbours().findOne({id: seat_id});
if (!data) {
var not_found_error = new Error('Seat not found');
not_found_error.status = 404;
return Promise.reject(not_found_error);
}
var seats = db.seats().find({id: {'$in': data.neighbours}});
return Promise.resolve(_.sortBy(seats, 'name'));
};
|
$(function() {
$('form#trip_plan_form').on('submit', function(e){
if ( !Rotas.validar() )
return false;
Rotas.tracar();
var fechado = $('a.direcoes').hasClass('fechado');
if ( fechado !== false )
{
// $('a.direcoes').removeClass('fechado');
// $('div#sidebar').show();
// $('div.direita')
// .removeClass('col-md-12')
// .addClass('col-md-push-4');
resize_window();
}
$('div.esquerda').show();
mostrar_aba('esquerda');
setTimeout( map.invalidateSize.bind(map) );
if ( $('div#coll_it1').css('display') == 'none' )
$('a[href="#coll_it1"]').trigger('click');
e.preventDefault();
});
}); |
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import Inferno from 'inferno';
export default () => (
<span id="feature-public-url">{process.env.PUBLIC_URL}.</span>
);
|
'use babel';
import TestDepsView from '../lib/test-deps-view';
describe('TestDepsView', () => {
it('has one valid test', () => {
expect('life').toBe('easy');
});
});
|
//GameTimer:用户不活跃的时候,自动降低刷新周期
//注意:本文件依赖于jquery
function GetNow(){
return (new Date()).getTime();
}
var g_theTimer = null;
function NosTimer(cfg){
this.time_idle_interval = cfg.time_idle_interval; //30*1000; //计算各个用户活跃状态时间段的最小周期。决定了各个周期的时间长度。
this.time_interval_base = cfg.time_interval_base; //10000; //刷新周期的最小值。其它刷新周期都是它的整数倍。决定了各个周期里,触发定时器的频率。
this.time_timer_interval = cfg.time_timer_interval; //1000; //定时器的周期,越小越精确,但越耗费客户端CPU
this.fun_timer = cfg.fun_timer;
//以下是自动生成的配置数据
this.time_cfg = {"playing":this.time_idle_interval,
"active":4*this.time_idle_interval,
"left":20*this.time_idle_interval}; //各个时间点的长度
this.time_user_active = (new Date()).getTime();
this.time_user_play = 0;
this.time_last_trige = 0;
g_theTimer = this;
$("body").bind("mousemove", function(e){
g_theTimer.UserActived();
});
/*$("body").bind("mouseup", function(e){
g_theTimer.UserPlayed();
});
$("body").bind("keypress", function(e){
g_theTimer.UserPlayed();
});*/
//setInterval("OnTimer();",this.time_timer_interval);
setInterval(this.OnTimer,this.time_timer_interval);
};
//当用户落子的时候调用
NosTimer.prototype.UserPlayed = function (){
this.time_user_play = GetNow();
this.time_user_active = this.time_user_play;
}
NosTimer.prototype.UserActived = function (fun){
this.time_user_active = GetNow();
}
NosTimer.prototype.TrigTimer = function (){
this.time_last_trige = GetNow();
if('function'==typeof(this.fun_timer)){
//如果是函数,执行此函数
this.fun_timer();
}
else{
//如果是对象,那么自动调用其call函数
this.fun_timer.call();
}
}
NosTimer.prototype.OnTimer = function (){
var now = GetNow();
//对局中
if((now - g_theTimer.time_user_play)<g_theTimer.time_cfg['playing'])
{
if((now-g_theTimer.time_last_trige)>g_theTimer.time_interval_base){
g_theTimer.TrigTimer();
}
return;
}
//用户活跃
if((now - g_theTimer.time_user_active)<g_theTimer.time_cfg['playing'])
{
if((now-g_theTimer.time_last_trige)>2*g_theTimer.time_interval_base){
g_theTimer.TrigTimer();
}
return;
}
//用户关注中
if((now - g_theTimer.time_user_active)<g_theTimer.time_cfg['active'])
{
if((now-g_theTimer.time_last_trige)>4*g_theTimer.time_interval_base){
g_theTimer.TrigTimer();
}
return;
}
//一般状态
if((now - g_theTimer.time_user_active)<g_theTimer.time_cfg['left'])
{
if((now-g_theTimer.time_last_trige)>6*g_theTimer.time_interval_base){
g_theTimer.TrigTimer();
}
return;
}
//用户已离开
if((now-g_theTimer.time_last_trige)>16*g_theTimer.time_interval_base){
g_theTimer.TrigTimer();
}
return;
} |
/*
finds the seccond (Partner) angle from the first
e.g. seccondAngle(Math.PI*0.25, 'sin', 'rad'){
...
}
would return Math.PI*0.75
*/
function seccondAngle(firstAngle, trigFunction, units) {
//sine calculator
if (trigFunction == "sin") {
if (units == "deg") {
if (firstAngle >= 0 && firstAngle <= 180) {
return 180 - firstAngle;
} else if (firstAngle < 0 || firstAngle > 180) {
return 360 - (firstAngle - 180);
}
} else if (units == "rad") {
if (firstAngle >= 0) {
return Math.PI - firstAngle;
} else if (firstAngle < 0) {
return Math.PI + firstAngle;
}
}
}
//cosine calculator
else if (trigFunction == "cos") {
if (units == "deg") {
if (firstAngle >= 0) {
return 180 - firstAngle;
} else if (firstAngle < 0) {
return 180 + firstAngle;
}
} else if (units == "rad") {
if (firstAngle >= 0) {
return Math.PI - firstAngle;
} else if (firstAngle < 0) {
return Math.PI + firstAngle;
}
}
}
//tangent calculator
else if (trigFunction == "tan") {
if (units == "deg") {
if (firstAngle >= 0) {
return 180 - firstAngle;
} else if (firstAngle < 0) {
return 180 + firstAngle;
}
} else if (units == "rad") {
if (firstAngle >=0 ) {
return Math.PI - firstAngle;
} else if (firstAngle < 0) {
return Math.PI + firstAngle;
}
}
}
} |
/**
* Group all `an` macros
* @namespace
* @alias macros.an
* @since 0.0.1
*/
macros.an = {
/**
* This should be the first command in a man page, not only
* creates the title of the page but also stores in the buffer
* useful variables: `title`, `section`, `date`, `source`
* and `manual`
*
* @param {string} args raw representation of the arguments
* described below, in this version the TH function is in charge
* to parse and store this arguments in the buffer
*
* @param {object} buffer
*
* @returns {string}
*
* @example
* var args = 'FOO 1 "MARCH 1995" Linux "User Manuals"';
* var buffer = {};
*
* TH(args, buffer);
* buffer.title //=> FOO
* buffer.section //=> 1
* buffer.date //=> "MARCH 1995"
*
* @since 0.0.1
*
*/
TH: function (args) {
var title;
args = this.parseArguments(args);
this.buffer.title = args[0] || '';
this.buffer.section = args[1] || '';
this.buffer.date = args[2] || '';
this.buffer.source = args[3] || '';
this.buffer.manual = args[4] || '';
title = this.buffer.title + '(' + this.buffer.section + ')';
return(
'<p><span>' + title + '</span>' +
'<span>' + this.buffer.manual + '</span>' +
'<span>' + title + '</span></p>'
);
},
/**
* Represent a section in the manual, creates a title tag
* with the contents of the `arg` variable
*
* @param {string} args section title, from 1 to n words.
*
* @returns {string} a semantic representation of a section title.
*
* @since 0.0.1
*
*/
SH: function (args) {
var openingTag = '<section style="margin-left:' +
this.buffer.style.indent + '%;">',
preamble = '';
this.buffer.section = args;
preamble += this.closeAllTags(this.buffer.fontModes);
preamble += this.closeAllTags(this.buffer.openTags);
preamble += this.closeAllTags(this.buffer.sectionTags);
this.buffer.sectionTags.push('section');
return preamble + this.generateTag('h2', args) + openingTag;
},
/**
* Represent a subsection inside a section, creates a subtitle tag
* with the contents of the `arg` variable
*
* @param {string} args subtitle, from 1 to n words.
*
* @returns {string} a semantic representation of a section title.
*
* @since 0.0.1
*
*/
SS: function (args) {
return this.generateTag('h3', args);
},
/**
* Generate bold text
*
* @param {string} args the text to be presented as bold
*
* @returns {string}
*
* @since 0.0.1
*
*/
B: function (args) {
return this.generateTag('strong', args);
},
/**
* Generate bold text alternated with italic text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
BI: function (args) {
return this.generateAlternTag('strong', 'i', args);
},
/**
* Generate bold text alternated with regular text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
BR: function (args) {
return this.generateAlternTag('strong', 'span', args);
},
/**
* Generate italic text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
I: function (args) {
return this.generateTag('i', args);
},
/**
* Generate italic text alternated with bold
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
IB: function (args) {
return this.generateAlternTag('i', 'strong', args);
},
/**
* Generate italic text alternated with regular text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
IR: function (args) {
return this.generateAlternTag('i', 'span', args);
},
/**
* Generate regular text alternated with bold text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
RB: function (args) {
return this.generateAlternTag('span', 'strong', args);
},
/**
* Generate regular text alternated with italic text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
RI: function (args) {
return this.generateAlternTag('span', 'i', args);
},
/**
* Generate small text alternated with bold text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
SB: function (args) {
return this.generateAlternTag('small', 'strong', args);
},
/**
* Generate small text
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
SM: function (args) {
return this.generateTag('small', args);
},
/**
* Generate a paragraph
*
* @param {string} args
*
* @returns {string}
*
* @since 0.0.1
*
*/
P: function () {
var result = '';
result += this.closeAllTags(this.buffer.fontModes);
result += this.closeTagsUntil('div', this.buffer.openTags);
this.buffer.openTags.push('div');
return result + '<div style="margin-bottom: 2%;">';
},
/**
* Start relative margin indent: moves the left margin `indent` to
* the right (if is omitted, the prevailing indent value is used).
*
* @param {string} indent
*
* @since 0.0.1
*
*/
RS: function (indent) {
var result = '';
indent = indent || this.buffer.style.indent;
result += this.closeAllTags(this.buffer.fontModes);
result += '<section style="margin-left:' + indent + '%">';
this.buffer.openTags.push('section');
return result;
},
/**
* End relative margin indent and restores the previous value
* of the prevailing indent.
*
* @since 0.0.1
*
*/
RE: function () {
return this.closeTagsUntil('section', this.buffer.openTags);
}
};
macros.an.LP = macros.an.P;
macros.an.PP = macros.an.P;
|
var express = require('express');
var router = express.Router();
var ctrlTemperatures = require('../controllers/temperatures');
router.get('/temperatures/fortnight', ctrlTemperatures.fortnight);
router.get('/temperatures', ctrlTemperatures.index);
router.get('/statistics', ctrlTemperatures.statisticsForDay);
router.get('/byRowId', ctrlTemperatures.apiByRowId);
module.exports = router;
|
var _ = require('lodash');
const assert = require('assert');
const authHandler = require('../../lib/mbaas/index');
const sampleUserConfig = require('../fixtures/sampleUserConfig.json');
const sampleProfileData = require('../fixtures/sampleUserProfile.json');
const sampleProfileDataLength = Object.keys(sampleProfileData).length;
var mbaasRouter = require('../../lib/mbaas/index');
var express = require('express');
var supertest = require('supertest');
var bodyParser = require('body-parser');
var mediatorMock = require('../mocks/mediatorMock');
var sampleUser = require('../fixtures/user');
var sinon = require('sinon');
var sampleExclusionList1 = ['banner'];
var sampleExclusionList2 = ['banner', 'avatar'];
var sampleExclusionList3 = [];
var sampleExclusionList4 = undefined;
var sampleExclusionList5 = null;
describe('Test mbass authentication', function() {
var app, request;
beforeEach(function(done) {
mediatorMock.request.reset();
app = express();
app.use(bodyParser.json());
request = supertest(app);
mbaasRouter.init(mediatorMock, app, [], {}, done);
});
it('Should log in using correct credentials', function(done) {
request
.get('/api/wfm/user/auth')
.send({userId: sampleUser.username, password: sampleUser.password})
.expect(200, function(err, res) {
assert.ok(!err, err);
assert.ok(res, "Expected a result from the authentication request.");
assert.equal(res.body.status, 'ok',
"Expected status ok from the successful authentication request.");
assert.equal(res.body.userId, sampleUser.username,
"Expected user profile from the successful authentication request.");
sinon.assert.calledTwice(mediatorMock.request);
sinon.assert.calledWith(mediatorMock.request, 'wfm:user:auth',
{username: sampleUser.username, password: sampleUser.password});
sinon.assert.calledWith(mediatorMock.request, 'wfm:user:username:read',
sampleUser.username);
done();
});
});
it('Should get 401 User not found when logging in with incorrect username', function(done) {
request
.get('/api/wfm/user/auth')
.send({userId: 'invalid_username', password: sampleUser.password})
.expect(401, function(err, res) {
assert.ok(!err, err);
assert.ok(res, "Expected a result from the failed authentication request.");
assert.equal(res.body, 'Invalid Credentials',
'Expected Invalid credentials message in response body on unsuccessful authentication request.');
sinon.assert.calledOnce(mediatorMock.request);
sinon.assert.calledWith(mediatorMock.request, 'wfm:user:auth',
sinon.match({
username: sinon.match(function(username) {
return username !== sampleUser.username;
}),
password: sinon.match(sampleUser.password)
}));
done();
});
});
it('Should get 401 Invalid credentials when logging in with incorrect password', function(done) {
request
.get('/api/wfm/user/auth')
.send({userId: sampleUser.username, password: 'invalid_password'})
.expect(401, function(err, res) {
assert.ok(!err, err);
assert.ok(res, "Expected a result from the authentication request.");
assert.equal(res.body, 'Invalid Credentials',
'Expected Invalid credentials message in response body on unsuccessful authentication request.');
sinon.assert.calledOnce(mediatorMock.request);
sinon.assert.calledWith(mediatorMock.request, 'wfm:user:auth',
sinon.match({
username: sinon.match(sampleUser.username),
password: sinon.match(function(password) {
return password !== sampleUser.password;
})
}));
done();
});
});
});
describe('#testAuthResponseData', function() {
it('it should not remove any fields when an empty exclusion list is specified', function(done) {
var authResponse = authHandler.trimProfileData(_.clone(sampleProfileData), sampleExclusionList3);
assert(Object.keys(authResponse).length === sampleProfileDataLength,
"Expect that specifying an empty exclusion list returns all the User fields in the response.");
done();
});
it('it should remove the password field by default', function(done) {
var authResponse = authHandler.trimProfileData(_.clone(sampleProfileData), sampleUserConfig.authResponseExclusionList);
assert(authResponse.password === undefined,
"Check that the Password field has been removed from the Response.");
assert(Object.keys(authResponse).length !== sampleProfileDataLength,
"Expect that the auth response has a different length to the user profile data.");
done();
});
it('it should remove a single field when specified', function(done) {
var authResponse = authHandler.trimProfileData(_.clone(sampleProfileData), sampleExclusionList1);
assert(authResponse.banner === undefined,
"Check that the Banner field has been removed from the Response.");
assert(Object.keys(authResponse).length !== sampleProfileDataLength,
"Expect that the auth response has a different length to the user profile data.");
done();
});
it('it should remove a single field when specified and also not remove the password', function(done) {
var authResponse = authHandler.trimProfileData(_.clone(sampleProfileData), sampleExclusionList1);
assert(authResponse.banner === undefined,
"Check that the Banner field has been removed from the Response.");
assert(authResponse.password !== undefined,
"Check that the Password field has Not been removed from the Response.");
assert(Object.keys(authResponse).length !== sampleProfileDataLength,
"Expect that the auth response has a different length to the user profile data.");
done();
});
it('it should remove a number of fields when specified', function(done) {
var authResponse = authHandler.trimProfileData(_.clone(sampleProfileData), sampleExclusionList2);
assert(authResponse.banner === undefined,
"Check that the Banner field has been removed from the Response.");
assert(authResponse.avatar === undefined,
"Check that the Avatar field has been removed from the Response.");
assert(Object.keys(authResponse).length !== sampleProfileDataLength,
"Expect that the auth response has a different length to the user profile data.");
done();
});
it('it should remove the password field by default when the exclusion list is undefined', function(done) {
var authResponse = authHandler.trimProfileData(_.clone(sampleProfileData), sampleExclusionList4);
assert(authResponse.password === undefined,
"Check that the Password field has been removed from the Response.");
assert(Object.keys(authResponse).length !== sampleProfileDataLength,
"Expect that specifying an undefined exclusion list will result in the default exclusion list being used");
done();
});
it('it should remove the password field by default when the exclusion list is null', function(done) {
var authResponse = authHandler.trimProfileData(_.clone(sampleProfileData), sampleExclusionList5);
assert(authResponse.password === undefined,
"Check that the Password field has been removed from the Response.");
assert(Object.keys(authResponse).length !== sampleProfileDataLength,
"Expect that specifying a null exclusion list will result in the default exclusion list being used.");
done();
});
});
|
import {customElement, bindable} from 'aurelia-templating';
import {bindingMode} from 'aurelia-binding';
import {inject} from 'aurelia-dependency-injection';
import {isTouch} from 'aurelia-interface-platforms';
import {DOM} from 'aurelia-pal';
const clickEvent = isTouch ? 'touchstart' : 'click';
@customElement('au-dropdown')
@inject(Element)
@bindable({
name: 'value',
attribute: 'value',
changeHandler: 'valueChanged',
defaultBindingMode: bindingMode.twoWay
})
export class DropdownElement {
@bindable options = null;
@bindable active = null;
constructor(element) {
this.element = element;
this.onClick = this.onClick.bind(this);
}
valueChanged(value) {
this.change && this.change(value);
this.active = false;
}
activeChanged(value) {
this.element.classList[value ? 'add' : 'remove']('is-active');
if (value) this.addListeners();
}
addListeners() {
DOM.addEventListener(clickEvent, this.onClick, true);
}
removeListeners() {
DOM.removeEventListener(clickEvent, this.onClick, true);
}
onClick(event) {
if (!this.element.contains(event.target)) {
this.active = false;
this.removeListeners();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.