code
stringlengths 2
1.05M
|
---|
console.log('----加载开始----');
module.exports = (num) => {
return num + 1;
}
console.log('----加载结束----');
|
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
function FileBlock() {}
FileBlock.prototype = {
appDir: null,
profileDir: null,
tempDir: null,
// List of domains for the whitelist
whitelist: [],
// Chrome pages that should not be shown
chromeBlacklist: ["browser", "mozapps", "marionette", "specialpowers",
"branding", "alerts"],
initialize: function() {
this.appDir = Services.io.newFileURI(Services.dirsvc.get("CurProcD", Ci.nsIFile)).spec;
var profileDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
this.profileDir = Services.io.newFileURI(profileDir).spec
this.tempDir = Services.io.newFileURI(Services.dirsvc.get("TmpD", Ci.nsIFile)).spec;
try {
var whitelist = Services.prefs.getCharPref("extensions.webconverger.whitelist");
this.whitelist = whitelist.split(",");
for (var i=0; i < this.whitelist.length; i++) {
this.whitelist[i] = this.whitelist[i].trim();
}
} catch(e) {}
var whitelistFile = profileDir.clone();
whitelistFile.append("webconverger.whitelist");
if (!whitelistFile.exists()) {
return;
}
var stream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
stream.init(whitelist, 0x01, 0644, 0);
var lis = stream.QueryInterface(Components.interfaces.nsILineInputStream);
var line = {value:null};
do {
var more = lis.readLine(line);
try {
var file = Cc["@mozilla.org/file/local;1"]
.createInstance(Ci.nsILocalFile);
file.initWithPath(line.value);
this.whitelist.push(ioService.newFileURI(file).spec.toLowerCase());
} catch (ex) {
/* Invalid path */
}
} while (more);
stream.close();
},
shouldLoad: function(aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) {
if (!this.appDir) {
this.initialize();
}
// We need to allow access to any files in the profile directory,
// application directory or the temporary directory. Without these,
// Firefox won't start
if (aContentLocation.spec.match(this.profileDir) ||
aContentLocation.spec.match(this.appDir) ||
aContentLocation.spec.match(this.tempDir)) {
return Ci.nsIContentPolicy.ACCEPT;
}
// Allow everything on the whitelist first
if (aContentLocation.scheme == "http" ||
aContentLocation.scheme == "https") {
for (var i=0; i< this.whitelist.length; i++) {
if (aContentLocation.host == this.whitelist[i] ||
aContentLocation.host.substr(aContentLocation.host.length - this.whitelist[i].length - 1) == "." + this.whitelist[i]) {
return Ci.nsIContentPolicy.ACCEPT;
}
}
}
if (aContentLocation.scheme == "chrome") {
// This prevents loading of chrome files into the browser window
if (aRequestOrigin &&
(aRequestOrigin.spec == "chrome://browser/content/browser.xul" ||
aRequestOrigin.scheme == "moz-nullprincipal")) {
for (var i=0; i < this.chromeBlacklist.length; i++) {
if (aContentLocation.host == this.chromeBlacklist[i]) {
return Ci.nsIContentPolicy.REJECT_REQUEST;
}
}
}
// All chrome requests come through here, so we have to allow them
// (Like loading the main browser window for instance)
return Ci.nsIContentPolicy.ACCEPT;
}
// Prevent the loading of resource files into the main browser window
if (aContentLocation.scheme == "resource") {
if (aRequestOrigin && aRequestOrigin.scheme == "moz-nullprincipal") {
return Ci.nsIContentPolicy.REJECT_REQUEST;
}
return Ci.nsIContentPolicy.ACCEPT;
}
// Only allow these three about URLs
if (aContentLocation.scheme == "about") {
if (aContentLocation.spec == "about:" ||
/^about:certerror/.test(aContentLocation.spec) ||
/^about:neterror/.test(aContentLocation.spec) ||
/^about:buildconfig/.test(aContentLocation.spec) ||
/^about:credits/.test(aContentLocation.spec) ||
/^about:license/.test(aContentLocation.spec) ||
// /^about:srcdoc/.test(aContentLocation.spec) || // Needed for Australis
// /^about:customizing/.test(aContentLocation.spec) || // Needed for Australis
/^about:blank/.test(aContentLocation.spec)) {
return Ci.nsIContentPolicy.ACCEPT;
}
return Ci.nsIContentPolicy.REJECT_REQUEST;
}
// We allow all javascript and data URLs
if (aContentLocation.scheme == "data" ||
aContentLocation.scheme == "javascript") {
return Ci.nsIContentPolicy.ACCEPT;
}
// Deny all files
if (aContentLocation.scheme == "file") {
return Ci.nsIContentPolicy.REJECT_REQUEST;
}
// Allow view source
// if (aContentLocation.scheme == "view-source") {
// return Ci.nsIContentPolicy.ACCEPT;
// }
// If we had a whitelist, reject everything else
if (this.whitelist.length > 0) {
if (aContentType == Ci.nsIContentPolicy.TYPE_DOCUMENT) {
// Services.prompt.alert(null, "Webconverger", "Not allowed, whitelist only permits: " + this.whitelist.join(", "));
return Ci.nsIContentPolicy.REJECT_REQUEST;
}
}
// If there is no whitelist, allow everything (because we denied file URLs)
return Ci.nsIContentPolicy.ACCEPT;
},
shouldProcess: function(aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) {
return Ci.nsIContentPolicy.ACCEPT;
},
classDescription: "Webconverger FileBlock Service",
contractID: "@webconverger.com/fileblock-service;1",
classID: Components.ID('{607c1749-dc0a-463c-96cf-8ec6c3901319}'),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPolicy])
}
var NSGetFactory = XPCOMUtils.generateNSGetFactory([FileBlock]);
|
/*! supercache - v0.0.1
* Release on: 2014-12-13
* Copyright (c) 2014 Stéphane Bachelier
* Licensed MIT */
!function(a,b){"use strict";"function"==typeof define&&define.amd?define(function(){return b()}):"undefined"!=typeof exports?module.exports=b():a.supercache=b()}(this,function(){"use strict";var a=Object.create(null),b=function(b){a[b.req.url]={content:b.text,parse:b.req.parse[b.req.type]}},c=function(b){var c=a[b];return c&&c.content&&c.parse?c.parse(c.text):null},d=function(){a=null},e=function(a){a&&a.on("response",b)};return{writeToCache:e,readFromCache:c,clearCache:d}}); |
/* Ship.js
KC3改 Ship Object
*/
(function(){
"use strict";
var deferList = {};
window.KC3Ship = function( data, toClone ){
// 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, deep clone if demanded
} else {
if(!!toClone)
$.extend(true, this, 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 leave 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 175; };
// hard-coded at `Core.swf/vo.UserShipData.VHP` / `main.js#ShipModel.prototype.VHP`
KC3Ship.getMaxHpModernize = function() { return 2; };
// hard-coded at `Core.swf/vo.UserShipData.VAS` / `main.js#ShipModel.prototype.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 > 22 ? 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, fleet number (1-based)].
* return [-1, 0, 0] if this ship is not on any fleet.
*/
KC3Ship.prototype.fleetPosition = function(){
var position = -1,
total = 0,
fleetNum = 0;
if(this.exists()) {
fleetNum = this.onFleet();
if(fleetNum > 0) {
var fleet = PlayerManager.fleets[fleetNum - 1];
position = fleet.ships.indexOf(this.rosterId);
total = fleet.countShips();
}
}
return [position, total, fleetNum];
};
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 hpArr = optAfterHp ? this.afterHp : this.hp,
HPPercent = hpArr[0] / hpArr[1],
RepairCalc = PS['KanColle.RepairTime'];
var result = { akashi: 0 };
if (HPPercent > 0.5 && HPPercent < 1.00 && this.isFree()) {
var dockTimeMillis = optAfterHp ?
RepairCalc.dockingInSecJSNum(this.master().api_stype, this.level, hpArr[0], hpArr[1]) * 1000 :
this.repair[0];
var repairTime = KC3AkashiRepair.calculateRepairTime(dockTimeMillis);
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] ) */
Math.hrdInt('floor', this.repair[0], 3, 1);
}
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() && v > 1 ? 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 resupply value, not max value. and cannot be less than 1
result.fuel = marriageConserve(result.fuel);
result.ammo = marriageConserve(result.ammo);
if(bauxiteNeeded){
var slotsBauxiteCost = (current, max) => (
current < max ? (max - current) * KC3GearManager.carrierSupplyBauxiteCostPerSlot : 0
);
result.bauxite = self.equipment()
.map((g, i) => slotsBauxiteCost(self.slots[i], master.api_maxeq[i]))
.sumValues();
// 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;
};
/**
* Get or calculate repair cost of this ship.
* @param currentHp - assumed current HP value if this ship is not damaged effectively.
* @return an object: {fuel: <fuelCost>, steel: <steelCost>}
*/
KC3Ship.prototype.calcRepairCost = function(currentHp){
const result = {
fuel: 0, steel: 0
};
if(this.isDummy()) { return result; }
if(currentHp > 0 && currentHp <= this.hp[1]) {
// formula see http://kancolle.wikia.com/wiki/Docking
const fullFuel = this.master().api_fuel_max;
const hpLost = this.hp[1] - currentHp;
result.fuel = Math.floor(fullFuel * hpLost * 0.032);
result.steel = Math.floor(fullFuel * hpLost * 0.06);
} else {
result.fuel = this.repair[1];
result.steel = this.repair[2];
}
return result;
};
/**
* 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
ht: 0
};
// Limited to currently used stats only,
// all implemented see `KC3Meta.js#statApiNameMap`
const statApiNames = {
"tyku": "aa",
"souk": "ar",
"tais": "as",
"houk": "ev",
"houg": "fp",
"saku": "ls",
"raig": "tp",
"houm": "ht",
"leng": "rn",
"soku": "sp",
};
for(const apiName in statApiNames) {
const equipStats = this.equipmentTotalStats(apiName);
stats[statApiNames[apiName]] -= equipStats;
}
return !statAttr ? stats : stats[statAttr];
};
KC3Ship.prototype.statsBonusOnShip = function(statAttr){
if(this.isDummy()) { return false; }
const stats = {};
const statApiNames = {
"houg": "fp",
"souk": "ar",
"raig": "tp",
"houk": "ev",
"tyku": "aa",
"tais": "as",
"saku": "ls",
"houm": "ht",
"leng": "rn",
"soku": "sp",
};
for(const apiName in statApiNames) {
stats[statApiNames[apiName]] = this.equipmentTotalStats(apiName, true, true, true);
}
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,
isOnShipBonusIncluded = true, isOnShipBonusOnly = false,
includeEquipTypes = null, includeEquipIds = null,
excludeEquipTypes = null, excludeEquipIds = null){
var total = 0;
const bonusDefs = isOnShipBonusIncluded || isOnShipBonusOnly ? KC3Gear.explicitStatsBonusGears() : false;
// Accumulates displayed stats from equipment, and count for special equipment
this.equipment(isExslotIncluded).forEach(equip => {
if(equip.exists()) {
const gearMst = equip.master(),
mstId = gearMst.api_id,
type2 = gearMst.api_type[2];
if(Array.isArray(includeEquipTypes) &&
!includeEquipTypes.includes(type2) ||
Array.isArray(includeEquipIds) &&
!includeEquipIds.includes(mstId) ||
Array.isArray(excludeEquipTypes) &&
excludeEquipTypes.includes(type2) ||
Array.isArray(excludeEquipIds) &&
excludeEquipIds.includes(mstId)
) { return; }
total += gearMst["api_" + apiName] || 0;
if(bonusDefs) KC3Gear.accumulateShipBonusGear(bonusDefs, equip);
}
});
// Add explicit stats bonuses (not masked, displayed on ship) from equipment on specific ship
if(bonusDefs) {
const onShipBonus = KC3Gear.equipmentTotalStatsOnShipBonus(bonusDefs, this, apiName);
total = isOnShipBonusOnly ? onShipBonus : total + onShipBonus;
}
return total;
};
KC3Ship.prototype.equipmentBonusGearAndStats = function(newGearObj){
const newGearMstId = (newGearObj || {}).masterId;
let gearFlag = false;
let synergyFlag = false;
const bonusDefs = KC3Gear.explicitStatsBonusGears();
const synergyGears = bonusDefs.synergyGears;
const allGears = this.equipment(true);
allGears.forEach(g => g.exists() && KC3Gear.accumulateShipBonusGear(bonusDefs, g));
const masterIdList = allGears.map(g => g.masterId)
.filter((value, index, self) => value > 0 && self.indexOf(value) === index);
let bonusGears = masterIdList.map(mstId => bonusDefs[mstId])
.concat(masterIdList.map(mstId => {
const typeDefs = bonusDefs[`t2_${KC3Master.slotitem(mstId).api_type[2]}`];
if (!typeDefs) return; else return $.extend(true, {}, typeDefs);
}));
masterIdList.push(...masterIdList);
// Check if each gear works on the equipped ship
const shipId = this.masterId;
const originId = RemodelDb.originOf(shipId);
const ctype = String(this.master().api_ctype);
const stype = this.master().api_stype;
const checkByShip = (byShip, shipId, originId, stype, ctype) =>
(byShip.ids || []).includes(shipId) ||
(byShip.origins || []).includes(originId) ||
(byShip.stypes || []).includes(stype) ||
(byShip.classes || []).includes(Number(ctype)) ||
(!byShip.ids && !byShip.origins && !byShip.stypes && !byShip.classes);
// Check if ship is eligible for equip bonus and add synergy/id flags
bonusGears = bonusGears.filter((gear, idx) => {
if (!gear) { return false; }
const synergyFlags = [];
const synergyIds = [];
const matchGearByMstId = (g) => g.masterId === masterIdList[idx];
let flag = false;
for (const type in gear) {
if (type === "byClass") {
for (const key in gear[type]) {
if (key == ctype) {
if (Array.isArray(gear[type][key])) {
for (let i = 0; i < gear[type][key].length; i++) {
gear.path = gear.path || [];
gear.path.push(gear[type][key][i]);
}
} else {
gear.path = gear[type][key];
}
}
}
}
else if (type === "byShip") {
if (Array.isArray(gear[type])) {
for (let i = 0; i < gear[type].length; i++) {
if (checkByShip(gear[type][i], shipId, originId, stype, ctype)) {
gear.path = gear.path || [];
gear.path.push(gear[type][i]);
}
}
} else if (checkByShip(gear[type], shipId, originId, stype, ctype)) {
gear.path = gear[type];
}
}
if (gear.path) {
if (typeof gear.path !== "object") { gear.path = gear[type][gear.path]; }
if (!Array.isArray(gear.path)) { gear.path = [gear.path]; }
const count = gear.count;
for (let pathIdx = 0; pathIdx < gear.path.length; pathIdx++) {
const check = gear.path[pathIdx];
if (check.excludes && check.excludes.includes(shipId)) { continue; }
if (check.excludeOrigins && check.excludeOrigins.includes(originId)) { continue; }
if (check.excludeClasses && check.excludeClasses.includes(ctype)) { continue; }
if (check.excludeStypes && check.excludeStypes.includes(stype)) { continue; }
if (check.remodel && RemodelDb.remodelGroup(shipId).indexOf(shipId) < check.remodel) { continue; }
if (check.remodelCap && RemodelDb.remodelGroup(shipId).indexOf(shipId) > check.remodelCap) { continue; }
if (check.origins && !check.origins.includes(originId)) { continue; }
if (check.stypes && !check.stypes.includes(stype)) { continue; }
if (check.classes && !check.classes.includes(ctype)) { continue; }
// Known issue: exact corresponding stars will not be found since identical equipment merged
if (check.minStars && allGears.find(matchGearByMstId).stars < check.minStars) { continue; }
if (check.single) { gear.count = 1; flag = true; }
if (check.multiple) { gear.count = count; flag = true; }
// countCap/minCount take priority
if (check.countCap) { gear.count = Math.min(check.countCap, count); }
if (check.minCount) { gear.count = count; }
// Synergy check
if (check.synergy) {
let synergyCheck = check.synergy;
if (!Array.isArray(synergyCheck)) { synergyCheck = [synergyCheck]; }
for (let checkIdx = 0; checkIdx < synergyCheck.length; checkIdx++) {
const flagList = synergyCheck[checkIdx].flags;
for (let flagIdx = 0; flagIdx < flagList.length; flagIdx++) {
const equipFlag = flagList[flagIdx];
if (equipFlag.endsWith("Nonexist")) {
if (!synergyGears[equipFlag]) { break; }
} else if (synergyGears[equipFlag] > 0) {
if (synergyGears[equipFlag + "Ids"].includes(newGearMstId)) { synergyFlag = true; }
synergyFlags.push(equipFlag);
synergyIds.push(masterIdList.find(id => synergyGears[equipFlag + "Ids"].includes(id)));
}
}
}
flag |= synergyFlags.length > 0;
}
}
}
}
gear.synergyFlags = synergyFlags;
gear.synergyIds = synergyIds;
gear.byType = idx >= Math.floor(masterIdList.length / 2);
gear.id = masterIdList[idx];
return flag;
});
if (!bonusGears.length) { return false; }
// Trim bonus gear object and add icon ids
const byIdGears = bonusGears.filter(g => !g.byType).map(g => g.id);
const result = bonusGears.filter(g => !g.byType || !byIdGears.includes(g.id)).map(gear => {
const obj = {};
obj.count = gear.count;
const g = allGears.find(eq => eq.masterId === gear.id);
obj.name = g.name();
if (g.masterId === newGearMstId) { gearFlag = true; }
obj.icon = g.master().api_type[3];
obj.synergyFlags = gear.synergyFlags.filter((value, index, self) => self.indexOf(value) === index && !!value);
obj.synergyNames = gear.synergyIds.map(id => allGears.find(eq => eq.masterId === id).name());
obj.synergyIcons = obj.synergyFlags.map(flag => {
if (flag.includes("Radar")) { return 11; }
else if (flag.includes("Torpedo")) { return 5; }
else if (flag.includes("LargeGunMount")) { return 3; }
else if (flag.includes("MediumGunMount")) { return 2; }
else if (flag.includes("SmallGunMount")) { return 1; }
else if (flag.includes("skilledLookouts")) { return 32; }
else if (flag.includes("searchlight")) { return 24; }
else if (flag.includes("rotorcraft") || flag.includes("helicopter")) { return 21; }
else if (flag.includes("Boiler")) { return 19; }
return 0; // Unknown synergy type
});
return obj;
});
const stats = this.statsBonusOnShip();
return {
isShow: gearFlag || synergyFlag,
bonusGears: result,
stats: stats,
};
};
// 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, includeImprovedAttack = false, forExped = false){
var equipmentTotalAsw = 0;
if(!forExped) {
// When calculating asw warefare relevant thing,
// asw stat from these known types of equipment not taken into account:
// main gun, recon seaplane, seaplane/carrier fighter, radar, large flying boat, LBAA
// KC Vita counts only carrier bomber, seaplane bomber, sonar (both), depth charges, rotorcraft and as-pby.
// All visible bonuses from equipment not counted towards asw attacks for now.
const noCountEquipType2Ids = [1, 2, 3, 6, 10, 12, 13, 41, 45, 47];
if(!canAirAttack) {
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) {
// exclude carrier bomber, seaplane bomber, rotorcraft, as-pby too if not able to air attack
noCountEquipType2Ids.push(...[7, 8, 11, 25, 26, 57, 58]);
}
}
equipmentTotalAsw = this.equipment(true)
.map(g => g.exists() && g.master().api_tais > 0 &&
noCountEquipType2Ids.includes(g.master().api_type[2]) ? 0 : g.master().api_tais
+ (!!includeImprovedAttack && g.attackPowerImprovementBonus("asw"))
).sumValues();
} else {
// For expeditions, asw from aircraft affected by proficiency and equipped slot size:
// https://wikiwiki.jp/kancolle/%E9%81%A0%E5%BE%81#about_stat
// https://docs.google.com/spreadsheets/d/1o-_-I8GXuJDkSGH0Dhjo7mVYx9Kpay2N2h9H3HMyO_E/htmlview
equipmentTotalAsw = this.equipment(true)
.map((g, i) => g.exists() && g.master().api_tais > 0 &&
// non-aircraft counts its actual asw value, land base plane cannot be used by expedition anyway
!KC3GearManager.carrierBasedAircraftType3Ids.includes(g.master().api_type[3]) ? g.master().api_tais :
// aircraft in 0-size slot take no effect, and
// current formula for 0 proficiency aircraft only,
// max level may give additional asw up to +2
(!this.slotSize(i) ? 0 : Math.floor(g.master().api_tais * (0.65 + 0.1 * Math.sqrt(Math.max(0, this.slotSize(i) - 2)))))
).sumValues()
// unconfirmed: all visible bonuses counted? or just like OASW, only some types counted? or none counted?
+ this.equipmentTotalStats("tais", true, true, true/*, null, null, [1, 6, 7, 8]*/);
}
return equipmentTotalAsw;
};
// estimated basic stats without equipments based on master data and modernization
KC3Ship.prototype.estimateNakedStats = function(statAttr) {
if(this.isDummy()) { return false; }
const shipMst = this.master();
if(!shipMst) { return false; }
const stats = {
fp: shipMst.api_houg[0] + this.mod[0],
tp: shipMst.api_raig[0] + this.mod[1],
aa: shipMst.api_tyku[0] + this.mod[2],
ar: shipMst.api_souk[0] + this.mod[3],
lk: shipMst.api_luck[0] + this.mod[4],
hp: this.maxHp(false) + (this.mod[5] || 0),
};
// shortcuts for following funcs
if(statAttr === "ls") return this.estimateNakedLoS();
if(statAttr === "as") return this.estimateNakedAsw() + (this.mod[6] || 0);
if(statAttr === "ev") return this.estimateNakedEvasion();
return !statAttr ? stats : stats[statAttr];
};
// 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;
};
// estimated the base value (on lv1) of the 3-stats (evasion, asw, los) missing in master data,
// based on current naked stats and max value (on lv99),
// in case whoever wanna submit this in order to collect ship's exact stats quickly.
// NOTE: naked stats needed, so should ensure no equipment equipped or at least no on ship bonus.
// btw, exact evasion and asw values can be found at in-game picture book api data, but los missing still.
KC3Ship.prototype.estimateBaseMasterStats = function() {
if(this.isDummy()) { return false; }
const info = {
// evasion for ship should be `api_kaih`, here uses gear one instead
houk: [0, this.ev[1], this.ev[0]],
tais: [0, this.as[1], this.as[0]],
saku: [0, this.ls[1], this.ls[0]],
};
const level = this.level;
Object.keys(info).forEach(apiName => {
const lv99Stat = info[apiName][1];
const nakedStat = info[apiName][2] - this.equipmentTotalStats(apiName);
info[apiName][3] = nakedStat;
if(level && level > 99) {
info[apiName][0] = false;
} else {
info[apiName][0] = WhoCallsTheFleetDb.estimateStatBase(nakedStat, lv99Stat, level);
// try to get stats on maxed married level too
info[apiName][4] = WhoCallsTheFleetDb.estimateStat({base: info[apiName][0], max: lv99Stat}, KC3Ship.getMaxLevel());
}
});
info.level = level;
info.mstId = this.masterId;
info.equip = this.equipment(true).map(g => g.masterId);
return info;
};
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.175 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};
};
/**
* Static method of the same logic to find available damecon to be used first.
* @param equipArray - the master ID array of ship's all equipment including ex-slot at the last.
* for 5-slot ship, array supposed to be 6 elements; otherwise should be always 5 elements.
* @see KC3Ship.prototype.findDameCon
* @see main.js#ShipModelReplica.prototype.useRepairItem - the repair items using order and the type codes
*/
KC3Ship.findDamecon = function(equipArray = []) {
// push last item from ex-slot to 1st
const sortedMstIds = equipArray.slice(-1);
sortedMstIds.push(...equipArray.slice(0, -1));
const dameconId = sortedMstIds.find(id => id === 42 || id === 43);
// code 1 for repair team, 2 for repair goddess
return dameconId === 42 ? 1 : dameconId === 43 ? 2 : 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));
const reconModifier = this.fighterPowerReconModifier(forLbas);
return [
Math.floor(powerBounds.map(b => b[0]).sumValues() * reconModifier),
Math.floor(powerBounds.map(b => b[1]).sumValues() * reconModifier)
];
};
/**
* @return value under verification of LB Recon modifier to LBAS sortie fighter power.
*/
KC3Ship.prototype.fighterPowerReconModifier = function(forLbas = false){
var reconModifier = 1;
this.equipment(function(id, idx, gear){
if(!id || gear.isDummy()){ return; }
const type2 = gear.master().api_type[2];
// LB Recon Aircraft
if(forLbas && type2 === 49){
const los = gear.master().api_saku;
reconModifier = Math.max(reconModifier,
los >= 9 ? 1.18 : 1.15
);
}
});
return reconModifier;
};
/* 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 || gear.isDummy()){ return; }
const type2 = gear.master().api_type[2];
if(KC3GearManager.landBaseReconnType2Ids.includes(type2)){
const los = gear.master().api_saku;
// Carrier Recon Aircraft
if(type2 === 9){
reconModifier = Math.max(reconModifier,
(los <= 7) ? 1.2 :
(los >= 9) ? 1.3 :
1.2 // unknown
);
// LB Recon Aircraft
} else if(type2 === 49){
reconModifier = Math.max(reconModifier,
(los <= 7) ? 1.18 : // unknown
(los >= 9) ? 1.23 :
1.18
);
// Recon Seaplane, Flying Boat, etc
} else {
reconModifier = Math.max(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.estimateNakedStats("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 {
// Explicit fire power bonus from equipment on specific ship taken into account:
// http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:2354#13
// so better to use current fp value from `api_karyoku` (including naked fp + all equipment fp),
// to avoid the case that fp bonus not accurately updated in time.
supportPower = 5 + this.fp[0] - 1;
// should be the same value with above if `equipmentTotalStats` works properly
//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.
* @param {boolean} isTargetLand - if the power is applied to a land-installation target.
* @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, isTargetLand = false){
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) {
if(isTargetLand) {
// https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#od036af3
// https://wikiwiki.jp/kancolle/%E5%AF%BE%E5%9C%B0%E6%94%BB%E6%92%83#AGCalcCV
// TP from all Torpedo Bombers not taken into account, DV power counted,
// current TB with DV power: TBM-3W+3S
// Regular Dive Bombers make carrier cannot attack against land-installation,
// except following: Ju87C Kai, Prototype Nanzan, F4U-1D, FM-2, Ju87C Kai Ni (variants),
// Suisei Model 12 (634 Air Group w/Type 3 Cluster Bombs)
// DV power from items other than previous ones should not be counted
const tbBaku = this.equipmentTotalStats("baku", true, false, false, [8, 58]);
const dbBaku = this.equipmentTotalStats("baku", true, false, false, [7, 57],
KC3GearManager.antiLandDiveBomberIds);
shellingPower += Math.floor(1.3 * (tbBaku + dbBaku));
} else {
// Should limit to TP from equippable aircraft?
// TP visible bonus from Torpedo Bombers no effect.
// DV visible bonus not implemented yet, unknown.
shellingPower += this.equipmentTotalStats("raig", true, false);
shellingPower += Math.floor(1.3 * this.equipmentTotalStats("baku"), true, false);
}
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");
};
KC3Ship.prototype.isAswAirAttack = function(){
// check asw attack type, 1530 is Abyssal Submarine Ka-Class
return this.estimateDayAttackType(1530, false)[0] === "AirAttack";
};
/**
* 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 isAirAttack = this.isAswAirAttack();
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?
let synergyModifier = 1;
// new DC + DCP synergy (x1.1 / x1.25)
const isNewDepthChargeEquipped = this.equipment(true).some(g => g.isDepthCharge());
const isDepthChargeProjectorEquipped = this.equipment(true).some(g => g.isDepthChargeProjector());
if(isNewDepthChargeEquipped && isDepthChargeProjectorEquipped) {
// Large Sonar, like T0 Sonar, not counted here
const isSonarEquipped = this.hasEquipmentType(2, 14);
synergyModifier = isSonarEquipped ? 1.25 : 1.1;
}
// legacy all types of sonar + all DC(P) synergy (x1.15)
synergyModifier *= this.hasEquipmentType(3, 18) && this.hasEquipmentType(3, 17) ? 1.15 : 1;
aswPower *= synergyModifier;
return aswPower;
};
/**
* Get anti-installation power against all possible types of installations.
* Will choose meaningful installation types based on current equipment.
* Special attacks and battle conditions are not taken into consideration.
* @return {array} with element {Object} that has attributes:
* * enemy: Enemy ID to get icon
* * dayPower: Day attack power of ship
* * nightPower: Night attack power of ship
* * modifiers: Known anti-installation modifiers
* * damagedPowers: Day & night attack power tuple on Chuuha ship
* @see estimateInstallationEnemyType for kc3-unique installation types
*/
KC3Ship.prototype.shipPossibleAntiLandPowers = function(){
if(this.isDummy()) { return []; }
let possibleTypes = [];
const hasAntiLandRocket = this.hasEquipment([126, 346, 347, 348, 349]);
const hasT3Shell = this.hasEquipmentType(2, 18);
const hasLandingCraft = this.hasEquipmentType(2, [24, 46]);
// WG42 variants/landing craft-type eligible for all
if (hasAntiLandRocket || hasLandingCraft){
possibleTypes = [1, 2, 3, 4, 5, 6];
}
// T3 Shell eligible for all except Pillbox
else if(hasT3Shell){
possibleTypes = [1, 3, 4, 5, 6];
}
// Return empty if no anti-installation weapon found
else {
return [];
}
// Dummy target enemy IDs, also used for abyssal icons
// 1573: Harbor Princess, 1665: Artillery Imp, 1668: Isolated Island Princess
// 1656: Supply Depot Princess - Damaged, 1699: Summer Harbor Princess
// 1753: Summer Supply Depot Princess
const dummyEnemyList = [1573, 1665, 1668, 1656, 1699, 1753];
const basicPower = this.shellingFirePower();
const resultList = [];
// Fill damage lists for each enemy type
possibleTypes.forEach(installationType => {
const obj = {};
const dummyEnemy = dummyEnemyList[installationType - 1];
// Modifiers from special attacks, battle conditions are not counted for now
const fixedPreConds = ["Shelling", 1, undefined, [], false, false, dummyEnemy],
fixedPostConds = ["Shelling", [], 0, false, false, 0, false, dummyEnemy];
const {power: precap, antiLandModifier, antiLandAdditive} = this.applyPrecapModifiers(basicPower, ...fixedPreConds);
let {power} = this.applyPowerCap(precap, "Day", "Shelling");
const postcapInfo = this.applyPostcapModifiers(power, ...fixedPostConds);
power = postcapInfo.power;
obj.enemy = dummyEnemy;
obj.modifiers = {
antiLandModifier,
antiLandAdditive,
postCapAntiLandModifier: postcapInfo.antiLandModifier,
postCapAntiLandAdditive: postcapInfo.antiLandAdditive
};
obj.dayPower = Math.floor(power);
// Still use day time pre-cap shelling power, without TP value.
// Power constant +5 included, if assumes night contact is triggered.
power = precap;
({power} = this.applyPowerCap(power, "Night", "Shelling"));
({power} = this.applyPostcapModifiers(power, ...fixedPostConds));
obj.nightPower = Math.floor(power);
// Get Chuuha day attack power (in case of nuke setups)
fixedPreConds.push("chuuha");
const {power: damagedPrecap} = this.applyPrecapModifiers(basicPower, ...fixedPreConds);
({power} = this.applyPowerCap(damagedPrecap, "Day", "Shelling"));
({power} = this.applyPostcapModifiers(power, ...fixedPostConds));
obj.damagedPowers = [Math.floor(power)];
// Get Chuuha night power
({power} = this.applyPowerCap(damagedPrecap, "Night", "Shelling"));
({power} = this.applyPostcapModifiers(power, ...fixedPostConds));
obj.damagedPowers.push(Math.floor(power));
resultList.push(obj);
});
return resultList;
};
/**
* Calculate landing craft pre-cap/post-cap bonus depending on installation type.
* @param installationType - kc3-unique installation types
* @return {number} multiplier of landing craft
* @see estimateInstallationEnemyType
* @see http://kancolle.wikia.com/wiki/Partials/Anti-Installation_Weapons
* @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#antiground
*/
KC3Ship.prototype.calcLandingCraftBonus = function(installationType = 0){
if(this.isDummy() || ![1, 2, 3, 4, 5, 6].includes(installationType)) { return 0; }
// 6 types of Daihatsu Landing Craft with known bonus:
// * 167: Special Type 2 Amphibious Tank
// * 166: Daihatsu Landing Craft (Type 89 Medium Tank & Landing Force)
// * 68 : Daihatsu Landing Craft
// * 230: Toku Daihatsu Landing Craft + 11th Tank Regiment
// * 193: Toku Daihatsu Landing Craft (most bonuses unknown)
// * 355: M4A1 DD
const landingCraftIds = [167, 166, 68, 230, 193, 355];
const landingCraftCounts = landingCraftIds.map(id => this.countEquipment(id));
const landingModifiers = KC3GearManager.landingCraftModifiers[installationType - 1] || {};
const getModifier = (type, forImp = false) => (
(landingModifiers[forImp ? "improvement" : "modifier"] || [])[type] || (forImp ? 0 : 1)
);
let tankBonus = 1;
const landingBonus = [1], landingImprovementBonus = [0];
/**
* Highest landing craft modifier is selected
* (Speculative) Then, highest landing craft improvement modifier is selected
* If two or more of the same equipment present, take average improvement level
*
* Then, multiply total landing modifier with tank modifier
* There are some enemies with recorded modifiers for two or more of same equipment,
* those will take priority
*/
// Arrange equipment in terms of priority
landingCraftCounts.forEach((count, type) => {
let improvement = 0;
this.equipment().forEach((g, i) => {
if(g.exists() && g.masterId === landingCraftIds[type]) {
improvement += g.stars;
}
});
// Two (or more) Type 2 Tank bonus (Currently only for Supply Depot and Pillbox)
if(count > 1 && type === 0 && [2, 4].includes(installationType)) {
tankBonus = installationType === 2 ? 3.2 : 2.5;
tankBonus *= 1 + improvement / count / 30;
}
// Type 2 Tank bonus
else if(count > 0 && type === 0) {
tankBonus = getModifier(type) + getModifier(type, true) * improvement / count;
}
// Bonus for two Type 89 Tank (Pillbox, Supply Depot and Isolated Island)
else if(count > 1 && type === 1 && [2, 3, 4].includes(installationType)) {
landingBonus.push(installationType === 4 ? 2.08 : 3 );
landingImprovementBonus.push((installationType === 4 ? 0.0416 : 0.06) * improvement / count);
}
// Otherwise, match modifier and improvement
else if(count > 0) {
landingBonus.push(getModifier(type));
landingImprovementBonus.push(getModifier(type, true) * improvement / count);
}
});
// Multiply modifiers
return tankBonus * (Math.max(...landingBonus) + Math.max(...landingImprovementBonus));
};
/**
* Get anti land installation power bonus & multiplier of this ship.
* @param targetShipMasterId - target land installation master ID.
* @param precap - type of bonus, false for post-cap, pre-cap by default.
* @param warfareType - to indicate if use different modifiers for phases other than day shelling.
* @see https://kancolle.fandom.com/wiki/Combat/Installation_Type
* @see https://wikiwiki.jp/kancolle/%E5%AF%BE%E5%9C%B0%E6%94%BB%E6%92%83#AGBonus
* @see https://twitter.com/T3_1206/status/994258061081505792
* @see https://twitter.com/KennethWWKK/status/1045315639127109634
* @see https://yy406myon.hatenablog.jp/entry/2018/09/14/213114
* @see https://cdn.discordapp.com/attachments/425302689887289344/614879250419417132/ECrra66VUAAzYMc.jpg_orig.jpg
* @see https://github.com/Nishisonic/UnexpectedDamage/blob/master/UnexpectedDamage.js
* @see estimateInstallationEnemyType
* @see calcLandingCraftBonus
* @return {Array} of [additive damage boost, multiplicative damage boost, precap submarine additive, precap tank additive, precap m4a1dd multiplicative]
*/
KC3Ship.prototype.antiLandWarfarePowerMods = function(targetShipMasterId = 0, precap = true, warfareType = "Shelling"){
if(this.isDummy()) { return [0, 1]; }
const installationType = this.estimateInstallationEnemyType(targetShipMasterId, precap);
if(!installationType) { return [0, 1]; }
const wg42Count = this.countEquipment(126);
const mortarCount = this.countEquipment(346);
const mortarCdCount = this.countEquipment(347);
const type4RocketCount = this.countEquipment(348);
const type4RocketCdCount = this.countEquipment(349);
const hasT3Shell = this.hasEquipmentType(2, 18);
const alDiveBomberCount = this.countEquipment(KC3GearManager.antiLandDiveBomberIds);
let wg42Bonus = 1;
let type4RocketBonus = 1;
let mortarBonus = 1;
let t3Bonus = 1;
let apShellBonus = 1;
let seaplaneBonus = 1;
let alDiveBomberBonus = 1;
let airstrikeBomberBonus = 1;
const submarineBonus = this.isSubmarine() ? 30 : 0;
const landingBonus = this.calcLandingCraftBonus(installationType);
const shikonCount = this.countEquipment(230);
const m4a1ddCount = this.countEquipment(355);
const shikonBonus = 25 * (shikonCount + m4a1ddCount);
const m4a1ddModifier = m4a1ddCount ? 1.4 : 1;
if(precap) {
// [0, 70, 110, 140, 160] additive for each WG42 from PSVita KCKai, unknown for > 4
const wg42Additive = !wg42Count ? 0 : [0, 75, 110, 140, 160][wg42Count] || 160;
const type4RocketAdditive = !type4RocketCount ? 0 : [0, 55, 115, 160, 190][type4RocketCount] || 190;
const type4RocketCdAdditive = !type4RocketCdCount ? 0 : [0, 80, 170][type4RocketCdCount] || 170;
const mortarAdditive = !mortarCount ? 0 : [0, 30, 55, 75, 90][mortarCount] || 90;
const mortarCdAdditive = !mortarCdCount ? 0 : [0, 60, 110, 150][mortarCdCount] || 150;
const rocketsAdditive = wg42Additive + type4RocketAdditive + type4RocketCdAdditive + mortarAdditive + mortarCdAdditive;
switch(installationType) {
case 1: // Soft-skinned, general type of land installation
// 2.5x multiplicative for at least one T3
t3Bonus = hasT3Shell ? 2.5 : 1;
seaplaneBonus = this.hasEquipmentType(2, [11, 45]) ? 1.2 : 1;
wg42Bonus = [1, 1.3, 1.82][wg42Count] || 1.82;
type4RocketBonus = [1, 1.25, 1.25 * 1.5][type4RocketCount + type4RocketCdCount] || 1.875;
mortarBonus = [1, 1.2, 1.2 * 1.3][mortarCount + mortarCdCount] || 1.56;
return [rocketsAdditive,
t3Bonus * seaplaneBonus * wg42Bonus * type4RocketBonus * mortarBonus * landingBonus,
submarineBonus, shikonBonus, m4a1ddModifier];
case 2: // Pillbox, Artillery Imp
// Works even if slot is zeroed
seaplaneBonus = this.hasEquipmentType(2, [11, 45]) ? 1.5 : 1;
alDiveBomberBonus = [1, 1.5, 1.5 * 2.0][alDiveBomberCount] || 3;
// DD/CL bonus
const lightShipBonus = [2, 3].includes(this.master().api_stype) ? 1.4 : 1;
// Multiplicative WG42 bonus
wg42Bonus = [1, 1.6, 2.72][wg42Count] || 2.72;
type4RocketBonus = [1, 1.5, 1.5 * 1.8][type4RocketCount + type4RocketCdCount] || 2.7;
mortarBonus = [1, 1.3, 1.3 * 1.5][mortarCount + mortarCdCount] || 1.95;
apShellBonus = this.hasEquipmentType(2, 19) ? 1.85 : 1;
// Set additive modifier, multiply multiplicative modifiers
return [rocketsAdditive,
seaplaneBonus * alDiveBomberBonus * lightShipBonus
* wg42Bonus * type4RocketBonus * mortarBonus * apShellBonus * landingBonus,
submarineBonus, shikonBonus, m4a1ddModifier];
case 3: // Isolated Island Princess
alDiveBomberBonus = [1, 1.4, 1.4 * 1.75][alDiveBomberCount] || 2.45;
t3Bonus = hasT3Shell ? 1.75 : 1;
wg42Bonus = [1, 1.4, 2.1][wg42Count] || 2.1;
type4RocketBonus = [1, 1.3, 1.3 * 1.65][type4RocketCount + type4RocketCdCount] || 2.145;
mortarBonus = [1, 1.2, 1.2 * 1.4][mortarCount + mortarCdCount] || 1.68;
// Set additive modifier, multiply multiplicative modifiers
return [rocketsAdditive, alDiveBomberBonus * t3Bonus
* wg42Bonus * type4RocketBonus * mortarBonus * landingBonus,
0, shikonBonus, m4a1ddModifier];
case 5: // Summer Harbor Princess
seaplaneBonus = this.hasEquipmentType(2, [11, 45]) ? 1.3 : 1;
alDiveBomberBonus = [1, 1.3, 1.3 * 1.2][alDiveBomberCount] || 1.56;
wg42Bonus = [1, 1.4, 2.1][wg42Count] || 2.1;
t3Bonus = hasT3Shell ? 1.75 : 1;
type4RocketBonus = [1, 1.25, 1.25 * 1.4][type4RocketCount + type4RocketCdCount] || 1.75;
mortarBonus = [1, 1.1, 1.1 * 1.15][mortarCount + mortarCdCount] || 1.265;
apShellBonus = this.hasEquipmentType(2, 19) ? 1.3 : 1;
// Set additive modifier, multiply multiplicative modifiers
return [rocketsAdditive, seaplaneBonus * alDiveBomberBonus * t3Bonus
* wg42Bonus * type4RocketBonus * mortarBonus * apShellBonus * landingBonus,
0, shikonBonus, m4a1ddModifier];
}
} else { // Post-cap types
switch(installationType) {
case 2: // Pillbox, Artillery Imp
// Dive Bomber, Seaplane Bomber, LBAA, Jet Bomber on airstrike phase
airstrikeBomberBonus = warfareType === "Aerial" &&
this.hasEquipmentType(2, [7, 11, 47, 57]) ? 1.55 : 1;
return [0, airstrikeBomberBonus, 0, 0, 1];
case 3: // Isolated Island Princess
airstrikeBomberBonus = warfareType === "Aerial" &&
this.hasEquipmentType(2, [7, 11, 47, 57]) ? 1.7 : 1;
return [0, airstrikeBomberBonus, 0, 0, 1];
case 4: // Supply Depot Princess
wg42Bonus = [1, 1.45, 1.625][wg42Count] || 1.625;
type4RocketBonus = [1, 1.2, 1.2 * 1.4][type4RocketCount + type4RocketCdCount] || 1.68;
mortarBonus = [1, 1.15, 1.15 * 1.2][mortarCount + mortarCdCount] || 1.38;
return [0, wg42Bonus * type4RocketBonus * mortarBonus * landingBonus, 0, 0, 1];
case 6: // Summer Supply Depot Princess (shikon bonus only)
return [0, landingBonus, 0, 0, 1];
}
}
return [0, 1, 0, 0, 1];
};
/**
* 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; }
// Night contact power bonus based on recon accuracy value: 1: 5, 2: 7, >=3: 9
// but currently only Type 98 Night Recon implemented (acc: 1), so always +5
return (isNightContacted ? 5 : 0) + this.fp[0] + this.tp[0]
+ this.equipmentTotalImprovementBonus("yasen");
};
/**
* Get pre-cap carrier night aerial attack power of this ship.
* This formula is the same with the one above besides slot bonus part and filtered equipment stats.
* @see http://kancolle.wikia.com/wiki/Damage_Calculation
* @see https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#nightAS
* @see https://wikiwiki.jp/kancolle/%E5%AF%BE%E5%9C%B0%E6%94%BB%E6%92%83#AGCalcCVN
*/
KC3Ship.prototype.nightAirAttackPower = function(isNightContacted = false, isTargetLand = false){
if(this.isDummy()) { return 0; }
const equipTotals = {
fp: 0, tp: 0, dv: 0, slotBonus: 0, improveBonus: 0
};
// Generally, power from only night capable aircraft will be taken into account.
// For Ark Royal (Kai) + Swordfish - Night Aircraft (despite of NOAP), only Swordfish counted.
const isThisArkRoyal = [515, 393].includes(this.masterId);
const isLegacyArkRoyal = isThisArkRoyal && !this.canCarrierNightAirAttack();
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]);
// Swordfish variants as special torpedo bombers
const isSwordfish = [242, 243, 244].includes(gear.masterId);
// Zero Fighter Model 62 (Fighter-bomber Iwai Squadron)
// Suisei Model 12 (Type 31 Photoelectric Fuze Bombs)
const isSpecialNightPlane = [154, 320].includes(gear.masterId);
const isNightPlane = isLegacyArkRoyal ? isSwordfish :
isNightAircraftType || isSwordfish || isSpecialNightPlane;
if(isNightPlane && slot > 0) {
equipTotals.fp += master.api_houg || 0;
if(!isTargetLand) equipTotals.tp += master.api_raig || 0;
equipTotals.dv += master.api_baku || 0;
if(!isLegacyArkRoyal) {
// Bonus from night aircraft slot which also takes bombing and asw stats into account
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");
}
}
});
// No effect for both visible fp and tp bonus
let shellingPower = this.estimateNakedStats("fp");
shellingPower += equipTotals.fp + equipTotals.tp + equipTotals.dv;
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, targetShipMasterId = 0,
damageStatus = this.damageStatus()){
// Engagement modifier
let engagementModifier = (warfareType === "Aerial" ? [] : [0, 1, 0.8, 1.2, 0.6])[engagementId] || 1;
// Formation modifier, about formation IDs:
// 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
let formationModifier = (
warfareType === "Antisub" ?
[0, 0.6, 0.8, 1.2, 1.1 , 1.3, 1, 0, 0, 0, 0, 1.3, 1.1, 1 , 0.7] :
warfareType === "Shelling" ?
[0, 1 , 0.8, 0.7, 0.75, 0.6, 1, 0, 0, 0, 0, 0.8, 1 , 0.7, 1.1] :
warfareType === "Torpedo" ?
[0, 1 , 0.8, 0.7, 0.6 , 0.6, 1, 0, 0, 0, 0, 0.8, 1 , 0.7, 1.1] :
// other warefare types like Aerial Opening Airstrike not affected
[]
)[formationId] || 1;
// TODO Any side Echelon vs Combined Fleet, shelling mod is 0.6?
// 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
// Vanguard still applies for night battle
if(isNightBattle && !canNightAntisub) {
engagementModifier = 1;
formationModifier = formationId !== 6 ? 1 : formationModifier;
}
// Damage percent modifier
// http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#m8aa1749
const damageModifier = (!isNightBattle && warfareType === "Torpedo" ? {
// Day time only affect Opening Torpedo in fact, Chuuha cannot Closing at all
// Night time unmentioned, assume to be the same with shelling
"chuuha": 0.8,
"taiha": 0.0
} : (isNightBattle && warfareType === "Torpedo") || warfareType === "Shelling" || warfareType === "Antisub" ? {
"chuuha": 0.7,
"taiha": 0.4
} : // Aerial Opening Airstrike not affected
{})[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;
// Anti-installation modifiers
const targetShipType = this.estimateTargetShipType(targetShipMasterId);
let antiLandAdditive = 0, antiLandModifier = 1, subAntiLandAdditive = 0, tankAdditive = 0, tankModifier = 1;
if(targetShipType.isLand) {
[antiLandAdditive, antiLandModifier, subAntiLandAdditive, tankAdditive, tankModifier] = this.antiLandWarfarePowerMods(targetShipMasterId, true, warfareType);
}
// Apply modifiers, flooring unknown, multiply and add anti-land modifiers first
let result = (((basicPower + subAntiLandAdditive) * antiLandModifier + tankAdditive) * tankModifier + antiLandAdditive)
* 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 && warfareType !== "Antisub") {
// 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,
antiLandModifier,
antiLandAdditive,
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
* @see https://github.com/Nishisonic/UnexpectedDamage/blob/master/UnexpectedDamage.js
*/
KC3Ship.prototype.applyPostcapModifiers = function(cappedPower, warfareType = "Shelling",
daySpecialAttackType = [], contactPlaneId = 0, isCritical = false, isAirAttack = false,
targetShipStype = 0, isDefenderArmorCounted = false, targetShipMasterId = 0){
// 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;
}
const isNightBattle = daySpecialAttackType.length === 0;
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(targetShipStype);
if(isTargetShipTypeMatched && !isNightBattle) {
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;
}
});
}
}
const targetShipType = this.estimateTargetShipType(targetShipMasterId);
// Against PT Imp modifier
let antiPtImpModifier = 1;
if(targetShipType.isPtImp) {
const lightGunBonus = this.countEquipmentType(2, 1) >= 2 ? 1.2 : 1;
const aaGunBonus = this.countEquipmentType(2, 21) >= 2 ? 1.1 : 1;
const secondaryGunBonus = this.countEquipmentType(2, 4) >= 2 ? 1.2 : 1;
const t3Bonus = this.hasEquipmentType(2, 18) ? 1.3 : 1;
antiPtImpModifier = lightGunBonus * aaGunBonus * secondaryGunBonus * t3Bonus;
}
// Anti-installation modifier
let antiLandAdditive = 0, antiLandModifier = 1;
if(targetShipType.isLand) {
[antiLandAdditive, antiLandModifier] = this.antiLandWarfarePowerMods(targetShipMasterId, false, warfareType);
}
// About rounding and position of anti-land modifier:
// http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:925#33
let result = Math.floor(Math.floor(
Math.floor(cappedPower * antiLandModifier + antiLandAdditive) * apshellModifier
) * criticalModifier * proficiencyCriticalModifier
) * dayCutinModifier * airstrikeConcatModifier
* antiPtImpModifier;
// 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,
antiPtImpModifier,
antiLandAdditive,
antiLandModifier,
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) {
// differentiated 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 specified equipment (or equip type) can be equipped on this ship.
KC3Ship.prototype.canEquip = function(gearMstId, gearType2) {
return KC3Master.equip_on_ship(this.masterId, gearMstId, gearType2);
};
// check if this ship is capable of equipping Amphibious Tank (Ka-Mi tank only for now, no landing craft variants)
KC3Ship.prototype.canEquipTank = function() {
if(this.isDummy()) { return false; }
return KC3Master.equip_type(this.master().api_stype, this.masterId).includes(46);
};
// check if this ship is capable of equipping Daihatsu (landing craft variants, amphibious tank not counted)
KC3Ship.prototype.canEquipDaihatsu = function() {
if(this.isDummy()) { return false; }
const master = this.master();
// Phase2 method: lookup Daihatsu type2 ID 24 in her master equip types
return KC3Master.equip_type(master.api_stype, this.masterId).includes(24);
// Phase1 method:
/*
// 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, 3, 9].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; }
const masterId = this.masterId,
stype = this.master().api_stype;
// Phase2 method: lookup FCF type2 ID 34 in her master equip types
return KC3Master.equip_type(stype, masterId).includes(34);
// Phase1 method:
/*
// 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 Shiratsuyu K2, DD Murasame K2, AO Kamoi Kai-Bo, DD Yuugumo K2, DD Naganami K2, DD Shiranui K2
const capableShips = [464, 497, 498, 500, 542, 543, 567];
// CVL Kasugamaru
const incapableShips = [521];
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, Janus Kai, Samuel B.Roberts Kai, Fletcher-Class, Yuubari K2D
return [141, 478, 394, 893, 681, 562, 689, 596, 624, 628, 629, 692].includes(this.masterId);
};
/**
* Test to see if this ship (with equipment) is capable of opening ASW. References:
* @see https://kancolle.fandom.com/wiki/Partials/Opening_ASW
* @see https://wikiwiki.jp/kancolle/%E5%AF%BE%E6%BD%9C%E6%94%BB%E6%92%83#oasw
*/
KC3Ship.prototype.canDoOASW = function (aswDiff = 0) {
if(this.isDummy()) { return false; }
if(this.isOaswShip()) { return true; }
const stype = this.master().api_stype;
const isEscort = stype === 1;
const isLightCarrier = stype === 7;
// is CVE? (Taiyou-class series, Gambier Bay series, Zuihou K2B)
const isEscortLightCarrier = this.isEscortLightCarrier();
// is regular ASW method not supposed to depth charge attack? (CAV, BBV, AV, LHA)
// but unconfirmed for AO and Hayasui Kai
const isAirAntiSubStype = [6, 10, 16, 17].includes(stype);
// is Sonar equipped? also counted large one: Type 0 Sonar
const hasSonar = this.hasEquipmentType(1, 10);
const isHyuugaKaiNi = this.masterId === 554;
const isKagaK2Go = this.masterId === 646;
// lower condition for DE and CVL, even lower if equips Sonar
const aswThreshold = isLightCarrier && hasSonar ? 50
: isEscort ? 60
// May apply to CVL, but only CVE can reach 65 for now (Zuihou K2 modded asw +9 +13x4 = 61)
: isEscortLightCarrier ? 65
// Kaga Kai Ni Go asw starts from 82 on Lv84, let her pass just like Hyuuga K2
: isKagaK2Go ? 80
// Hyuuga Kai Ni can OASW even asw < 100, but lower threshold unknown,
// guessed from her Lv90 naked asw 79 + 12 (1x helicopter, without bonus and mod)
: isHyuugaKaiNi ? 90
: 100;
// ship stats not updated in time when equipment changed, so take the diff if necessary,
// and explicit asw bonus from Sonars taken into account confirmed.
const shipAsw = this.as[0] + aswDiff
// Visible asw bonus from Fighters, Dive Bombers and Torpedo Bombers still not counted,
// confirmed since 2019-06-29: https://twitter.com/trollkin_ball/status/1144714377024532480
// 2019-08-08: https://wikiwiki.jp/kancolle/%E5%AF%BE%E6%BD%9C%E6%94%BB%E6%92%83#trigger_conditions
// but bonus from other aircraft like Rotorcraft not (able to be) confirmed,
// perhaps a similar logic to exclude some types of equipment, see #effectiveEquipmentTotalAsw
// Green (any small?) gun (DE +1 asw from 12cm Single High-angle Gun Mount Model E) not counted,
// confirmed since 2020-06-19: https://twitter.com/99_999999999/status/1273937773225893888
- this.equipmentTotalStats("tais", true, true, true, [1, 6, 7, 8]);
// shortcut on the stricter condition first
if (shipAsw < aswThreshold)
return false;
// For CVE like Taiyou-class, initial asw stat is high enough to reach 50 / 65,
// but for Kasugamaru, since not possible to reach high asw for now, tests are not done.
// For Taiyou-class Kai/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 OASW still can be performed. only Sonar equipped can do neither.
// For other CVL possible but hard to reach 50 asw and do OASW with Sonar and high ASW aircraft.
// For CV Kaga K2Go, can perform OASW with any asw aircraft like Taiyou-class Kai+:
// https://twitter.com/noobcyan/status/1299886834919510017
if(isLightCarrier || isKagaK2Go) {
const isTaiyouKaiAfter = RemodelDb.remodelGroup(521).indexOf(this.masterId) > 1
|| RemodelDb.remodelGroup(534).indexOf(this.masterId) > 0;
const hasAswAircraft = this.equipment(true).some(gear => gear.isAswAircraft(false));
return ((isTaiyouKaiAfter || isKagaK2Go) && hasAswAircraft) // ship visible asw irrelevant
|| this.equipment(true).some(gear => gear.isHighAswBomber(false)) // mainly asw 50/65, dive bomber not work
|| (shipAsw >= 100 && hasSonar && hasAswAircraft); // almost impossible for pre-marriage
}
// DE 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;
}
// Hyuuga Kai Ni can OASW with 2 Autogyro or 1 Helicopter,
// but her initial naked asw too high to verify the lower threshold.
// Fusou-class Kai Ni can OASW with at least 1 Helicopter + Sonar and asw >= 100.
// https://twitter.com/cat_lost/status/1146075888636710912
// Hyuuga Kai Ni cannot OASW with Sonar only, just like BBV cannot ASW with Depth Charge.
// perhaps all AirAntiSubStype doesn't even they can equip Sonar and asw >= 100?
// at least 1 slot of ASW capable aircraft needed.
if(isAirAntiSubStype) {
return (isHyuugaKaiNi || hasSonar) &&
(this.countEquipmentType(1, 15) >= 2 ||
this.countEquipmentType(1, 44) >= 1);
}
// for other ship types who can do ASW with Depth Charge
return hasSonar;
};
/**
* @return true if this ship can do ASW attack.
*/
KC3Ship.prototype.canDoASW = function(time = "Day") {
if(this.isDummy() || this.isAbsent()) { return false; }
const stype = this.master().api_stype;
const isHayasuiKaiWithTorpedoBomber = this.masterId === 352 && this.hasEquipmentType(2, 8);
const isKagaK2Go = this.masterId === 646;
// CAV, CVL, BBV, AV, LHA, CVL-like Hayasui Kai, Kaga Kai Ni Go
const isAirAntiSubStype = [6, 7, 10, 16, 17].includes(stype) || isHayasuiKaiWithTorpedoBomber || isKagaK2Go;
if(isAirAntiSubStype) {
// CV Kaga Kai Ni Go implemented since 2020-08-27, can do ASW under uncertained conditions (using CVL's currently),
// but any CV form (converted back from K2Go) may ASW either if her asw modded > 0, fixed on the next day
// see https://twitter.com/Synobicort_SC/status/1298998245893394432
const isCvlLike = stype === 7 || isHayasuiKaiWithTorpedoBomber || isKagaK2Go;
// At night, most ship types cannot do ASW,
// only CVL can ASW with depth charge if naked asw is not 0 and not taiha,
// even no plane equipped or survived, such as Taiyou Kai Ni, Hayasui Kai.
// but CVE will attack surface target first if NCVCI met.
// *Some Abyssal AV/BBV can do ASW with air attack at night.
if(time === "Night") return isCvlLike && !this.isTaiha() && this.as[1] > 0;
// For day time, false if CVL or CVL-like chuuha
if(isCvlLike && this.isStriped()) return false;
// and if ASW plane equipped and its 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.hasEquipmentType(2, 22);
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`, `isPtImp`.
*/
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;
// known PT Imp Packs (also belong to surface)
const isPtImp = [1637, 1638, 1639, 1640].includes(targetShipMasterId);
return {
isSubmarine,
isLand,
isSurface,
isPtImp,
};
};
/**
* Divide Abyssal land installation into KC3-unique types:
* Type 0: Not land installation
* Type 1: Soft-skinned, eg: Harbor Princess
* Type 2: Artillery Imp, aka. Pillbox
* Type 3: Isolated Island Princess
* Type 4: Supply Depot Princess
* Type 5: Summer Harbor Princess
* Type 6: Summer Supply Depot Princess
* @param precap - specify true if going to calculate pre-cap modifiers
* @return the numeric type identifier
* @see http://kancolle.wikia.com/wiki/Installation_Type
*/
KC3Ship.prototype.estimateInstallationEnemyType = function(targetShipMasterId = 0, precap = true){
const targetShip = KC3Master.ship(targetShipMasterId);
if(!this.masterId || !targetShip) { return 0; }
if(!this.estimateTargetShipType(targetShipMasterId).isLand) { return 0; }
// Supply Depot Princess
if([1653, 1654, 1655, 1656, 1657, 1658,
1921, 1922, 1923, 1924, 1925, 1926, // B
1933, 1934, 1935, 1936, 1937, 1938 // B Summer Landing Mode
].includes(targetShipMasterId)) {
// Unique case: takes soft-skinned pre-cap but unique post-cap
return precap ? 1 : 4;
}
// Summer Supply Depot Princess
if([1753, 1754].includes(targetShipMasterId)) {
// Same unique case as above
return precap ? 1 : 6;
}
const abyssalIdTypeMap = {
// Summer Harbor Princess
"1699": 5, "1700": 5, "1701": 5, "1702": 5, "1703": 5, "1704": 5,
// Isolated Island Princess
"1668": 3, "1669": 3, "1670": 3, "1671": 3, "1672": 3,
// Artillery Imp
"1665": 2, "1666": 2, "1667": 2,
};
return abyssalIdTypeMap[targetShipMasterId] || 1;
};
/**
* @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, except some exceptions
if(targetShipType.isLand && this.equipment().some((g, i) => this.slots[i] > 0 &&
g.master().api_type[2] === 7 &&
!KC3GearManager.antiLandDiveBomberIds.includes(g.masterId)
)) 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, FBB, BB, BBV, SS, SSV, AV, CT
const isTorpedoStype = [2, 3, 4, 5, 6, 8, 9, 10, 13, 14, 16, 21].includes(this.master().api_stype);
return isTorpedoStype && this.estimateNakedStats("tp") > 0;
};
/**
* Conditions under verification, known for now:
* Flagship is healthy Nelson, Double Line variants formation selected.
* Min 6 ships fleet needed, main fleet only for Combined Fleet.
* 3rd, 5th ship not carrier, no any submarine in fleet.
* No AS/AS+ air battle needed like regular Artillery Spotting.
*
* No PvP sample found for now.
* Can be triggered in 1 battle per sortie, max 3 chances to roll (if yasen).
*
* @return true if this ship (Nelson) can do Nelson Touch cut-in attack.
* @see http://kancolle.wikia.com/wiki/Nelson
* @see https://wikiwiki.jp/kancolle/Nelson
*/
KC3Ship.prototype.canDoNelsonTouch = function() {
if(this.isDummy() || this.isAbsent()) { return false; }
// is this ship Nelson and not even Chuuha
// still okay even 3th and 5th ship are Taiha
if(KC3Meta.nelsonTouchShips.includes(this.masterId) && !this.isStriped()) {
const [shipPos, shipCnt, fleetNum] = this.fleetPosition();
// Nelson is flagship of a fleet, which min 6 ships needed
if(fleetNum > 0 && shipPos === 0 && shipCnt >= 6
// not in any escort fleet of Combined Fleet
&& (!PlayerManager.combinedFleet || fleetNum !== 2)) {
// Double Line variants selected
const isDoubleLine = [2, 12].includes(
this.collectBattleConditions().formationId || ConfigManager.aaFormation
);
const fleetObj = PlayerManager.fleets[fleetNum - 1],
// 3th and 5th ship are not carrier or absent?
invalidCombinedShips = [fleetObj.ship(2), fleetObj.ship(4)]
.some(ship => ship.isAbsent() || ship.isCarrier()),
// submarine in any position of the fleet?
hasSubmarine = fleetObj.ship().some(s => s.isSubmarine()),
// no ship(s) sunk or retreated in mid-sortie?
hasSixShips = fleetObj.countShips(true) >= 6;
return isDoubleLine && !invalidCombinedShips && !hasSubmarine && hasSixShips;
}
}
return false;
};
/**
* Most conditions are the same with Nelson Touch, except:
* Flagship is healthy Nagato/Mutsu Kai Ni, Echelon formation selected.
* 2nd ship is a battleship, Chuuha ok, Taiha no good.
*
* Additional ammo consumption for Nagato/Mutsu & 2nd battleship:
* + Math.floor(or ceil?)(total ammo cost of this battle (yasen may included) / 2)
*
* @return true if this ship (Nagato/Mutsu Kai Ni) can do special cut-in attack.
* @see http://kancolle.wikia.com/wiki/Nagato
* @see https://wikiwiki.jp/kancolle/%E9%95%B7%E9%96%80%E6%94%B9%E4%BA%8C
* @see http://kancolle.wikia.com/wiki/Mutsu
* @see https://wikiwiki.jp/kancolle/%E9%99%B8%E5%A5%A5%E6%94%B9%E4%BA%8C
*/
KC3Ship.prototype.canDoNagatoClassCutin = function(flagShipIds = KC3Meta.nagatoClassCutinShips) {
if(this.isDummy() || this.isAbsent()) { return false; }
if(flagShipIds.includes(this.masterId) && !this.isStriped()) {
const [shipPos, shipCnt, fleetNum] = this.fleetPosition();
if(fleetNum > 0 && shipPos === 0 && shipCnt >= 6
&& (!PlayerManager.combinedFleet || fleetNum !== 2)) {
const isEchelon = [4, 12].includes(
this.collectBattleConditions().formationId || ConfigManager.aaFormation
);
const fleetObj = PlayerManager.fleets[fleetNum - 1],
// 2nd ship not battle ship?
invalidCombinedShips = [fleetObj.ship(1)].some(ship =>
ship.isAbsent() || ship.isTaiha() ||
![8, 9, 10].includes(ship.master().api_stype)),
hasSubmarine = fleetObj.ship().some(s => s.isSubmarine()),
hasSixShips = fleetObj.countShips(true) >= 6;
return isEchelon && !invalidCombinedShips && !hasSubmarine && hasSixShips;
}
}
return false;
};
/**
* Nagato/Mutsu Kai Ni special cut-in attack modifiers are variant depending on the fleet 2nd ship.
* And there are different modifiers for 2nd ship's 3rd attack.
* @param modifierFor2ndShip - to indicate the returned modifier is used for flagship or 2nd ship.
* @return the modifier, 1 by default for unknown conditions.
* @see https://wikiwiki.jp/kancolle/%E9%95%B7%E9%96%80%E6%94%B9%E4%BA%8C
*/
KC3Ship.prototype.estimateNagatoClassCutinModifier = function(modifierFor2ndShip = false) {
const locatedFleet = PlayerManager.fleets[this.onFleet() - 1];
if(!locatedFleet) return 1;
const flagshipMstId = locatedFleet.ship(0).masterId;
if(!KC3Meta.nagatoClassCutinShips.includes(flagshipMstId)) return 1;
const ship2ndMstId = locatedFleet.ship(1).masterId;
const partnerModifierMap = KC3Meta.nagatoCutinShips.includes(flagshipMstId) ?
(modifierFor2ndShip ? {
"573": 1.4, // Mutsu Kai Ni
"276": 1.35, // Mutsu Kai, base form unverified?
"576": 1.25, // Nelson Kai, base form unverified?
} : {
"573": 1.2, // Mutsu Kai Ni
"276": 1.15, // Mutsu Kai, base form unverified?
"576": 1.1, // Nelson Kai, base form unverified?
}) :
KC3Meta.mutsuCutinShips.includes(flagshipMstId) ?
(modifierFor2ndShip ? {
"541": 1.4, // Nagato Kai Ni
"275": 1.35, // Nagato Kai
"576": 1.25, // Nelson Kai
} : {
"541": 1.2, // Nagato Kai Ni
"275": 1.15, // Nagato Kai
"576": 1.1, // Nelson Kai
}) : {};
const baseModifier = modifierFor2ndShip ? 1.2 : 1.4;
const partnerModifier = partnerModifierMap[ship2ndMstId] || 1;
const apShellModifier = this.hasEquipmentType(2, 19) ? 1.35 : 1;
// Surface Radar modifier not always limited to post-cap and AP Shell synergy now,
// can be applied to night battle (pre-cap) independently?
const surfaceRadarModifier = this.equipment(true).some(gear => gear.isSurfaceRadar()) ? 1.15 : 1;
return baseModifier * partnerModifier * apShellModifier * surfaceRadarModifier;
};
/**
* Most conditions are the same with Nelson Touch, except:
* Flagship is healthy Colorado, Echelon formation selected.
* 2nd and 3rd ships are healthy battleship, neither Taiha nor Chuuha.
*
* The same additional ammo consumption like Nagato/Mutsu cutin for top 3 battleships.
*
* 4 types of smoke animation effects will be used according corresponding position of partener ships,
* see `main.js#CutinColoradoAttack.prototype._getSmoke`.
*
* @return true if this ship (Colorado) can do Colorado special cut-in attack.
* @see http://kancolle.wikia.com/wiki/Colorado
* @see https://wikiwiki.jp/kancolle/Colorado
*/
KC3Ship.prototype.canDoColoradoCutin = function() {
if(this.isDummy() || this.isAbsent()) { return false; }
// is this ship Colorado and not even Chuuha
if(KC3Meta.coloradoCutinShips.includes(this.masterId) && !this.isStriped()) {
const [shipPos, shipCnt, fleetNum] = this.fleetPosition();
if(fleetNum > 0 && shipPos === 0 && shipCnt >= 6
&& (!PlayerManager.combinedFleet || fleetNum !== 2)) {
const isEchelon = [4, 12].includes(
this.collectBattleConditions().formationId || ConfigManager.aaFormation
);
const fleetObj = PlayerManager.fleets[fleetNum - 1],
// 2nd and 3rd ship are (F)BB(V) only, not even Chuuha?
validCombinedShips = [fleetObj.ship(1), fleetObj.ship(2)]
.some(ship => !ship.isAbsent() && !ship.isStriped()
&& [8, 9, 10].includes(ship.master().api_stype)),
// submarine in any position of the fleet?
hasSubmarine = fleetObj.ship().some(s => s.isSubmarine()),
// uncertain: ship(s) sunk or retreated in mid-sortie can prevent proc?
hasSixShips = fleetObj.countShips(true) >= 6;
return isEchelon && validCombinedShips && !hasSubmarine && hasSixShips;
}
}
return false;
};
/**
* Colorado special cut-in attack modifiers are variant,
* depending on equipment and 2nd and 3rd ship in the fleet.
* @see https://twitter.com/syoukuretin/status/1132763536222969856
*/
KC3Ship.prototype.estimateColoradoCutinModifier = function(forShipPos = 0) {
const locatedFleet = PlayerManager.fleets[this.onFleet() - 1];
if(!locatedFleet) return 1;
const flagshipMstId = locatedFleet.ship(0).masterId;
if(!KC3Meta.coloradoCutinShips.includes(flagshipMstId)) return 1;
const combinedModifierMaps = [
// No more mods for flagship?
{},
// x1.1 for Big-7 2nd ship
{
"80": 1.1, "275": 1.1, "541": 1.1, // Nagato
"81": 1.1, "276": 1.1, "573": 1.1, // Mutsu
"571": 1.1, "576": 1.1, // Nelson
},
// x1.15 for Big-7 3rd ship
{
"80": 1.15, "275": 1.15, "541": 1.15,
"81": 1.15, "276": 1.15, "573": 1.15,
"571": 1.15, "576": 1.15,
},
];
forShipPos = (forShipPos || 0) % 3;
const baseModifier = [1.3, 1.15, 1.15][forShipPos];
const targetShip = locatedFleet.ship(forShipPos),
targetShipMstId = targetShip.masterId,
targetShipModifier = combinedModifierMaps[forShipPos][targetShipMstId] || 1;
// Bug 'mods of 2nd ship's apshell/radar and on-5th-slot-empty-exslot spread to 3rd ship' not applied here
const apShellModifier = targetShip.hasEquipmentType(2, 19) ? 1.35 : 1;
const surfaceRadarModifier = targetShip.equipment(true).some(gear => gear.isSurfaceRadar()) ? 1.15 : 1;
const ship2ndMstId = locatedFleet.ship(1).masterId,
ship2ndModifier = combinedModifierMaps[1][ship2ndMstId] || 1;
return baseModifier * targetShipModifier
* (forShipPos === 2 && targetShipModifier > 1 ? ship2ndModifier : 1)
* apShellModifier * surfaceRadarModifier;
};
/**
* Most conditions are the same with Nelson Touch, except:
* Flagship is healthy Kongou-class Kai Ni C, Line Ahead formation selected, night battle only.
* 2nd ship is healthy one of the following:
* * Kongou K2C flagship: Hiei K2C / Haruna K2 / Warspite
* * Hiei K2C flagship: Kongou K2C / Kirishima K2
* Surface ships in fleet >= 5 (that means 1 submarine is okay for single fleet)
*
* Since it's a night battle only cutin, have to be escort fleet of any Combined Fleet.
* And it's impossible to be triggered after any other daytime Big-7 special cutin,
* because all ship-combined spcutins only trigger 1-time per sortie?
*
* The additional 30% ammo consumption, see:
* * https://twitter.com/myteaGuard/status/1254040809365618690
* * https://twitter.com/myteaGuard/status/1254048759559778305
*
* @return true if this ship (Kongou-class K2C) can do special cut-in attack.
* @see https://kancolle.fandom.com/wiki/Kongou/Special_Cut-In
* @see https://wikiwiki.jp/kancolle/%E6%AF%94%E5%8F%A1%E6%94%B9%E4%BA%8C%E4%B8%99
*/
KC3Ship.prototype.canDoKongouCutin = function() {
if(this.isDummy() || this.isAbsent()) { return false; }
// is this ship Kongou-class K2C and not even Chuuha
if(KC3Meta.kongouCutinShips.includes(this.masterId) && !this.isStriped()) {
const [shipPos, shipCnt, fleetNum] = this.fleetPosition();
if(fleetNum > 0 && shipPos === 0 && shipCnt >= 5
&& (!PlayerManager.combinedFleet || fleetNum === 2)) {
const isLineAhead = [1, 14].includes(
this.collectBattleConditions().formationId || ConfigManager.aaFormation
);
const fleetObj = PlayerManager.fleets[fleetNum - 1],
// 2nd ship is valid partener and not even Chuuha
validCombinedShips = ({
// Kongou K2C: Hiei K2C, Haruna K2, Warspite
"591": [592, 151, 439, 364],
// Hiei K2C: Kongou K2C, Kirishima K2
"592": [591, 152],
}[this.masterId] || []).includes(fleetObj.ship(1).masterId)
&& !fleetObj.ship(1).isStriped(),
// uncertain: ship(s) sunk or retreated in mid-sortie can prevent proc?
hasFiveSurfaceShips = fleetObj.shipsUnescaped().filter(s => !s.isSubmarine()).length >= 5;
return isLineAhead && validCombinedShips && hasFiveSurfaceShips;
}
}
return false;
};
/**
* @return the landing attack kind ID, return 0 if can not attack.
* Since Phase 2, defined by `_getDaihatsuEffectType` at `PhaseHougekiOpening, PhaseHougeki, PhaseHougekiBase`,
* all the ID 1 are replaced by 3, ID 2 except the one at `PhaseHougekiOpening` replaced by 3.
*/
KC3Ship.prototype.estimateLandingAttackType = function(targetShipMasterId = 0) {
const targetShip = KC3Master.ship(targetShipMasterId);
if(!this.masterId || !targetShip) return 0;
const isLand = targetShip.api_soku <= 0;
// new equipment: M4A1 DD
if(this.hasEquipment(355) && isLand) return 6;
// higher priority: Toku Daihatsu + 11th Tank
if(this.hasEquipment(230)) return isLand ? 5 : 0;
// 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
// but why Summer Supply Depot Princess not counted?
1809, 1810, 1811, 1812, 1813, 1814, // Supply Depot Princess Vacation Mode
1921, 1922, 1923, 1924, 1925, 1926, // Supply Depot Princess B
1933, 1934, 1935, 1936, 1937, 1938, // Supply Depot Princess B Summer Landing Mode
1815, 1816, 1817, 1818, 1819, 1820, // Anchorage Water Demon Vacation Mode
1556, 1631, 1632, 1633, 1650, 1651, 1652, 1889, 1890, 1891, 1892, 1893, 1894 // Airfield Princess
].includes(targetShipMasterId);
// T2 Tank
if(this.hasEquipment(167)) {
const isThisSubmarine = this.isSubmarine();
if(isThisSubmarine && isLand) return 4;
if(isTargetLandable) return 4;
return 0;
}
if(isTargetLandable) {
// M4A1 DD
if(this.hasEquipment(355)) return 6;
// T89 Tank
if(this.hasEquipment(166)) return 3;
// Toku Daihatsu
if(this.hasEquipment(193)) return 3;
// Daihatsu
if(this.hasEquipment(68)) return 3;
}
return 0;
};
/**
* @param atType - id from `api_hougeki?.api_at_type` which indicates the special attack.
* @param altCutinTerm - different term string for cutin has different variant, like CVCI.
* @param altModifier - different power modifier for cutin has different variant, like CVCI.
* @return known special attack (aka Cut-In) types definition tuple.
* will return an object mapped all IDs and tuples if atType is omitted.
* will return `["SingleAttack", 0]` if no matched ID found.
* @see estimateDayAttackType
*/
KC3Ship.specialAttackTypeDay = function(atType, altCutinTerm, altModifier){
const knownDayAttackTypes = {
1: ["Cutin", 1, "Laser"], // no longer exists now
2: ["Cutin", 2, "DoubleAttack", 1.2],
3: ["Cutin", 3, "CutinMainSecond", 1.1],
4: ["Cutin", 4, "CutinMainRadar", 1.2],
5: ["Cutin", 5, "CutinMainApshell", 1.3],
6: ["Cutin", 6, "CutinMainMain", 1.5],
7: ["Cutin", 7, "CutinCVCI", 1.25],
100: ["Cutin", 100, "CutinNelsonTouch", 2.0],
101: ["Cutin", 101, "CutinNagatoSpecial", 2.27],
102: ["Cutin", 102, "CutinMutsuSpecial", 2.27],
103: ["Cutin", 103, "CutinColoradoSpecial", 2.26],
200: ["Cutin", 200, "CutinZuiunMultiAngle", 1.35],
201: ["Cutin", 201, "CutinAirSeaMultiAngle", 1.3],
};
if(atType === undefined) return knownDayAttackTypes;
const matched = knownDayAttackTypes[atType] || ["SingleAttack", 0];
if(matched[0] === "Cutin") {
if(altCutinTerm) matched[2] = altCutinTerm;
if(altModifier) matched[3] = altModifier;
}
return matched;
};
/**
* 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 main.js#PhaseHougeki.prototype._getNormalAttackType - since Phase 2
* @see specialAttackTypeDay
* @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();
// Special cutins do not need isAirSuperiorityBetter
if(trySpTypeFirst) {
// Nelson Touch since 2018-09-15
if(this.canDoNelsonTouch()) {
const isRedT = this.collectBattleConditions().engagementId === 4;
return KC3Ship.specialAttackTypeDay(100, null, isRedT ? 2.5 : 2.0);
}
// Nagato cutin since 2018-11-16
if(this.canDoNagatoClassCutin(KC3Meta.nagatoCutinShips)) {
// To clarify: here only indicates the modifier of flagship's first 2 attacks
return KC3Ship.specialAttackTypeDay(101, null, this.estimateNagatoClassCutinModifier());
}
// Mutsu cutin since 2019-02-27
if(this.canDoNagatoClassCutin(KC3Meta.mutsuCutinShips)) {
return KC3Ship.specialAttackTypeDay(102, null, this.estimateNagatoClassCutinModifier());
}
// Colorado cutin since 2019-05-25
if(this.canDoColoradoCutin()) {
return KC3Ship.specialAttackTypeDay(103, null, this.estimateColoradoCutinModifier());
}
}
const isAirSuperiorityBetter = airBattleId === 1 || airBattleId === 2;
// Special Multi-Angle cutins do not need recon plane and probably higher priority
if(trySpTypeFirst && isAirSuperiorityBetter) {
const isThisIseClassK2 = [553, 554].includes(this.masterId);
const mainGunCnt = this.countEquipmentType(2, [1, 2, 3, 38]);
if(isThisIseClassK2 && mainGunCnt > 0 && !this.isTaiha()) {
// Ise-class Kai Ni Zuiun Multi-Angle Attack since 2019-03-27
const spZuiunCnt = this.countNonZeroSlotEquipment(
// All seaplane bombers named Zuiun capable?
[26, 79, 80, 81, 207, 237, 322, 323]
);
// Zuiun priority to Air/Sea Attack when they are both equipped
if(spZuiunCnt > 1) return KC3Ship.specialAttackTypeDay(200);
// Ise-class Kai Ni Air/Sea Multi-Angle Attack since 2019-03-27
const spSuiseiCnt = this.countNonZeroSlotEquipment(
// Only Suisei named 634th Air Group capable?
[291, 292, 319]
);
if(spSuiseiCnt > 1) return KC3Ship.specialAttackTypeDay(201);
}
}
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, 38]);
const apShellCnt = this.countEquipmentType(2, 19);
if(mainGunCnt >= 2 && apShellCnt >= 1) return KC3Ship.specialAttackTypeDay(6);
const secondaryCnt = this.countEquipmentType(2, 4);
if(mainGunCnt >= 1 && secondaryCnt >= 1 && apShellCnt >= 1)
return KC3Ship.specialAttackTypeDay(5);
const radarCnt = this.countEquipmentType(2, [12, 13]);
if(mainGunCnt >= 1 && secondaryCnt >= 1 && radarCnt >= 1)
return KC3Ship.specialAttackTypeDay(4);
if(mainGunCnt >= 1 && secondaryCnt >= 1) return KC3Ship.specialAttackTypeDay(3);
if(mainGunCnt >= 2) return KC3Ship.specialAttackTypeDay(2);
} 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 KC3Ship.specialAttackTypeDay(7, "CutinFDBTB", 1.25);
if(diveBomberCnt >= 2 && torpedoBomberCnt >= 1)
return KC3Ship.specialAttackTypeDay(7, "CutinDBDBTB", 1.2);
if(diveBomberCnt >= 1 && torpedoBomberCnt >= 1)
return KC3Ship.specialAttackTypeDay(7, "CutinDBTB", 1.15);
}
// is target a land installation
if(targetShipType.isLand) {
const landingAttackType = this.estimateLandingAttackType(targetShipMasterId);
if(landingAttackType > 0) {
return ["LandingAttack", landingAttackType];
}
// see `main.js#PhaseHougeki.prototype._hasRocketEffect` or same method of `PhaseHougekiBase`,
// and if base attack method is NOT air attack
const hasRocketLauncher = this.hasEquipmentType(2, 37) || this.hasEquipment([346, 347]);
// 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 Class Kai Ni, Kaga Kai Ni Go
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 hasNightAircraft = this.hasEquipmentType(3, KC3GearManager.nightAircraftType3Ids);
const hasNightAvPersonnel = this.hasEquipment([258, 259]);
// night battle capable carriers: Saratoga Mk.II, Akagi Kai Ni E/Kaga Kai Ni E
const isThisNightCarrier = [545, 599, 610].includes(this.masterId);
// ~~Swordfish variants are counted as night aircraft for Ark Royal + NOAP~~
// Ark Royal + Swordfish variants + NOAP - night aircraft will not get `api_n_mother_list: 1`
//const isThisArkRoyal = [515, 393].includes(this.masterId);
//const isSwordfishArkRoyal = isThisArkRoyal && this.hasEquipment([242, 243, 244]);
// if night aircraft + (NOAP equipped / on Saratoga Mk.2/Akagi K2E/Kaga K2E)
return hasNightAircraft && (hasNightAvPersonnel || isThisNightCarrier);
}
return false;
};
/**
* @param spType - id from `api_hougeki.api_sp_list` which indicates the special attack.
* @param altCutinTerm - different term string for cutin has different variant, like SS TCI, CVNCI, DDCI.
* @param altModifier - different power modifier for cutin has different variant, like SS TCI, CVNCI, DDCI.
* @return known special attack (aka Cut-In) types definition tuple.
* will return an object mapped all IDs and tuples if atType is omitted.
* will return `["SingleAttack", 0]` if no matched ID found.
* @see estimateNightAttackType
*/
KC3Ship.specialAttackTypeNight = function(spType, altCutinTerm, altModifier){
const knownNightAttackTypes = {
1: ["Cutin", 1, "DoubleAttack", 1.2],
2: ["Cutin", 2, "CutinTorpTorpMain", 1.3],
3: ["Cutin", 3, "CutinTorpTorpTorp", 1.5],
4: ["Cutin", 4, "CutinMainMainSecond", 1.75],
5: ["Cutin", 5, "CutinMainMainMain", 2.0],
6: ["Cutin", 6, "CutinCVNCI", 1.25],
7: ["Cutin", 7, "CutinMainTorpRadar", 1.3],
8: ["Cutin", 8, "CutinTorpRadarLookout", 1.2],
100: ["Cutin", 100, "CutinNelsonTouch", 2.0],
101: ["Cutin", 101, "CutinNagatoSpecial", 2.27],
102: ["Cutin", 102, "CutinMutsuSpecial", 2.27],
103: ["Cutin", 103, "CutinColoradoSpecial", 2.26],
104: ["Cutin", 104, "CutinKongouSpecial", 1.9],
};
if(spType === undefined) return knownNightAttackTypes;
const matched = knownNightAttackTypes[spType] || ["SingleAttack", 0];
if(matched[0] === "Cutin") {
if(altCutinTerm) matched[2] = altCutinTerm;
if(altModifier) matched[3] = altModifier;
}
return matched;
};
/**
* 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 main.js#PhaseHougekiBase.prototype._getNormalAttackType - since Phase 2
* @see specialAttackTypeNight
* @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 isThisKagaK2Go = this.masterId === 646;
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/Akagi K2E/Kaga K2E needed
if(isCarrierNightAirAttack) {
// https://kancolle.fandom.com/wiki/Combat#Setups_and_Attack_Types
// http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#x397cac6
const nightFighterCnt = this.countNonZeroSlotEquipmentType(3, 45);
const nightTBomberCnt = this.countNonZeroSlotEquipmentType(3, 46);
// Zero Fighter Model 62 (Fighter-bomber Iwai Squadron)
const iwaiDBomberCnt = this.countNonZeroSlotEquipment(154);
// Swordfish variants
const swordfishTBomberCnt = this.countNonZeroSlotEquipment([242, 243, 244]);
// new patterns for Suisei Model 12 (Type 31 Photoelectric Fuze Bombs) since 2019-04-30,
// it more likely acts as yet unimplemented Night Dive Bomber type
const photoDBomberCnt = this.countNonZeroSlotEquipment(320);
// might extract this out for estimating unexpected damage actual pattern modifier
const ncvciModifier = (() => {
const otherCnt = photoDBomberCnt + iwaiDBomberCnt + swordfishTBomberCnt;
if(nightFighterCnt >= 2 && nightTBomberCnt >= 1) return 1.25;
if(nightFighterCnt + nightTBomberCnt + otherCnt === 2) return 1.2;
if(nightFighterCnt + nightTBomberCnt + otherCnt >= 3) return 1.18;
return 1; // should not reach here
})();
// first place thank to its highest mod 1.25
if(nightFighterCnt >= 2 && nightTBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNFNTB", ncvciModifier);
// 3 planes mod 1.18
if(nightFighterCnt >= 3)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNFNF", ncvciModifier);
if(nightFighterCnt >= 1 && nightTBomberCnt >= 2)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBNTB", ncvciModifier);
if(nightFighterCnt >= 2 && iwaiDBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNFFBI", ncvciModifier);
if(nightFighterCnt >= 2 && swordfishTBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNFSF", ncvciModifier);
if(nightFighterCnt >= 1 && iwaiDBomberCnt >= 2)
return KC3Ship.specialAttackTypeNight(6, "CutinNFFBIFBI", ncvciModifier);
if(nightFighterCnt >= 1 && swordfishTBomberCnt >= 2)
return KC3Ship.specialAttackTypeNight(6, "CutinNFSFSF", ncvciModifier);
if(nightFighterCnt >= 1 && iwaiDBomberCnt >= 1 && swordfishTBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFFBISF", ncvciModifier);
if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && iwaiDBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBFBI", ncvciModifier);
if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && swordfishTBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBSF", ncvciModifier);
if(nightFighterCnt >= 2 && photoDBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNFNDB", ncvciModifier);
if(nightFighterCnt >= 1 && photoDBomberCnt >= 2)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNDBNDB", ncvciModifier);
if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && photoDBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBNDB", ncvciModifier);
if(nightFighterCnt >= 1 && photoDBomberCnt >= 1 && iwaiDBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNDBFBI", ncvciModifier);
if(nightFighterCnt >= 1 && photoDBomberCnt >= 1 && swordfishTBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNDBSF", ncvciModifier);
// 2 planes mod 1.2, put here not to mask previous patterns, tho proc rate might be higher
if(nightFighterCnt >= 1 && nightTBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNTB", ncvciModifier);
if(nightFighterCnt >= 1 && photoDBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNFNDB", ncvciModifier);
if(nightTBomberCnt >= 1 && photoDBomberCnt >= 1)
return KC3Ship.specialAttackTypeNight(6, "CutinNTBNDB", ncvciModifier);
} else {
// special Nelson Touch since 2018-09-15
if(this.canDoNelsonTouch()) {
const isRedT = this.collectBattleConditions().engagementId === 4;
return KC3Ship.specialAttackTypeNight(100, null, isRedT ? 2.5 : 2.0);
}
// special Nagato Cutin since 2018-11-16
if(this.canDoNagatoClassCutin(KC3Meta.nagatoCutinShips)) {
return KC3Ship.specialAttackTypeNight(101, null, this.estimateNagatoClassCutinModifier());
}
// special Mutsu Cutin since 2019-02-27
if(this.canDoNagatoClassCutin(KC3Meta.mutsuCutinShips)) {
return KC3Ship.specialAttackTypeNight(102, null, this.estimateNagatoClassCutinModifier());
}
// special Colorado Cutin since 2019-05-25
if(this.canDoColoradoCutin()) {
return KC3Ship.specialAttackTypeNight(103, null, this.estimateColoradoCutinModifier());
}
// special Kongou-class K2C Cutin since 2020-04-23
if(this.canDoKongouCutin()) {
// Basic precap modifier is 1.9: https://twitter.com/CC_jabberwock/status/1253677320629399552
const engagementMod = [1, 1, 1, 1.25, 0.75][this.collectBattleConditions().engagementId] || 1.0;
return KC3Ship.specialAttackTypeNight(104, null, 1.9 * engagementMod);
}
// special torpedo radar cut-in for destroyers since 2017-10-25
// http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#dfcb6e1f
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.isSurfaceRadar());
const hasSkilledLookout = this.hasEquipmentType(2, 39);
const smallMainGunCnt = this.countEquipmentType(2, 1);
// Extra bonus if small main gun is 12.7cm Twin Gun Mount Model D Kai Ni/3
// https://twitter.com/ayanamist_m2/status/944176834551222272
// https://docs.google.com/spreadsheets/d/1_e0M6asJUbu9EEW4PrGCu9hOxZnY7OQEDHH2DUAzjN8/htmlview
const modelDK2SmallGunCnt = this.countEquipment(267),
modelDK3SmallGunCnt = this.countEquipment(366);
// Possible to equip 2 D guns for 4 slots Tashkent
// https://twitter.com/Xe_UCH/status/1011398540654809088
const modelDSmallGunModifier =
([1, 1.25, 1.4][modelDK2SmallGunCnt + modelDK3SmallGunCnt] || 1.4)
* (1 + modelDK3SmallGunCnt * 0.05);
if(hasCapableRadar && smallMainGunCnt >= 1)
return KC3Ship.specialAttackTypeNight(7, null, 1.3 * modelDSmallGunModifier);
if(hasCapableRadar && hasSkilledLookout)
return KC3Ship.specialAttackTypeNight(8, null, 1.2 * modelDSmallGunModifier);
}
// special torpedo cut-in for late model submarine torpedo
const lateTorpedoCnt = this.countEquipment([213, 214, 383]);
const submarineRadarCnt = this.countEquipmentType(2, 51);
if(lateTorpedoCnt >= 1 && submarineRadarCnt >= 1)
return KC3Ship.specialAttackTypeNight(3, "CutinLateTorpRadar", 1.75);
if(lateTorpedoCnt >= 2)
return KC3Ship.specialAttackTypeNight(3, "CutinLateTorpTorp", 1.6);
// although modifier lower than Main CI / Mix CI, but seems be more frequently used
// will not mutex if 5 slots ships can equip torpedo
if(torpedoCnt >= 2) return KC3Ship.specialAttackTypeNight(3);
const mainGunCnt = this.countEquipmentType(2, [1, 2, 3, 38]);
if(mainGunCnt >= 3) return KC3Ship.specialAttackTypeNight(5);
const secondaryCnt = this.countEquipmentType(2, 4);
if(mainGunCnt === 2 && secondaryCnt >= 1)
return KC3Ship.specialAttackTypeNight(4);
if((mainGunCnt === 2 && secondaryCnt === 0 && torpedoCnt === 1) ||
(mainGunCnt === 1 && torpedoCnt === 1))
return KC3Ship.specialAttackTypeNight(2);
// 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 KC3Ship.specialAttackTypeNight(1);
}
}
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
if(isCarrierNightAirAttack) {
return ["AirAttack", 1, true];
}
if(targetShipType.isSubmarine && (isThisLightCarrier || isThisKagaK2Go)) {
return ["DepthCharge", 2];
}
if(isThisCarrier) {
// these abyssal ships can only be shelling attacked,
// see `main.js#PhaseHougekiBase.prototype._getNormalAttackType`
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];
};
/**
* Calculates base value used in day battle artillery spotting process chance.
* Likely to be revamped as formula comes from PSVita and does not include CVCI,
* uncertain about Combined Fleet interaction.
* @see https://kancolle.wikia.com/wiki/User_blog:Shadow27X/Artillery_Spotting_Rate_Formula
* @see KC3Fleet.prototype.artillerySpottingLineOfSight
*/
KC3Ship.prototype.daySpAttackBaseRate = function() {
if (this.isDummy() || !this.onFleet()) { return {}; }
const [shipPos, shipCnt, fleetNum] = this.fleetPosition();
const fleet = PlayerManager.fleets[fleetNum - 1];
const fleetLoS = fleet.artillerySpottingLineOfSight();
const adjFleetLoS = Math.floor(Math.sqrt(fleetLoS) + fleetLoS / 10);
const adjLuck = Math.floor(Math.sqrt(this.lk[0]) + 10);
// might exclude equipment on ship LoS bonus for now,
// to include LoS bonus, use `this.equipmentTotalLoS()` instead
const equipLoS = this.equipmentTotalStats("saku", true, false);
// assume to best condition AS+ by default (for non-battle)
const airBattleId = this.collectBattleConditions().airBattleId || 1;
const baseValue = airBattleId === 1 ? adjLuck + 0.7 * (adjFleetLoS + 1.6 * equipLoS) + 10 :
airBattleId === 2 ? adjLuck + 0.6 * (adjFleetLoS + 1.2 * equipLoS) : 0;
return {
baseValue,
isFlagship: shipPos === 0,
equipLoS,
fleetLoS,
dispSeiku: airBattleId
};
};
/**
* Calculates base value used in night battle cut-in process chance.
* @param {number} currentHp - used by simulating from battle prediction or getting different HP value.
* @see https://kancolle.wikia.com/wiki/Combat/Night_Battle#Night_Cut-In_Chance
* @see https://wikiwiki.jp/kancolle/%E5%A4%9C%E6%88%A6#nightcutin1
* @see KC3Fleet.prototype.estimateUsableSearchlight
*/
KC3Ship.prototype.nightSpAttackBaseRate = function(currentHp) {
if (this.isDummy()) { return {}; }
let baseValue = 0;
if (this.lk[0] < 50) {
baseValue += 15 + this.lk[0] + 0.75 * Math.sqrt(this.level);
} else {
baseValue += 65 + Math.sqrt(this.lk[0] - 50) + 0.8 * Math.sqrt(this.level);
}
const [shipPos, shipCnt, fleetNum] = this.fleetPosition();
// Flagship bonus
const isFlagship = shipPos === 0;
if (isFlagship) { baseValue += 15; }
// Chuuha bonus
const isChuuhaOrWorse = (currentHp || this.hp[0]) <= (this.hp[1] / 2);
if (isChuuhaOrWorse) { baseValue += 18; }
// Skilled lookout bonus
if (this.hasEquipmentType(2, 39)) { baseValue += 5; }
// Searchlight bonus, large SL unknown for now
const fleetSearchlight = fleetNum > 0 && PlayerManager.fleets[fleetNum - 1].estimateUsableSearchlight();
if (fleetSearchlight) { baseValue += 7; }
// Starshell bonus/penalty
const battleConds = this.collectBattleConditions();
const playerStarshell = battleConds.playerFlarePos > 0;
const enemyStarshell = battleConds.enemyFlarePos > 0;
if (playerStarshell) { baseValue += 4; }
if (enemyStarshell) { baseValue += -10; }
return {
baseValue,
isFlagship,
isChuuhaOrWorse,
fleetSearchlight,
playerStarshell,
enemyStarshell
};
};
/**
* Calculate Nelson Touch process rate, currently only known in day
* @param {boolean} isNight - Nelson Touch has lower modifier at night?
* @return {number} special attack rate
* @see https://twitter.com/Xe_UCH/status/1180283907284979713
*/
KC3Ship.prototype.nelsonTouchRate = function(isNight) {
if (this.isDummy() || isNight) { return false; }
const [shipPos, shipCnt, fleetNum] = this.fleetPosition();
// Nelson Touch prerequisite should be fulfilled before calling this, see also #canDoNelsonTouch
// here only to ensure fleetObj and combinedShips below not undefined if this invoked unexpectedly
if (shipPos !== 0 || shipCnt < 6 || !fleetNum) { return false; }
const fleetObj = PlayerManager.fleets[fleetNum - 1];
const combinedShips = [2, 4].map(pos => fleetObj.ship(pos));
const combinedShipsLevel = combinedShips.reduce((acc, ship) => acc + ship.level, 0);
const combinedShipsPenalty = combinedShips.some(ship => [2, 16].includes(ship.master().api_stype)) ? 10 : 0; // estimate
return (0.08 * this.level + 0.04 * combinedShipsLevel + 0.24 * this.lk[0] + 36 - combinedShipsPenalty) / 100;
};
/**
* Calculate ship day time artillery spotting process rate based on known type factors.
* @param {number} atType - based on api_at_type value of artillery spotting type.
* @param {string} cutinSubType - sub type of cut-in like CVCI.
* @return {number} artillery spotting percentage, false if unable to arty spot or unknown special attack.
* @see daySpAttackBaseRate
* @see estimateDayAttackType
* @see Type factors: https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#Observation
* @see Type factors for multi-angle cutin: https://wikiwiki.jp/kancolle/%E4%BC%8A%E5%8B%A2%E6%94%B9%E4%BA%8C
*/
KC3Ship.prototype.artillerySpottingRate = function(atType = 0, cutinSubType = "") {
// type 1 laser attack has gone forever, ship not on fleet cannot be evaluated
if (atType < 2 || this.isDummy() || !this.onFleet()) { return false; }
const formatPercent = num => Math.floor(num * 1000) / 10;
// Nelson Touch
if (atType === 100) {
return formatPercent(this.nelsonTouchRate(false));
}
const typeFactor = {
2: 150,
3: 120,
4: 130,
5: 130,
6: 140,
7: ({
"CutinFDBTB" : 125,
"CutinDBDBTB": 140,
"CutinDBTB" : 155,
})[cutinSubType],
// 100~103 might use different formula, see #nelsonTouchRate
200: 120,
201: undefined,
}[atType];
if (!typeFactor) { return false; }
const {baseValue, isFlagship} = this.daySpAttackBaseRate();
return formatPercent(((Math.floor(baseValue) + (isFlagship ? 15 : 0)) / typeFactor) || 0);
};
/**
* Calculate ship night battle special attack (cut-in and double attack) process rate based on known type factors.
* @param {number} spType - based on api_sp_list value of night special attack type.
* @param {string} cutinSubType - sub type of cut-in like CVNCI, submarine cut-in.
* @return {number} special attack percentage, false if unable to perform or unknown special attack.
* @see nightSpAttackBaseRate
* @see estimateNightAttackType
* @see Type factors: https://wikiwiki.jp/kancolle/%E5%A4%9C%E6%88%A6#nightcutin1
*/
KC3Ship.prototype.nightCutinRate = function(spType = 0, cutinSubType = "") {
if (spType < 1 || this.isDummy()) { return false; }
// not sure: DA success rate almost 99%
if (spType === 1) { return 99; }
const typeFactor = {
2: 115,
3: ({ // submarine late torp cutin should be different?
"CutinLateTorpRadar": undefined,
"CutinLateTorpTorp": undefined,
})[cutinSubType] || 122, // regular CutinTorpTorpTorp
4: 130,
5: 140,
6: ({ // CVNCI factors unknown, placeholders
"CutinNFNFNTB": undefined, // should be 3 types, for mod 1.25
"CutinNFNTB" : undefined, // 2 planes for mod 1.2
"CutinNFNDB" : undefined,
"CutinNTBNDB": undefined,
"CutinNFNFNF" : undefined, // 3 planes for mod 1.18
"CutinNFNTBNTB": undefined,
"CutinNFNFFBI" : undefined,
"CutinNFNFSF" : undefined,
"CutinNFFBIFBI": undefined,
"CutinNFSFSF" : undefined,
"CutinNFFBISF" : undefined,
"CutinNFNTBFBI": undefined,
"CutinNFNTBSF" : undefined,
"CutinNFNFNDB" : undefined,
"CutinNFNDBNDB": undefined,
"CutinNFNTBNDB": undefined,
"CutinNFNDBFBI": undefined,
"CutinNFNDBSF" : undefined,
})[cutinSubType],
// This two DD cutins can be rolled after regular cutin, more chance to be processed
7: 130,
8: undefined, // CutinTorpRadarLookout unknown
// 100~104 might be different, even with day one
}[spType];
if (!typeFactor) { return false; }
const {baseValue} = this.nightSpAttackBaseRate();
const formatPercent = num => Math.floor(num * 1000) / 10;
return formatPercent((Math.floor(baseValue) / typeFactor) || 0);
};
/**
* Calculate ship's Taiha rate when taken an overkill damage.
* This is related to the '4n+3 is better than 4n' theory,
* '4n+x' only refer to the rounded Taiha HP threshold, rate is also affected by current HP in fact.
* @param {number} currentHp - expected current hp value, use ship's real current hp by default.
* @param {number} maxHp - expected full hp value, use ship's real max hp by default.
* @return {number} Taiha percentage, 100% for already Taiha or red morale or dummy ship.
* @see https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#eb18c7e5
*/
KC3Ship.prototype.overkillTaihaRate = function(currentHp = this.hp[0], maxHp = this.hp[1]) {
if (this.isDummy()) { return 100; }
const taihaHp = Math.max(1, Math.floor(0.25 * maxHp));
const battleConds = this.collectBattleConditions();
// already taiha (should get rid of fasly or negative hp value)
// or red morale (hit red morale hp will be left fixed 1)
if (currentHp <= taihaHp || this.moraleEffectLevel([1, 1, 0, 0, 0], battleConds.isOnBattle)) {
return 100;
}
// sum all random cases of taiha
const taihaCases = Array.numbers(0, currentHp - 1).map(rndint => (
(currentHp - Math.floor(currentHp * 0.5 + rndint * 0.3)) <= taihaHp ? 1 : 0
)).sumValues();
// percentage with 2 decimal
return Math.round(taihaCases / currentHp * 10000) / 100;
};
/**
* 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);
// 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("ht");
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, see #artillerySpottingRate
if(applySpAttackModifiers) {
artillerySpottingModifier = (type => {
if(type[0] === "Cutin") {
return ({
// IDs from `api_hougeki.api_at_type`, see #specialAttackTypeDay
"2": 1.1, "3": 1.3, "4": 1.5, "5": 1.3, "6": 1.2,
// modifier for 7 (CVCI) still unknown
// modifiers for [100, 201] (special cutins) still unknown
})[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?
// mods: https://twitter.com/Xe_UCH/status/1304783506275409920
modifier = enemyFormationId === 2 ? 1.45 : 1.4;
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
// 12.7cm Single High-angle Gun Mount (Late Model)
const singleHighAngleMountCnt = this.countEquipment(229);
// for Mutsuki class including Satsuki K2
result += (ctype === 28 ? 5 : 0) * Math.sqrt(singleHighAngleMountCnt);
// for Kamikaze class still unknown
break;
case 3:
case 4:
case 21: // for Light Cruisers
// overhaul implemented in-game since 2017-06-23, not fully verified
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 (might disappeared?)
// 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.toCamelCase()] || 0;
if(this.isMarried()) value *= fit[1].married || 1;
result += value * Math.sqrt(count);
});
break;
case 16: // for Seaplane Tender
// Medium cal. guns for partial AVs, no formula summarized
// https://docs.google.com/spreadsheets/d/1wl9v3NqPuRawSuFadokgYh1R1R1W82H51JNC66DH2q8/htmlview
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.
* NOTE: type ID shifted to 1-based since Phase 2, but internal values here unchanged.
* @see `TaskAircraftFlightBase.prototype._getAntiAircraftAbility`
* @see `TaskAirWarAntiAircraft._type` - AA attack animation types
*/
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 [0, "None"];
case 0: return [1, "Normal"];
case 1: return [2, "HighAngleMount"];
case 2: return [3, "RocketLauncher"];
case 3: return [4, "RocketLauncherK2"];
case 4: return [5, "Type3Shell"];
case 5: return [6, "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/noratako5/status/1062027534026428416 - luck modifier
* @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] * 0.9) /
(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.
* @param {Object} oldShipObj - the cloned old ship instance with stats and item IDs before equipment changed.
*/
KC3Ship.prototype.equipmentChangedEffects = function(newGearObj = {}, oldGearObj = {}, oldShipObj = this) {
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;
// NOTE: shipObj here to be returned will be the 'old' ship instance,
// whose stats, like fp, tp, asw, are the values before equipment change.
// but its items array (including ex item) are post-change values.
const shipObj = this;
// To get the 'latest' ship stats, should defer `GunFit` event after `api_get_member/ship3` call,
// and retrieve latest ship instance via KC3ShipManager.get method like this:
// const newShipObj = KC3ShipManager.get(data.shipObj.rosterId);
// It can not be latest ship at the timing of this equipmentChangedEffects invoked,
// because the api call above not executed, KC3ShipManager data not updated yet.
// Or you can compute the simple stat difference manually like this:
const oldEquipAsw = oldGearObj.masterId > 0 ? oldGearObj.master().api_tais : 0;
const newEquipAsw = newGearObj.masterId > 0 ? newGearObj.master().api_tais : 0;
const aswDiff = newEquipAsw - oldEquipAsw
// explicit asw bonus from new equipment
+ shipObj.equipmentTotalStats("tais", true, true, true)
// explicit asw bonus from old equipment
- oldShipObj.equipmentTotalStats("tais", true, true, true);
const oaswPower = shipObj.canDoOASW(aswDiff) ? shipObj.antiSubWarfarePower(aswDiff) : false;
isShow = isShow || (oaswPower !== false);
const antiLandPowers = shipObj.shipPossibleAntiLandPowers();
isShow = isShow || antiLandPowers.length > 0;
const equipBonus = shipObj.equipmentBonusGearAndStats(newGearObj);
isShow = isShow || (equipBonus !== false && equipBonus.isShow);
// Possible TODO:
// can opening torpedo
// can cut-in (fire / air)
// can night attack for CV
// can night cut-in
return {
isShow,
shipObj,
shipOld: oldShipObj,
gearObj: newGearObj.masterId ? newGearObj : false,
gunFit,
shipAacis,
oaswPower,
antiLandPowers: antiLandPowers.length > 0,
equipBonus,
};
};
/* 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);
return true;
} catch (e) {
console.error("Failed when perform" + command, e);
return false;
}
};
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(),
bonusStats = shipObj.statsBonusOnShip(),
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 optionalNumber = (n, pre = '\u21d1', show0 = false) => !n && (!show0 || n !== 0) ? '' : pre + n;
const replaceFilename = (file, newName) => file.slice(0, file.lastIndexOf("/") + 1) + newName;
$(".stat_value span", tooltipBox).css("display", "inline");
$(".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}{1})".format(nakedStats.fp, optionalNumber(bonusStats.fp)))
.toggle(!!equipDiffStats.fp || !!bonusStats.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}{1})".format(nakedStats.ar, optionalNumber(bonusStats.ar)))
.toggle(!!equipDiffStats.ar || !!bonusStats.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}{1})".format(nakedStats.tp, optionalNumber(bonusStats.tp)))
.toggle(!!equipDiffStats.tp || !!bonusStats.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}{1})".format(nakedStats.ev, optionalNumber(bonusStats.ev)))
.toggle(!!equipDiffStats.ev || !!bonusStats.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}{1})".format(nakedStats.aa, optionalNumber(bonusStats.aa)))
.toggle(!!equipDiffStats.aa || !!bonusStats.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}{1})".format(nakedStats.as, optionalNumber(bonusStats.as)))
.toggle(!!equipDiffStats.as || !!bonusStats.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}{1})".format(nakedStats.ls, optionalNumber(bonusStats.ls)))
.toggle(!!equipDiffStats.ls || !!bonusStats.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 shipMst = shipObj.master();
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 canAsw = shipObj.canDoASW();
if(canAsw){
const aswAttackType = shipObj.estimateDayAttackType(1530, false);
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, aswAttackType[0] === "AirAttack").power;
}
({power} = shipObj.applyPostcapModifiers(power, "Antisub"));
}
let attackTypeIndicators = !canShellingAttack || !canAsw ?
KC3Meta.term("ShipAttackTypeNone") :
KC3Meta.term("ShipAttackType" + aswAttackType[0]);
if(canOpeningTorp) attackTypeIndicators += ", {0}"
.format(KC3Meta.term("ShipExtraPhaseOpeningTorpedo"));
if(canClosingTorp) attackTypeIndicators += ", {0}"
.format(KC3Meta.term("ShipExtraPhaseClosingTorpedo"));
$(".dayAswPower", tooltipBox).html(
KC3Meta.term("ShipDayAttack").format(
KC3Meta.term("ShipWarfareAntisub"),
joinPowerAndCritical(power, criticalPower, isCapped),
attackTypeIndicators
)
);
} else {
$(".dayAswPower", tooltipBox).html("-");
}
const isAswPowerShown = canAsw && (canOasw && !shipObj.isOaswShip()
|| shipObj.onlyHasEquipmentType(1, [10, 15, 16, 32]));
// Show ASW power if Opening ASW conditions met, or only ASW equipment equipped
if(isAswPowerShown){
$(".dayAttack", tooltipBox).parent().parent().hide();
} else {
$(".dayAswPower", tooltipBox).parent().parent().hide();
}
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);
const dayCutinRate = shipObj.artillerySpottingRate(spAttackType[1], spAttackType[2]);
// 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]) + (dayCutinRate ? " {0}%".format(dayCutinRate) : "") :
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();
// See functions in previous 2 lines, ships whose night attack is AirAttack,
// but power formula seems be shelling: Taiyou Kai Ni, Shinyou Kai Ni
const hasYasenPower = (shipMst.api_houg || [])[0] + (shipMst.api_raig || [])[0] > 0;
const hasNightFlag = attackTypeNight[0] === "AirAttack" && attackTypeNight[2] === true;
const warfareTypeNight = {
"Torpedo" : "Torpedo",
"DepthCharge" : "Antisub",
"LandingAttack" : "AntiLand",
"Rocket" : "AntiLand"
}[attackTypeNight[0]] || "Shelling";
if(attackTypeNight[0] === "AirAttack" && canNightAttack && (hasNightFlag || !hasYasenPower)){
let power = shipObj.nightAirAttackPower(battleConds.contactPlaneId == 102);
let criticalPower = false;
let isCapped = false;
const spAttackType = shipObj.estimateNightAttackType(undefined, true);
const nightCutinRate = shipObj.nightCutinRate(spAttackType[1], spAttackType[2]);
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]) + (nightCutinRate ? " {0}%".format(nightCutinRate) : "") :
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);
const nightCutinRate = shipObj.nightCutinRate(spAttackType[1], spAttackType[2]);
// 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]) + (nightCutinRate ? " {0}%".format(nightCutinRate) : "") :
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 > 0 ?
" ({0})".format(
aaEffectTypeId === 4 ?
// 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");
// show day shelling power instead of ASW power (if any) on holding Alt key
if(event.altKey && $(".dayAswPower", ui.tooltip).is(":visible")) {
$(".dayAswPower", ui.tooltip).parent().parent().hide();
$(".dayAttack", ui.tooltip).parent().parent().show();
}
// show day ASW power instead of shelling power if can ASW on holding Ctrl/Meta key
if((event.ctrlKey || event.metaKey) && !$(".dayAswPower", ui.tooltip).is(":visible")
&& $(".dayAswPower", ui.tooltip).text() !== "-") {
$(".dayAswPower", ui.tooltip).parent().parent().show();
$(".dayAttack", ui.tooltip).parent().parent().hide();
}
return true;
};
KC3Ship.prototype.deckbuilder = function() {
var itemsInfo = {};
var result = {
id: this.masterId,
lv: this.level,
luck: this.lk[0],
hp: this.hp[0],
asw : this.nakedAsw(),
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;
};
})();
|
var watchers = Object.create(null);
var wait = function (linkid, callback) {
watchers[linkid] = cross("options", "/:care-" + linkid).success(function (res) {
if (watchers[linkid]) wait(linkid, callback);
var a = JSAM.parse(res.responseText);
if (isFunction(callback)) a.forEach(b => callback(b));
}).error(function () {
if (watchers[linkid]) wait(linkid, callback);
});
};
var kill = function (linkid) {
var r = watchers[linkid];
delete watchers[linkid];
if (r) r.abort();
};
var block_size = 1024;
var cast = function (linkid, data) {
data = encode(data);
var inc = 0, size = block_size;
return new Promise(function (ok, oh) {
var run = function () {
if (inc > data.length) return ok();
cross("options", "/:cast-" + linkid + "?" + data.slice(inc, inc + size)).success(run).error(oh);
inc += size;
};
run();
}).then(function () {
if (inc === data.length) {
return cast(linkid, '');
}
});
};
var encode = function (data) {
var str = encodeURIComponent(data.replace(/\-/g, '--')).replace(/%/g, '-');
return str;
};
var decode = function (params) {
params = params.replace(/\-\-|\-/g, a => a === '-' ? '%' : '-');
params = decodeURIComponent(params);
return params;
};
function serve(listener) {
return new Promise(function (ok, oh) {
cross("options", "/:link").success(function (res) {
var responseText = res.responseText;
wait(responseText, listener);
ok(responseText);
}).error(oh);
})
}
function servd(getdata) {
return serve(function (linkid) {
cast(linkid, JSAM.stringify(getdata()));
});
}
function servp(linkto) {
return new Promise(function (ok, oh) {
var blocks = [], _linkid;
serve(function (block) {
blocks.push(block);
if (block.length < block_size) {
var data = decode(blocks.join(''));
ok(JSAM.parse(data));
kill(_linkid);
}
}).then(function (linkid) {
cast(linkto, linkid);
_linkid = linkid;
}, oh);
});
}
serve.servd = servd;
serve.servp = servp;
serve.kill = kill;
|
/**
* This cli.js test file tests the `gnode` wrapper executable via
* `child_process.spawn()`. Generator syntax is *NOT* enabled for these
* test cases.
*/
var path = require('path');
var assert = require('assert');
var semver = require('semver');
var spawn = require('child_process').spawn;
// node executable
var node = process.execPath || process.argv[0];
var gnode = path.resolve(__dirname, '..', 'bin', 'gnode');
// chdir() to the "test" dir, so that relative test filenames work as expected
process.chdir(path.resolve(__dirname, 'cli'));
describe('command line interface', function () {
this.slow(1000);
this.timeout(2000);
cli([ '-v' ], 'should output the version number', function (child, done) {
buffer(child.stdout, function (err, data) {
assert(semver.valid(data.trim()));
done();
});
});
cli([ '--help' ], 'should output the "help" display', function (child, done) {
buffer(child.stdout, function (err, data) {
assert(/^Usage\: (node|iojs)/.test(data));
done();
});
});
cli([ 'check.js' ], 'should quit with a SUCCESS exit code', function (child, done) {
child.on('exit', function (code) {
assert(code == 0, 'gnode quit with exit code: ' + code);
done();
});
});
cli([ 'nonexistant.js' ], 'should quit with a FAILURE exit code', function (child, done) {
child.on('exit', function (code) {
assert(code != 0, 'gnode quit with exit code: ' + code);
done();
});
});
cli([ 'argv.js', '1', 'foo' ], 'should have a matching `process.argv`', function (child, done) {
buffer(child.stdout, function (err, data) {
if (err) return done(err);
data = JSON.parse(data);
assert('argv.js' == path.basename(data[1]));
assert('1' == data[2]);
assert('foo' == data[3]);
done();
});
});
cli([ '--harmony_generators', 'check.js' ], 'should not output the "unrecognized flag" warning', function (child, done) {
var async = 2;
buffer(child.stderr, function (err, data) {
if (err) return done(err);
assert(!/unrecognized flag/.test(data), 'got stderr data: ' + JSON.stringify(data));
--async || done();
});
child.on('exit', function (code) {
assert(code == 0, 'gnode quit with exit code: ' + code);
--async || done();
});
});
cli([], 'should work properly over stdin', function (child, done) {
child.stdin.end(
'var assert = require("assert");' +
'function *test () {};' +
'var t = test();' +
'assert("function" == typeof t.next);' +
'assert("function" == typeof t.throw);'
);
child.on('exit', function (code) {
assert(code == 0, 'gnode quit with exit code: ' + code);
done();
});
});
if (!/^v0.8/.test(process.version)) cli(['-p', 'function *test () {yield 3}; test().next().value;'], 'should print result with -p', function (child, done) {
var async = 2
buffer(child.stdout, function (err, data) {
if (err) return done(err);
assert('3' == data.trim(), 'gnode printed ' + data);
--async || done();
});
child.on('exit', function (code) {
assert(code == 0, 'gnode quit with exit code: ' + code);
--async || done();
});
});
cli(['-e', 'function *test () {yield 3}; console.log(test().next().value);'], 'should print result with -e', function (child, done) {
var async = 2
buffer(child.stdout, function (err, data) {
if (err) return done(err);
assert('3' == data.trim(), 'expected 3, got: ' + data);
--async || done();
});
child.on('exit', function (code) {
assert(code == 0, 'gnode quit with exit code: ' + code);
--async || done();
});
});
cli(['--harmony_generators', '-e', 'function *test () {yield 3}; console.log(test().next().value);'], 'should print result with -e', function (child, done) {
var async = 2
buffer(child.stdout, function (err, data) {
if (err) return done(err);
assert('3' == data.trim(), 'gnode printed ' + data);
--async || done();
});
child.on('exit', function (code) {
assert(code == 0, 'gnode quit with exit code: ' + code);
--async || done();
});
});
cli(['-e', 'console.log(JSON.stringify(process.argv))', 'a', 'b', 'c'], 'should pass additional arguments after -e', function (child, done) {
var async = 2
buffer(child.stdout, function (err, data) {
if (err) return done(err);
data = JSON.parse(data)
assert.deepEqual(['a', 'b', 'c'], data.slice(2))
--async || done();
});
child.on('exit', function (code) {
assert(code == 0, 'gnode quit with exit code: ' + code);
--async || done();
});
});
});
function cli (argv, name, fn) {
describe('gnode ' + argv.join(' '), function () {
it(name, function (done) {
var child = spawn(node, [ gnode ].concat(argv));
fn(child, done);
});
});
}
function buffer (stream, fn) {
var buffers = '';
stream.setEncoding('utf8');
stream.on('data', ondata);
stream.on('end', onend);
stream.on('error', onerror);
function ondata (b) {
buffers += b;
}
function onend () {
stream.removeListener('error', onerror);
fn(null, buffers);
}
function onerror (err) {
fn(err);
}
}
|
var group___s_t_m32_f4xx___h_a_l___driver =
[
[ "CRC", "group___c_r_c.html", "group___c_r_c" ],
[ "GPIOEx", "group___g_p_i_o_ex.html", "group___g_p_i_o_ex" ],
[ "AHB3 Peripheral Clock Enable Disable", "group___r_c_c_ex___a_h_b3___clock___enable___disable.html", null ],
[ "HAL", "group___h_a_l.html", "group___h_a_l" ],
[ "ADC", "group___a_d_c.html", "group___a_d_c" ],
[ "ADCEx", "group___a_d_c_ex.html", "group___a_d_c_ex" ],
[ "CORTEX", "group___c_o_r_t_e_x.html", "group___c_o_r_t_e_x" ],
[ "DMA", "group___d_m_a.html", "group___d_m_a" ],
[ "DMAEx", "group___d_m_a_ex.html", "group___d_m_a_ex" ],
[ "FLASH", "group___f_l_a_s_h.html", "group___f_l_a_s_h" ],
[ "FLASHEx", "group___f_l_a_s_h_ex.html", "group___f_l_a_s_h_ex" ],
[ "GPIO", "group___g_p_i_o.html", "group___g_p_i_o" ],
[ "I2C", "group___i2_c.html", "group___i2_c" ],
[ "I2S", "group___i2_s.html", "group___i2_s" ],
[ "I2SEx", "group___i2_s_ex.html", "group___i2_s_ex" ],
[ "IRDA", "group___i_r_d_a.html", "group___i_r_d_a" ],
[ "IWDG", "group___i_w_d_g.html", "group___i_w_d_g" ],
[ "NAND", "group___n_a_n_d.html", null ],
[ "NOR", "group___n_o_r.html", null ],
[ "PWR", "group___p_w_r.html", "group___p_w_r" ],
[ "PWREx", "group___p_w_r_ex.html", "group___p_w_r_ex" ],
[ "RCC", "group___r_c_c.html", "group___r_c_c" ],
[ "RCCEx", "group___r_c_c_ex.html", "group___r_c_c_ex" ],
[ "RTC", "group___r_t_c.html", "group___r_t_c" ],
[ "RTCEx", "group___r_t_c_ex.html", "group___r_t_c_ex" ],
[ "SAI", "group___s_a_i.html", "group___s_a_i" ],
[ "SAIEx", "group___s_a_i_ex.html", "group___s_a_i_ex" ],
[ "SMARTCARD", "group___s_m_a_r_t_c_a_r_d.html", "group___s_m_a_r_t_c_a_r_d" ],
[ "SPI", "group___s_p_i.html", "group___s_p_i" ],
[ "TIM", "group___t_i_m.html", "group___t_i_m" ],
[ "TIMEx", "group___t_i_m_ex.html", "group___t_i_m_ex" ],
[ "UART", "group___u_a_r_t.html", "group___u_a_r_t" ],
[ "USART", "group___u_s_a_r_t.html", "group___u_s_a_r_t" ],
[ "WWDG", "group___w_w_d_g.html", "group___w_w_d_g" ],
[ "FMC_LL", "group___f_m_c___l_l.html", "group___f_m_c___l_l" ],
[ "FSMC_LL", "group___f_s_m_c___l_l.html", null ]
]; |
import React from 'react'
import { compose } from 'redux'
import { connect } from 'react-redux'
import { Field, FieldArray, reduxForm } from 'redux-form'
import { amount, autocomplete, debitCredit } from './Fields'
import { Button, FontIcon } from 'react-toolbox'
import { getAutocomplete } from 'modules/autocomplete'
import { create } from 'modules/entities/journalEntryCreatedEvents'
import classes from './JournalEntryForm.scss'
import { fetch as fetchLedgers } from 'modules/entities/ledgers'
const validate = (values) => {
const errors = {}
return errors
}
const renderRecords = ({ fields, meta: { touched, error, submitFailed }, ledgers, financialFactId }) => (
<div>
<div>
<Button onClick={() => fields.push({})}> <FontIcon value='add' /></Button>
{(touched || submitFailed) && error && <span>{error}</span>}
</div>
<div className={classes.recordsList}>
{fields.map((record, index) =>
<div key={index}>
<Button
onClick={() => fields.remove(index)}> <FontIcon value='remove' /></Button>
<div className={classes.journalEntryField}>
<Field name={`${record}.ledger`}
component={autocomplete}
label='Ledger'
source={ledgers}
multiple={false}
/>
</div>
<div className={classes.journalEntryField}>
<Field
name={`${record}.debitCredit`}
component={debitCredit}
label='Debit/credit' />
</div>
<div className={classes.journalEntryField}>
<Field
name={`${record}.amount`}
component={amount}
label='Amount' />
</div>
</div>
)}
</div>
</div>
)
const JournalEntryForm = (props) => {
const { ledgers, handleSubmit, submitting, reset } = props
return (
<div className={classes.journalEntryForm}>
<form onSubmit={handleSubmit}>
<FieldArray name='records' component={renderRecords} ledgers={ledgers} />
<Button type='submit' disabled={submitting}>Submit</Button>
<Button type='button' disabled={submitting} onClick={reset}>Clear</Button>
</form>
</div>
)
}
const onSubmit = (values) => {
return create({
values: {
...values
}
})
}
const mapDispatchToProps = {
onSubmit,
fetchLedgers
}
const mapStateToProps = (state) => {
return {
ledgers: getAutocomplete(state, 'ledgers')
}
}
export default compose(
connect(mapStateToProps, mapDispatchToProps),
reduxForm({
form: 'JournalEntryForm',
validate
}))(JournalEntryForm)
|
var _ = require('lodash');
var localConfig = {};
try {
localConfig = require('./config.local');
} catch (e) {
console.log(e.code === 'MODULE_NOT_FOUND');
if (e.code !== 'MODULE_NOT_FOUND' || e.message.indexOf('config.local') < 0) {
//config.local module is broken, rethrow the exception
throw e;
}
}
var path = require('path');
var defaultConfig = {
dataSources: [
{
type: 'local',
base: 'tmp/',
endpoints: ['nodes.json', 'graph.json'],
interval: 3000
}
// {
// type: 'remote',
// base: 'http://example.com/ffmap/',
// endpoints: ['nodes.json', 'graph.json'],
// interval: 30000
// },
],
frontend: {
path: path.join(__dirname, 'public')
},
database: {
host: 'rethinkdb',
port: '28015',
db: 'ffmap'
},
port: 8000
};
module.exports = _.defaults({
defaults: defaultConfig
}, localConfig, defaultConfig);
|
const frisby = require('frisby')
const config = require('config')
const URL = 'http://localhost:3000'
let blueprint
for (const product of config.get('products')) {
if (product.fileForRetrieveBlueprintChallenge) {
blueprint = product.fileForRetrieveBlueprintChallenge
break
}
}
describe('Server', () => {
it('GET responds with index.html when visiting application URL', done => {
frisby.get(URL)
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', 'dist/juice-shop.min.js')
.done(done)
})
it('GET responds with index.html when visiting application URL with any path', done => {
frisby.get(URL + '/whatever')
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', 'dist/juice-shop.min.js')
.done(done)
})
it('GET a restricted file directly from file system path on server via Directory Traversal attack loads index.html instead', done => {
frisby.get(URL + '/public/images/../../ftp/eastere.gg')
.expect('status', 200)
.expect('bodyContains', '<meta name="description" content="An intentionally insecure JavaScript Web Application">')
.done(done)
})
it('GET a restricted file directly from file system path on server via URL-encoded Directory Traversal attack loads index.html instead', done => {
frisby.get(URL + '/public/images/%2e%2e%2f%2e%2e%2fftp/eastere.gg')
.expect('status', 200)
.expect('bodyContains', '<meta name="description" content="An intentionally insecure JavaScript Web Application">')
.done(done)
})
})
describe('/public/images/tracking', () => {
it('GET tracking image for "Score Board" page access challenge', done => {
frisby.get(URL + '/public/images/tracking/scoreboard.png')
.expect('status', 200)
.expect('header', 'content-type', 'image/png')
.done(done)
})
it('GET tracking image for "Administration" page access challenge', done => {
frisby.get(URL + '/public/images/tracking/administration.png')
.expect('status', 200)
.expect('header', 'content-type', 'image/png')
.done(done)
})
it('GET tracking background image for "Geocities Theme" challenge', done => {
frisby.get(URL + '/public/images/tracking/microfab.gif')
.expect('status', 200)
.expect('header', 'content-type', 'image/gif')
.done(done)
})
})
describe('/encryptionkeys', () => {
it('GET serves a directory listing', done => {
frisby.get(URL + '/encryptionkeys')
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', '<title>listing directory /encryptionkeys</title>')
.done(done)
})
it('GET a non-existing file in will return a 404 error', done => {
frisby.get(URL + '/encryptionkeys/doesnotexist.md')
.expect('status', 404)
.done(done)
})
it('GET the Premium Content AES key', done => {
frisby.get(URL + '/encryptionkeys/premium.key')
.expect('status', 200)
.done(done)
})
it('GET a key file whose name contains a "/" fails with a 403 error', done => {
frisby.fetch(URL + '/encryptionkeys/%2fetc%2fos-release%2500.md', {}, { urlEncode: false })
.expect('status', 403)
.expect('bodyContains', 'Error: File names cannot contain forward slashes!')
.done(done)
})
})
describe('Hidden URL', () => {
it('GET the second easter egg by visiting the Base64>ROT13-decrypted URL', done => {
frisby.get(URL + '/the/devs/are/so/funny/they/hid/an/easter/egg/within/the/easter/egg')
.expect('status', 200)
.expect('header', 'content-type', /text\/html/)
.expect('bodyContains', '<title>Welcome to Planet Orangeuze</title>')
.done(done)
})
it('GET the premium content by visiting the ROT5>Base64>z85>ROT5-decrypted URL', done => {
frisby.get(URL + '/this/page/is/hidden/behind/an/incredibly/high/paywall/that/could/only/be/unlocked/by/sending/1btc/to/us')
.expect('status', 200)
.expect('header', 'content-type', 'image/gif')
.done(done)
})
it('GET Geocities theme CSS is accessible directly from file system path', done => {
frisby.get(URL + '/css/geo-bootstrap/swatch/bootstrap.css')
.expect('status', 200)
.expect('bodyContains', 'Designed and built with all the love in the world @twitter by @mdo and @fat.')
.done(done)
})
it('GET Klingon translation file for "Extra Language" challenge', done => {
frisby.get(URL + '/i18n/tlh_AA.json')
.expect('status', 200)
.expect('header', 'content-type', /application\/json/)
.done(done)
})
it('GET blueprint file for "Retrieve Blueprint" challenge', done => {
frisby.get(URL + '/public/images/products/' + blueprint)
.expect('status', 200)
.done(done)
})
})
|
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Navigation.css';
import Link from '../Link';
class Navigation extends React.Component {
render() {
return (
<div className={s.root} role="navigation">
<Link className={s.link} to="/catalog">Каталог продукції</Link>
<Link className={s.link} to="/about">Про нас</Link>
<Link className={s.link} to="/catalog">Наші роботи</Link>
</div>
);
}
}
export default withStyles(s)(Navigation);
|
/* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);
var _svgIcon = require('../../svg-icon');
var _svgIcon2 = _interopRequireDefault(_svgIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var HardwarePhonelinkOff = _react2.default.createClass({
displayName: 'HardwarePhonelinkOff',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z'}));
}
});
exports.default = HardwarePhonelinkOff;
module.exports = exports['default'];
|
define(function(require, exports) {
'use strict';
var Backbone = require('backbone')
, global = require('global');
var teamColours = [
'#FFBBBB', '#FFE1BA', '#FDFFBA', '#D6FFBA',
'#BAFFCE', '#BAFFFD', '#BAE6FF', '#BAC8FF',
'#D3BAFF', '#EBBAFF', '#E4E0FF', '#BAFCE1',
'#FCC6BB', '#E3F3CE', '#EEEEEE', '#D8FFF4'
];
exports.Problem = Backbone.Model.extend({});
exports.Team = Backbone.Model.extend({
colour: function() {
return teamColours[this.id % teamColours.length];
}
});
exports.Stage = Backbone.Model.extend({
glyphs: {
1: 'remove',
2: 'ok',
3: 'forward'
},
glyph: function() {
return this.glyphs[this.get('state')];
}
});
}); |
'use strict';
// Setting up route
angular.module('socialevents').config(['$stateProvider',
function($stateProvider) {
// SocialEvents state routing
$stateProvider.
state('listSocialEvents', {
url: '/socialevents',
templateUrl: 'modules/socialevents/views/list-socialevents.client.view.html'
}).
state('createSocialEvent', {
url: '/socialevents/create',
templateUrl: 'modules/socialevents/views/create-socialevent.client.view.html'
}).
state('viewSocialEvent', {
url: '/socialevents/:socialeventId',
templateUrl: 'modules/socialevents/views/view-socialevent.client.view.html'
}).
state('editSocialEvent', {
url: '/socialevents/:socialeventId/edit',
templateUrl: 'modules/socialevents/views/edit-socialevent.client.view.html'
});
}
]); |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.10.2.15_A1_T8;
* @section: 15.10.2.15;
* @assertion: The internal helper function CharacterRange takes two CharSet parameters A and B and performs the
* following:
* If A does not contain exactly one character or B does not contain exactly one character then throw
* a SyntaxError exception;
* @description: Checking if execution of "/[\Wb-G]/.exec("a")" leads to throwing the correct exception;
*/
//CHECK#1
try {
$ERROR('#1.1: /[\\Wb-G]/.exec("a") throw SyntaxError. Actual: ' + (/[\Wb-G]/.exec("a")));
} catch (e) {
if((e instanceof SyntaxError) !== true){
$ERROR('#1.2: /[\\Wb-G]/.exec("a") throw SyntaxError. Actual: ' + (e));
}
}
|
const autoprefixer = require('autoprefixer');
const precss = require('precss');
const stylelint = require('stylelint');
const fontMagician = require('postcss-font-magician')({
// this is required due to a weird bug where if we let PFM use the `//` protocol Webpack style-loader
// thinks it's a relative URL and won't load the font when sourceMaps are also enabled
protocol: 'https:',
display: 'swap',
});
module.exports = {
plugins: [stylelint, fontMagician, precss, autoprefixer],
};
|
(function(window, document){
var chart;
var pressure_chart;
var lasttime;
function drawCurrent(data)
{
var tempDHT, tempBMP;
if (data.count_dht022 > 0)
{
lasttime = data.humidity[data.count_dht022-1][0];
tempDHT = data.temperature_dht022[data.count_dht022-1][1];
document.querySelector("span#humidityDHT022").innerHTML = data.humidity[data.count_dht022-1][1];
var date = new Date(lasttime);
document.querySelector("span#time").innerHTML = date.toTimeString();
}
if (data.count_bmp180 > 0)
{
lasttime = data.temperature_bmp180[data.count_bmp180-1][0];
tempBMP = data.temperature_bmp180[data.count_bmp180-1][1];
document.querySelector("span#pressureBMP180").innerHTML = data.pressure[data.count_bmp180-1][1] + 'mm hg (' + (data.pressure[data.count_bmp180-1][1] / 7.50061561303).toFixed(2) + ' kPa)' ;
var date = new Date(lasttime);
document.querySelector("span#time").innerHTML = date.toTimeString();
}
document.querySelector("span#temperature").innerHTML = '<abbr title="BMP180 ' + tempBMP + ', DHT022 ' + tempDHT + '">' + ((tempDHT + tempBMP)/2).toFixed(1) + '</abbr>';
document.querySelector("span#lastupdate").innerHTML = new Date().toTimeString();
}
function requestDelta()
{
$.ajax({
url: 'weather_new.php?mode=delta&delta='+lasttime,
datatype: "json",
success: function(data)
{
var i;
if (data.count > 0) {
for(i=0; i<data.count_dht022;i++)
chart.series[0].addPoint(data.temperature_dht022[i], false, true);
for(i=0; i<data.count_dht022;i++)
chart.series[1].addPoint(data.humidity[i], false, true);
for(i=0; i<data.count_bmp180;i++)
chart.series[0].addPoint(data.temperature_bmp180[i], false, true);
for(i=0; i<data.count_bmp180;i++)
pressure_chart.series[0].addPoint(data.pressure[i], false, true);
chart.redraw();
pressure_chart.redraw();
}
drawCurrent(data);
}
});
}
function requestData()
{
var daterange = document.querySelector("select#daterange").value;
if (!daterange)
daterange = "today";
$.ajax({
url: 'weather_new.php?mode='+daterange,
datatype: "json",
success: function(data)
{
chart.series[0].setData(data.temperature_dht022);
chart.series[1].setData(data.humidity);
chart.series[2].setData(data.temperature_bmp180);
pressure_chart.series[0].setData(data.pressure);
drawCurrent(data);
setInterval(requestDelta, 5 * 60 * 1000);
}
});
}
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'graph',
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Monitoring'
},
tooltip: {
shared: true
},
xAxis: {
type: 'datetime',
maxZoom: 20 * 1000
},
yAxis: {
min: 10,
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Temperature/Humidity',
margin: 80
}
},
series: [{
name: 'Temperature DHT022',
data: []
},
{
name: 'Humidity',
data: []
},
{
name: 'Temperature BMP180',
data: []
}]
});
pressure_chart = new Highcharts.Chart({
chart: {
renderTo: 'pressure_graph',
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Pressure monitoring'
},
tooltip: {
shared: true
},
xAxis: {
type: 'datetime',
maxZoom: 20 * 1000
},
yAxis: {
min: 700,
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Pressure',
margin: 80
}
},
series: [{
name: 'Pressure',
data: []
}]
});
$('select#daterange').change(function() {requestData();});
});
})(window, document)
|
'use strict';
//Translations service used for translations REST endpoint
angular.module('mean.translations').factory('deleteTranslations', ['$resource',
function($resource) {
return $resource('deleteTranslations/:translationId', {
translationId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
/**
* @flow
*/
import React from 'react';
import {storiesOf} from '@kadira/storybook';
import Textarea from './Textarea';
storiesOf('<Textarea />', module)
.add('Default state', () => <Textarea />)
.add('Error state', () => <Textarea error />)
.add('Disabled state', () => <Textarea disabled />)
.add('No border variant', () => <Textarea noBorder />);
|
/* jshint node:true */
// var RSVP = require('rsvp');
// For details on each option run `ember help release`
module.exports = {
// local: true,
// remote: 'some_remote',
// annotation: "Release %@",
// message: "Bumped version to %@",
manifest: [ 'package.json', 'package-lock.json']
// publish: true,
// strategy: 'date',
// format: 'YYYY-MM-DD',
// timezone: 'America/Los_Angeles',
//
// beforeCommit: function(project, versions) {
// return new RSVP.Promise(function(resolve, reject) {
// // Do custom things here...
// });
// }
};
|
module.exports = function(player, playerSpec) {
return ('data:image/svg+xml;utf-8,' +
encodeURIComponent(
`<svg width="${playerSpec.width}" height="${playerSpec.height}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${playerSpec.width} ${playerSpec.height}" version="1.1" class="mapSvg"> \
<circle cx="${playerSpec.width/2}" cy="${playerSpec.height/2}" r="${playerSpec.height/4}" class="mapSvg__player" stroke="${playerSpec[player].color}" fill="${playerSpec[player].color}"/> \
</svg>`
)
);
};
|
"use strict";
var chai = require('chai'),
should = chai.should(),
expect = chai.expect,
XMLGrammers = require('../').XMLGrammers,
Parameters = require('../').Parameters;
describe('FMServerConstants', function(){
describe('XMLGrammers', function(){
it('should be frozen', function(){
expect(function(){
XMLGrammers.a = 1;
}).to.throw("Can't add property a, object is not extensible");
});
});
describe('Parameters', function() {
it('should be frozen', function () {
expect(function () {
Parameters.a = 1;
}).to.throw("Can't add property a, object is not extensible");
})
})
})
|
define(
[
'Magento_Checkout/js/model/error-processor',
'Magento_Checkout/js/model/full-screen-loader',
'Magento_Checkout/js/model/url-builder'
],
function (
errorProcessor,
fullScreenLoader,
urlBuilder
) {
'use strict';
const RETURN_URL = '/orders/:order_id/omise-offsite';
return {
/**
* Get return URL for Magento (based on order id)
*
* @return {string}
*/
getMagentoReturnUrl: function (order_id) {
return urlBuilder.createUrl(
RETURN_URL,
{ order_id }
);
},
/**
* Get payment method code
*
* @return {string}
*/
getCode: function() {
return this.code;
},
/**
* Is method available to display
*
* @return {boolean}
*/
isActive: function() {
if (this.restrictedToCurrencies && this.restrictedToCurrencies.length) {
let orderCurrency = this.getOrderCurrency();
return (this.getStoreCurrency() == orderCurrency) && this.restrictedToCurrencies.includes(orderCurrency);
} else {
return true;
}
},
/**
* Get order currency
*
* @return {string}
*/
getOrderCurrency: function () {
return window.checkoutConfig.quoteData.quote_currency_code.toLowerCase();
},
/**
* Get store currency
*
* @return {string}
*/
getStoreCurrency: function () {
return window.checkoutConfig.quoteData.store_currency_code.toLowerCase();
},
/**
* Checks if sandbox is turned on
*
* @return {boolean}
*/
isSandboxOn: function () {
return window.checkoutConfig.isOmiseSandboxOn;
},
/**
* Creates a fail handler for given context
*
* @return {boolean}
*/
buildFailHandler(context) {
return function (response) {
errorProcessor.process(response, context.messageContainer);
fullScreenLoader.stopLoader();
context.isPlaceOrderActionAllowed(true);
}
}
};
}
);
|
// Parts of this source are modified from npm and lerna:
// npm: https://github.com/npm/npm/blob/master/LICENSE
// lerna: https://github.com/lerna/lerna/blob/master/LICENSE
// @flow
import fs from 'fs';
import path from 'path';
import _cmdShim from 'cmd-shim';
import _readCmdShim from 'read-cmd-shim';
import promisify from 'typeable-promisify';
import makeDir from 'make-dir';
import _rimraf from 'rimraf';
export function readFile(filePath: string): Promise<string> {
return promisify(cb => fs.readFile(filePath, cb));
}
export function writeFile(
filePath: string,
fileContents: string
): Promise<string> {
return promisify(cb => fs.writeFile(filePath, fileContents, cb));
}
export function mkdirp(filePath: string): Promise<void> {
return makeDir(filePath);
}
export function rimraf(filePath: string): Promise<void> {
return promisify(cb => _rimraf(filePath, cb));
}
export function stat(filePath: string) {
return promisify(cb => fs.stat(filePath, cb));
}
export function lstat(filePath: string) {
return promisify(cb => fs.lstat(filePath, cb));
}
function unlink(filePath: string) {
return promisify(cb => fs.unlink(filePath, cb));
}
export function realpath(filePath: string) {
return promisify(cb => fs.realpath(filePath, cb));
}
function _symlink(src: string, dest: string, type: string) {
return promisify(cb => fs.symlink(src, dest, type, cb));
}
function stripExtension(filePath: string) {
return path.join(
path.dirname(filePath),
path.basename(filePath, path.extname(filePath))
);
}
async function cmdShim(src: string, dest: string) {
// If not a symlink we default to the actual src file
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L273
let relativeShimTarget = await readlink(src);
let currentShimTarget = relativeShimTarget
? path.resolve(path.dirname(src), relativeShimTarget)
: src;
await promisify(cb => _cmdShim(currentShimTarget, stripExtension(dest), cb));
}
async function createSymbolicLink(src, dest, type) {
try {
await lstat(dest);
await rimraf(dest);
} catch (err) {
if (err.code === 'EPERM') throw err;
}
await _symlink(src, dest, type);
}
async function createPosixSymlink(origin, dest, type) {
if (type === 'exec') {
type = 'file';
}
let src = path.relative(path.dirname(dest), origin);
return await createSymbolicLink(src, dest, type);
}
async function createWindowsSymlink(src, dest, type) {
if (type === 'exec') {
return await cmdShim(src, dest);
} else {
return await createSymbolicLink(src, dest, type);
}
}
export async function symlink(
src: string,
dest: string,
type: 'exec' | 'junction'
) {
if (dest.includes(path.sep)) {
await mkdirp(path.dirname(dest));
}
if (process.platform === 'win32') {
return await createWindowsSymlink(src, dest, type);
} else {
return await createPosixSymlink(src, dest, type);
}
}
export async function readdir(dir: string) {
return promisify(cb => fs.readdir(dir, cb));
}
// Return an empty array if a directory doesnt exist (but still throw if errof if dir is a file)
export async function readdirSafe(dir: string) {
return stat(dir)
.catch(err => Promise.resolve([]))
.then(statsOrArray => {
if (statsOrArray instanceof Array) return statsOrArray;
if (!statsOrArray.isDirectory())
throw new Error(dir + ' is not a directory');
return readdir(dir);
});
}
function readCmdShim(filePath: string) {
return promisify(cb => _readCmdShim(filePath, cb));
}
function _readlink(filePath: string) {
return promisify(cb => fs.readlink(filePath, cb));
}
// Copied from:
// https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L280-L297
export async function readlink(filePath: string) {
let stat = await lstat(filePath);
let result = null;
if (stat.isSymbolicLink()) {
result = await _readlink(filePath);
} else {
try {
result = await readCmdShim(filePath);
} catch (err) {
if (err.code !== 'ENOTASHIM' && err.code !== 'EISDIR') {
throw err;
}
}
}
return result;
}
export async function dirExists(dir: string) {
try {
let _stat = await stat(dir);
return _stat.isDirectory();
} catch (err) {
return false;
}
}
export async function symlinkExists(filePath: string) {
try {
let stat = await lstat(filePath);
return stat.isSymbolicLink();
} catch (err) {
return false;
}
}
|
module.exports = IpfsUtil;
var fs = require('fs');
var formstream = require('formstream');
var http = require('http');
var request = require('request');
function IpfsUtil() {
}
IpfsUtil.prototype.init = function (config) {
this.__host = config.ipfs.host;
this.__port = config.ipfs.port;
};
IpfsUtil.prototype.getTar = function (key, toFile, callback) {
var self = this;
var uri = 'http://' + self.__host + ':' + self.__port + '/api/v0/tar/cat?arg=' + key;
console.log(uri);
request
.get(uri)
.on('end', function () {
console.log('GET request ended....');
callback();
}).on('error', function (err) {
console.log('ERROR: ', err);
return callback(err);
})
.pipe(fs.createWriteStream(toFile));
};
IpfsUtil.prototype.uploadTar = function (filePath, callback) {
var self = this;
var form = formstream();
form.file('file', filePath);
var options = {
method: 'POST',
host: self.__host,
port: self.__port,
path: '/api/v0/tar/add',
headers: form.headers()
};
console.log(options);
var req = http.request(options, function (res) {
res.on('data', function (data) {
console.log(data);
callback(null, (JSON.parse(data)).Hash);
});
//res.on('end', function () {
// console.log('Request ended...');
// callback();
//});
res.on('error', function (err) {
console.log(err);
return callback(err);
})
});
form.pipe(req);
}; |
import {observable} from 'mobx';
export default class SessionDocumentModel {
@observable id;
@observable sessionID;
@observable studentID;
@observable filename;
@observable CreatorId;
@observable archived;
constructor(value) {
this.id = id;
this.sessionID = sessionID;
this.studentID = studentID;
this.filename = filename;
this.CreatorId = CreatorId;
this.archived = archived;
}
}
|
'use babel';
//import reddit from './api/reddit';
import giphy from './api/giphy';
import ohMaGif from './api/oh-ma-gif';
import reactionGifs from './api/reaction-gifs';
const apis = [
//reddit,
giphy,
ohMaGif,
reactionGifs
];
export default function getRndThumbnail() {
const apiFn = apis[Math.floor(Math.random() * apis.length)];
return apiFn().catch(err => {
// Show error notification
atom.notifications.addError(err, {
dismissable: true
});
});
}
|
var dropzoneOverlay = document.querySelector('.dropzone-overlay');
function getDataTransferFiles(event) {
var dataTransferItemsList = [];
if (event.dataTransfer) {
var dt = event.dataTransfer;
if (dt.files && dt.files.length) {
dataTransferItemsList = dt.files;
} else if (dt.items && dt.items.length) {
// During the drag even the dataTransfer.files is null
// but Chrome implements some drag store, which is accesible via dataTransfer.items
dataTransferItemsList = dt.items;
}
} else if (event.target && event.target.files) {
dataTransferItemsList = event.target.files;
}
if (dataTransferItemsList.length > 0) {
dataTransferItemsList = [dataTransferItemsList[0]];
}
// Convert from DataTransferItemsList to the native Array
return Array.prototype.slice.call(dataTransferItemsList);
}
function showDragFocus() {
dropzoneOverlay.className = 'dropzone-overlay active';
}
function hideDragFocus() {
dropzoneOverlay.className = 'dropzone-overlay';
}
function onFileDragEnter(ev) {
ev.preventDefault();
showDragFocus();
}
function onFileDragOver(ev) {
ev.preventDefault();
}
function onFileDrop(ev) {
ev.preventDefault();
hideDragFocus();
var fileList = getDataTransferFiles(ev);
updateStickerImage(fileList[0]);
return null;
}
function onFileDragLeave(ev) {
ev.preventDefault();
console.log(ev.target)
if (ev.target !== document.body) {
return;
}
hideDragFocus();
}
function drawImage(canvas, imageBitmap) {
var ctx = canvas.getContext('2d');
ctx.drawImage(file, 0, 0);
}
function updateStickerImage(file) {
var reader = new FileReader();
reader.onload = function(ev) {
var dataURL = ev.target.result;
document.querySelectorAll('.sticker-img').forEach(function(img) {
img.style = 'background-image: url(' + dataURL + ')';
});
}
reader.readAsDataURL(file);
}
document.body.ondragenter = onFileDragEnter;
document.body.ondragover = onFileDragOver;
document.body.ondragleave = onFileDragLeave;
document.body.ondrop = onFileDrop; |
'use strict';
import React from 'react';
import { external_url_map } from "../components/globals";
/**
* Method to display either mode of inheritance with adjective,
* or just mode of inheritance if no adjective
* @param {object} object - A GDM or Interpretation object
*/
export function renderSelectedModeInheritance(object) {
let moi = '', moiAdjective = '';
if (object && object.modeInheritance) {
moi = object.modeInheritance;
if (object.modeInheritanceAdjective) {
moiAdjective = object.modeInheritanceAdjective;
}
}
return (
<span>{moi && moi.length ? renderModeInheritanceLink(moi, moiAdjective) : 'None'}</span>
);
}
/**
* Method to construct mode of inheritance linkout
*/
function renderModeInheritanceLink(modeInheritance, modeInheritanceAdjective) {
if (modeInheritance) {
let start = modeInheritance.indexOf('(');
let end = modeInheritance.indexOf(')');
let hpoNumber;
let adjective = modeInheritanceAdjective && modeInheritanceAdjective.length ? ' (' + modeInheritanceAdjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1] + ')' : '';
if (start && end) {
hpoNumber = modeInheritance.substring(start+1, end);
}
if (hpoNumber && hpoNumber.indexOf('HP:') > -1) {
let hpoLink = external_url_map['HPO'] + hpoNumber;
return (
<span><a href={hpoLink} target="_blank">{modeInheritance.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1]}</a>{adjective}</span>
);
} else {
return (
<span>{modeInheritance + adjective}</span>
);
}
}
} |
"use strict";
var echo = require('echo'),
Authorization = require('./auth.js'),
Packer = require('./packer.js'),
Request = require('./request.js'),
RequestOptions = require('./req-options.js'),
portMatch = /:(\d+)$/,
parse = function (host, port) {
var out = {
"host": "localhost",
"port": 80
},
match = portMatch.exec(host);
if (match) {
if (isNaN(port)) {
port = match[1];
}
host = host.slice(0, match.index);
}
if (host) {
out.host = host;
}
if (!isNaN(port)) {
out.port = Number(port);
}
return out;
},
secs = function (ms) {
var secs = ms / 1000;
return '(' + secs.toFixed(3) + ' sec)';
};
function Client() {
this.host = undefined;
this.port = undefined;
this.auth = undefined;
this.timeout = undefined;
this.verbose = undefined;
}
Client.prototype = {
"request": function (options, data, done, fail) {
var self = this,
auth = self.auth,
verbose = self.verbose,
target = self.toString(options),
req,
authStr;
if (auth) {
authStr = auth.toString(options);
}
req = Request.create(options, authStr);
req.on('response', function (res, options) {
var code = res.statusCode,
failed = function (msg) {
if (msg && verbose) {
echo(msg);
}
if (fail) {
fail(code, options, res);
} else {
res._dump();
}
};
if (verbose) {
echo(target, 'returned', code, secs(options.duration));
}
if (code === 401) {
if (auth) {
if (authStr) {
failed('Invalid credentials.');
} else {
auth.parse(res.headers);
res._dump();
self.request(options, data, done, fail);
}
} else {
failed('Credentials required.');
}
} else if (Math.floor(code / 100) === 2) {
if (done) {
done(res, options);
}
} else {
failed();
}
});
req.on('timeout', function (seconds) {
var sec = '(' + seconds + ' seconds)';
if (verbose) {
echo(target, 'timed out.', sec);
}
auth.clear();
if (fail) {
fail('ETIMEDOUT', options);
}
});
req.on('error', function (code, options) {
if (verbose) {
echo(target, code);
}
if (fail) {
fail(code, options);
}
});
if (verbose) {
echo(target);
}
req.send(data, self.timeout);
},
"get": function (path, done, fail) {
var options = RequestOptions.createGET(this.host, this.port, path);
this.request(options, undefined, done, fail);
},
"postEmpty": function (path, done, fail) {
var options = RequestOptions.createPOSTEmpty(this.host, this.port, path);
this.request(options, undefined, done, fail);
},
"post": function (path, mime, str, done, fail) {
var options = RequestOptions.createPOSTAs(this.host, this.port, path, mime, str);
this.request(options, str, done, fail);
},
"postString": function (path, str, done, fail) {
var options = RequestOptions.createPOSTString(this.host, this.port, path, str);
this.request(options, str, done, fail);
},
"postJSON": function (path, json, done, fail) {
var data = JSON.stringify(json),
options = RequestOptions.createPOSTJSON(this.host, this.port, path, data);
this.request(options, data, done, fail);
},
"postXML": function (path, xml, done, fail) {
var data = Packer.packXML(xml),
options = RequestOptions.createPOSTXML(this.host, this.port, path, data);
this.request(options, data, done, fail);
},
"toString": function (options) {
var host = this.host + ':' + this.port,
str = options.method + ' ' + host + options.path,
max = 60;
if (str.length > max) {
return str.slice(0, max) + '...';
}
return str;
}
};
module.exports = {
"create": function (info) {
var client = new Client(),
parsed;
if (!info) {
info = {};
}
parsed = parse(info.host, info.port);
client.host = parsed.host;
client.port = parsed.port;
if (info.user) {
client.auth = Authorization.create(info.user, info.pass);
}
client.timeout = info.timeout || 180;
client.verbose = info.verbose;
return client;
}
};
|
var searchData=
[
['database',['Database',['../namespace_pontikis_1_1_database.html',1,'Pontikis']]],
['pg_5fsequence_5fname_5fauto',['PG_SEQUENCE_NAME_AUTO',['../class_pontikis_1_1_database_1_1_dacapo.html#aef46219ed4c7133e99979e0d3aa5cd86',1,'Pontikis::Database::Dacapo']]],
['pontikis',['Pontikis',['../namespace_pontikis.html',1,'']]],
['prepared_5fstatements_5fnumbered',['PREPARED_STATEMENTS_NUMBERED',['../class_pontikis_1_1_database_1_1_dacapo.html#a963df8efcdd80ba37064e3cde0c8809a',1,'Pontikis::Database::Dacapo']]],
['prepared_5fstatements_5fquestion_5fmark',['PREPARED_STATEMENTS_QUESTION_MARK',['../class_pontikis_1_1_database_1_1_dacapo.html#a63dd2d4d612585c42c7e53e9b66caf24',1,'Pontikis::Database::Dacapo']]]
];
|
import test from 'ava';
import debounce from 'lodash.debounce';
import webpack from 'webpack';
import 'babel-core/register';
import helper from './_helper';
import expected from './basic/expected.json';
test.beforeEach(t => {
const config = helper.getSuiteConfig('basic');
t.context.config = config
t.context.extractOpts = helper.getExtractOptions(config);
t.end();
})
test('basic', t => {
t.plan(1);
const callback = (err, stats) => {
err = err || (stats.hasErrors() ? new Error(stats.toString()) : null)
if (err) { t.fail(err); t.end(); }
setTimeout(() => {
const output = require(t.context.extractOpts.outputFile);
t.same(output, expected);
t.end();
}, t.context.extractOpts.writeDebounceMs);
}
webpack(t.context.config, callback);
})
test('basic (onOutput)', t => {
t.plan(1);
const onOutput = debounce((filename, blob, total) => {
t.same(total, expected);
t.end();
}, t.context.extractOpts.writeDebounceMs);
const config = Object.assign({}, t.context.config, {
extractCssModuleClassnames: { onOutput }
});
const callback = (err, stats) => {
err = err || (stats.hasErrors() ? new Error(stats.toString()) : null)
if (err) { t.fail(err); t.end(); }
}
webpack(config, callback);
});
|
/**
* 对Storage的封装
* Author : smohan
* Website : https://smohan.net
* Date: 2017/10/12
* 参数1:布尔值, true : sessionStorage, 无论get,delete,set都得申明
* 参数1:string key 名
* 参数2:null,用作删除,其他用作设置
* 参数3:string,用于设置键名前缀
* 如果是sessionStorage,即参数1是个布尔值,且为true,
* 无论设置/删除/获取都应该指明,而localStorage无需指明
*/
const MEMORY_CACHE = Object.create(null)
export default function () {
let isSession = false,
name, value, prefix
let args = arguments
if (typeof args[0] === 'boolean') {
isSession = args[0]
args = [].slice.call(args, 1)
}
name = args[0]
value = args[1]
prefix = args[2] === undefined ? '_mo_data_' : args[2]
const Storage = isSession ? window.sessionStorage : window.localStorage
if (!name || typeof name !== 'string') {
throw new Error('name must be a string')
}
let cacheKey = (prefix && typeof prefix === 'string') ? (prefix + name) : name
if (value === null) { //remove
delete MEMORY_CACHE[cacheKey]
return Storage.removeItem(cacheKey)
} else if (!value && value !== 0) { //get
if (MEMORY_CACHE[cacheKey]) {
return MEMORY_CACHE[cacheKey]
}
let _value = undefined
try {
_value = JSON.parse(Storage.getItem(cacheKey))
} catch (e) {}
return _value
} else { //set
MEMORY_CACHE[cacheKey] = value
return Storage.setItem(cacheKey, JSON.stringify(value))
}
}
|
/*
*
* UI reducer
*
*/
import { fromJS } from 'immutable';
import {
SET_PRODUCT_QUANTITY_SELECTOR,
} from './constants';
const initialState = fromJS({
product: {
quantitySelected: 1,
},
});
function uiReducer(state = initialState, action) {
switch (action.type) {
case SET_PRODUCT_QUANTITY_SELECTOR:
return state.setIn(['product', 'quantitySelected'], action.quantity);
default:
return state;
}
}
export default uiReducer;
|
var async = require('async');
var settings = require('../settings/settings.js');
var Post = require('../models/post.js');
var List = require('../models/list.js');
module.exports = function(app){
app.get('/getArchive',function(req,res,next){
if(req.sessionID){
var list = new List({
pageIndex:1,
pageSize:settings.pageSize,
queryObj:{}
});
list.getArchive(function(err,archiveArray){
if(!(err)&&archiveArray){
res.json(archiveArray);
res.end();
}else{
res.json({status:404,message:''});
res.end();
}
});
}else{
res.end();
}
});
app.get('/getPageCount',function(req,res,next){
if(req.sessionID){
var list = new List({
pageIndex:1,
pageSize:settings.pageSize,
queryObj:{}
});
list.getCount(function(err,count){
if(!(err)&&(count!=0)){
res.json(Math.ceil(count/settings.pageSize));
res.end();
}else{
res.json({status:404,message:''});
res.end();
}
});
}else{
res.end();
}
});
app.get('/',function(req,res,next){
if(req.sessionID){
var list = new List({
pageIndex:1,
pageSize:settings.pageSize,
queryObj:{}
});
list.getList(function(err,docs){
if(!(err)&&docs){
res.json(docs);
res.end();
}else{
res.json({status:404,message:''});
res.end();
}
});
}else{
res.end();
}
});
} |
module('Item');
test('.setOptions()', function() {
var item = new Item({
name: 'Name',
category: 'Category',
icon: 'Icon',
value: 'Value',
flavor: 'Flavor',
rarity: 'Rare',
});
item.code = 'Code';
equal(item.getName(),'Name');
equal(item.getCategory(),'Category');
equal(item.getIcon(),'Icon');
equal(item.getValue(),'Value');
equal(item.getFlavor(),'Flavor');
equal(item.getRarity(),'Rare');
equal(item.getCode(),'Code');
equal(item.isEquipment(),false);
});
test('Rarity Classes', function() {
var item = Factories.buildItem({});
equal(item.getRarity(),'Common');
equal(item.getClassName(),'highlight-item-common');
item.rarity = 'Uncommon';
equal(item.getClassName(),'highlight-item-uncommon');
item.rarity = 'Rare';
equal(item.getClassName(),'highlight-item-rare');
item.rarity = 'Epic';
equal(item.getClassName(),'highlight-item-epic');
});
|
(function (angular) {
// Create all modules and define dependencies to make sure they exist
// and are loaded in the correct order to satisfy dependency injection
// before all nested files are concatenated by Gulp
// Config
angular
.module('jackalMqtt.config', [])
.value('jackalMqtt.config', {
debug: true
});
// Modules
angular
.module('jackalMqtt.services', []);
angular
.module('jackalMqtt', [
'jackalMqtt.config',
'jackalMqtt.services'
]);
})(angular);
angular
.module('jackalMqtt.services')
.factory('mqttService', MqttService)
.factory('dataService', DataService);
DataService.$inject = [ ];
function DataService () {
var service = {
data: { }
};
return service;
}
MqttService.$inject = ['$rootScope', 'dataService'];
function MqttService ($rootScope, dataService) {
var mqttc;
var Paho = Paho;
var callbacks = { };
function addCallback(chanel, callbackName, dataName) {
callbacks[chanel] = [callbackName, dataName];
}
function deleteCallback(chanel){
delete callbacks[chanel];
}
function chanelMatch(chanel, destination) {
var reg = '^';
destination += '/';
var levels = chanel.split('/');
for (var ind = 0; ind < levels.length; ind++){
var lvl = levels[ind];
if(lvl === '+'){
reg = '([a-z]|[0-9])+/';
}else if(lvl === '#'){
reg += '(([a-z]|[0-9])|/)*';
}else{
reg += (lvl + '/');
}
}
reg += '$';
reg = new RegExp(reg);
if(reg.test(destination)){
return true;
}
return false;
}
function onConnect() {
$rootScope.$broadcast('connected');
}
function onConnectionLost(responseObject) {
if(responseObject.errorCode !== 0){
$rootScope.$broadcast('connectionLost');
}
}
function onMessageArrived(message) {
var payload = message.payloadString;
var destination = message.destinationName;
for(var key in callbacks) {
if(callbacks.hasOwnProperty(key)) {
var match = chanelMatch(key, destination);
if(match) {
dataService.data[callbacks[key][1]] = payload;
$rootScope.$broadcast(callbacks[key][0]);
}
}
}
}
function connect(host, port, options) {
mqttc = new Paho.MQTT.Client(host, Number(port), 'web_client_' + Math.round(Math.random() * 1000));
mqttc.onConnectionLost = onConnectionLost;
mqttc.onMessageArrived = onMessageArrived;
options['onSuccess'] = onConnect;
mqttc.connect(options);
}
function disconnect() {
mqttc.disconnect();
}
function subscribe(chanel, callbackName, dataName) {
mqttc.subscribe(chanel);
addCallback(chanel, callbackName, dataName);
}
function unsubscribe(chanel) {
mqttc.unsubscribe(chanel);
deleteCallback(chanel);
}
function publish(chanel, message, retained) {
var payload = JSON.stringify(message);
var mqttMessage = new Paho.MQTT.Message(payload);
mqttMessage.retained = retained;
mqttMessage.detinationName = chanel;
mqttc.send(mqttMessage);
}
return {
connect: connect,
disconnect: disconnect,
subscribe: subscribe,
unsubscribe: unsubscribe,
publish: publish,
/** TEST CODE **/
_addCallback: addCallback,
_deleteCallback: deleteCallback,
_chanelMatch: chanelMatch,
_callbacks: callbacks
/** TEST CODE **/
};
}
|
import TheWalletView from '@/views/TheWalletView';
import Dashboard from '@/views/layouts-wallet/TheDashboardLayout';
import Send from '@/views/layouts-wallet/TheSendTransactionLayout';
import NftManager from '@/views/layouts-wallet/TheNFTManagerLayout';
import Swap from '@/views/layouts-wallet/TheSwapLayout';
import InteractContract from '@/views/layouts-wallet/TheInteractContractLayout';
import DeployContract from '@/views/layouts-wallet/TheDeployContractLayout';
import SignMessage from '@/views/layouts-wallet/TheSignMessageLayout';
import VerifyMessage from '@/views/layouts-wallet/TheVerifyMessageLayout';
import Dapps from '@/views/layouts-wallet/TheDappCenterLayout.vue';
import DappRoutes from '@/dapps/routes-dapps.js';
import Settings from '@/modules/settings/ModuleSettings';
import NftManagerSend from '@/modules/nft-manager/components/NftManagerSend';
// import Notifications from '@/modules/notifications/ModuleNotifications';
import Network from '@/modules/network/ModuleNetwork';
import { swapProps, swapRouterGuard } from './helpers';
import { ROUTES_WALLET } from '../configs/configRoutes';
export default {
path: '/wallet',
component: TheWalletView,
props: true,
children: [
{
path: ROUTES_WALLET.WALLETS.PATH,
name: ROUTES_WALLET.WALLETS.NAME,
component: Dashboard,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.DASHBOARD.PATH,
name: ROUTES_WALLET.DASHBOARD.NAME,
component: Dashboard,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.SETTINGS.PATH,
name: ROUTES_WALLET.SETTINGS.NAME,
component: Settings,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.SEND_TX.PATH,
name: ROUTES_WALLET.SEND_TX.NAME,
component: Send,
props: true,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.NFT_MANAGER.PATH,
name: ROUTES_WALLET.NFT_MANAGER.NAME,
component: NftManager,
children: [
{
path: ROUTES_WALLET.NFT_MANAGER_SEND.PATH,
name: ROUTES_WALLET.NFT_MANAGER_SEND.NAME,
component: NftManagerSend,
meta: {
noAuth: false
}
}
],
meta: {
noAuth: false
}
},
// {
// path: ROUTES_WALLET.NOTIFICATIONS.PATH,
// name: ROUTES_WALLET.NOTIFICATIONS.NAME,
// component: Notifications,
// meta: {
// noAuth: false
// }
// },
{
path: ROUTES_WALLET.NETWORK.PATH,
name: ROUTES_WALLET.NETWORK.NAME,
component: Network,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.SWAP.PATH,
name: ROUTES_WALLET.SWAP.NAME,
component: Swap,
props: swapProps,
beforeEnter: swapRouterGuard,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.DAPPS.PATH,
component: Dapps,
children: DappRoutes,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.DEPLOY_CONTRACT.PATH,
name: ROUTES_WALLET.DEPLOY_CONTRACT.NAME,
component: DeployContract,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.INTERACT_WITH_CONTRACT.PATH,
name: ROUTES_WALLET.INTERACT_WITH_CONTRACT.NAME,
component: InteractContract,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.SIGN_MESSAGE.PATH,
name: ROUTES_WALLET.SIGN_MESSAGE.NAME,
component: SignMessage,
meta: {
noAuth: false
}
},
{
path: ROUTES_WALLET.VERIFY_MESSAGE.PATH,
name: ROUTES_WALLET.VERIFY_MESSAGE.NAME,
component: VerifyMessage,
meta: {
noAuth: false
}
}
]
};
|
/**
* Created by ozgur on 24.07.2017.
*/
var assert = require('assert');
var fs = require("fs");
var path = require("path");
var LineCounter = require("../lib/LineCounter");
var ExtensionsFactory = require("../lib/Extensions");
var Rules = require("../lib/Rules");
describe("LineCounter", function(){
before(function(){
var dir = __dirname;
fs.mkdirSync(path.join(dir, "dir"));
fs.mkdirSync(path.join(dir, "dir", "dir2"));
fs.mkdirSync(path.join(dir, "dir", "dir3"));
fs.writeFileSync(path.join(dir, "dir", "file1.java"), "line1\nline2");
fs.writeFileSync(path.join(dir, "dir", "file1.js"), "line1\nline2\nline3");
fs.writeFileSync(path.join(dir, "dir", "dir2", "file3.php"), "line1\nline2");
fs.writeFileSync(path.join(dir, "dir", "dir2", "file4.swift"), "line1\nline2");
fs.writeFileSync(path.join(dir, "dir", "dir3", "file5.java"), "line1\nline2");
fs.writeFileSync(path.join(dir, "dir", "dir3", "file6.js"), "line1\nline2");
});
describe("#resolveTargetFiles()", function(){
it("should return allowed extensions", function(){
var lc = new LineCounter();
lc.setPath(path.join(__dirname, "dir"));
lc.setExtensions(ExtensionsFactory.from("js"));
var result = lc.resolveTargetFiles();
var expected = [ path.join(__dirname, "dir", "dir3", "file6.js"), path.join(__dirname, "dir", "file1.js") ];
for( var i = 0; i < expected.length; i++ ){
assert.equal(expected[i], result[i].getPath());
}
});
it("should return all except disallowed ones", function(){
var lc = new LineCounter();
lc.setPath(path.join(__dirname, "dir"));
lc.setExtensions(ExtensionsFactory.except("java, swift, php"));
var result = lc.resolveTargetFiles();
var expected = [ path.join(__dirname, "dir", "dir3", "file6.js"), path.join(__dirname, "dir", "file1.js") ];
for( var i = 0; i < expected.length; i++ ){
assert.equal(expected[i], result[i].getPath());
}
});
it("should return all", function(){
var lc = new LineCounter();
lc.setPath(path.join(__dirname, "dir"));
var result = lc.resolveTargetFiles();
var expected = [ path.join(__dirname, "dir", "dir2", "file3.php"), path.join(__dirname, "dir", "dir2", "file4.swift"),
path.join(__dirname, "dir", "dir3", "file5.java"), path.join(__dirname, "dir", "dir3", "file6.js"),
path.join(__dirname, "dir", "file1.java"), path.join(__dirname, "dir", "file1.js")];
for( var i = 0; i < expected.length; i++ ){
assert.equal(expected[i], result[i].getPath());
}
});
});
describe("#getLines()", function(){
it("should count all files correctly", function(done){
var lc = new LineCounter();
lc.setPath(path.join(__dirname, "dir"));
lc.getLines(function(result){
assert.equal(6, result.files);
assert.equal(13, result.lines);
done();
});
});
it("should count only js files", function(done){
var lc = new LineCounter();
lc.setPath(path.join(__dirname, "dir"));
lc.setExtensions(ExtensionsFactory.from("js"));
lc.getLines(function(result){
assert.equal(2, result.files);
assert.equal(5, result.lines);
done();
});
});
});
describe("#addRule()", function(){
it("should return only the files starts with file1", function(){
var lc = new LineCounter();
lc.setPath(path.join(__dirname, "dir"));
lc.addRule(Rules.filePrefix, "file1");
var result = lc.resolveTargetFiles();
var expected = [ path.join(__dirname, "dir", "file1.java"), path.join(__dirname, "dir", "file1.js") ];
for( var i = 0; i < expected.length; i++ ){
assert.equal(expected[i], result[i].getPath());
}
});
it("should ignore dir2 and dir3 directories", function(){
var lc = new LineCounter();
lc.setPath(path.join(__dirname, "dir"));
lc.addRule(Rules.ignoreDir, "dir2");
lc.addRule(Rules.ignoreDir, "dir3");
var result = lc.resolveTargetFiles();
var expected = [ path.join(__dirname, "dir", "file1.java"), path.join(__dirname, "dir", "file1.js") ];
for( var i = 0; i < expected.length; i++ ){
assert.equal(expected[i], result[i].getPath());
}
});
});
after(function(){
var dir = __dirname;
fs.unlinkSync(path.join(dir, "dir", "dir3", "file6.js"));
fs.unlinkSync(path.join(dir, "dir", "dir3", "file5.java"));
fs.unlinkSync(path.join(dir, "dir", "dir2", "file4.swift"));
fs.unlinkSync(path.join(dir, "dir", "dir2", "file3.php"));
fs.unlinkSync(path.join(dir, "dir", "file1.js"));
fs.unlinkSync(path.join(dir, "dir", "file1.java"));
fs.rmdirSync(path.join(dir, "dir", "dir2"));
fs.rmdirSync(path.join(dir, "dir", "dir3"));
fs.rmdirSync(path.join(dir, "dir"));
});
}); |
define(['./Suite','./SuiteView','./Spy', './Verify'],function (Suite,SuiteView,Spy,Verify) {
var itchCork = {
Suite: Suite,
suiteView: new SuiteView(),
Spy: Spy,
Verify: Verify
};
itchCork.Suite.prototype.linkView(itchCork.suiteView);
window._bTestResults = {};
return itchCork;
});
|
!function r(e,n,t){function i(u,f){if(!n[u]){if(!e[u]){var a="function"==typeof require&&require;if(!f&&a)return a(u,!0);if(o)return o(u,!0);var c=new Error("Cannot find module '"+u+"'");throw c.code="MODULE_NOT_FOUND",c}var s=n[u]={exports:{}};e[u][0].call(s.exports,function(r){var n=e[u][1][r];return i(n||r)},s,s.exports,r,e,n,t)}return n[u].exports}for(var o="function"==typeof require&&require,u=0;u<t.length;u++)i(t[u]);return i}({1:[function(r,e,n){!function(){"use strict";Object.rearmed.add({hasKey:function(r){var e=!1;for(var n in this)if(n===r){e=!0;break}return e}})}()},{}]},{},[1]); |
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const chai = require('chai');
const dirtyChai = require('dirty-chai');
const should = chai.Should;
should();
chai.use(dirtyChai);
chai.use(sinonChai);
const index = require('./../src/index.js');
const error = new Error('should not be called');
describe('node-vault', () => {
describe('module', () => {
it('should export a function that returns a new client', () => {
const v = index();
index.should.be.a('function');
v.should.be.an('object');
});
});
describe('client', () => {
let request = null;
let response = null;
let vault = null;
// helper
function getURI(path) {
return [vault.endpoint, vault.apiVersion, path].join('/');
}
function assertRequest(thisRequest, params, done) {
return () => {
thisRequest.should.have.calledOnce();
thisRequest.calledWithMatch(params).should.be.ok();
return done();
};
}
beforeEach(() => {
// stub requests
request = sinon.stub();
response = sinon.stub();
response.statusCode = 200;
request.returns({
then(fn) {
return fn(response);
},
catch(fn) {
return fn();
},
});
vault = index(
{
endpoint: 'http://localhost:8200',
token: '123',
'request-promise': request, // dependency injection of stub
}
);
});
describe('help(path, options)', () => {
it('should response help text for any path', done => {
const path = 'sys/policy';
const params = {
method: 'GET',
uri: `${getURI(path)}?help=1`,
};
vault.help(path)
.then(assertRequest(request, params, done))
.catch(done);
});
it('should handle undefined options', done => {
const path = 'sys/policy';
const params = {
method: 'GET',
uri: `${getURI(path)}?help=1`,
};
vault.help(path)
.then(assertRequest(request, params, done))
.catch(done);
});
});
describe('list(path, requestOptions)', () => {
it('should list entries at the specific path', done => {
const path = 'secret/hello';
const params = {
method: 'LIST',
uri: getURI(path),
};
vault.list(path)
.then(assertRequest(request, params, done))
.catch(done);
});
});
describe('write(path, data, options)', () => {
it('should write data to path', done => {
const path = 'secret/hello';
const data = {
value: 'world',
};
const params = {
method: 'PUT',
uri: getURI(path),
};
vault.write(path, data)
.then(assertRequest(request, params, done))
.catch(done);
});
it('should handle undefined options', done => {
const path = 'secret/hello';
const data = {
value: 'world',
};
const params = {
method: 'PUT',
uri: getURI(path),
};
vault.write(path, data)
.then(assertRequest(request, params, done))
.catch(done);
});
});
describe('read(path, options)', () => {
it('should read data from path', done => {
const path = 'secret/hello';
const params = {
method: 'GET',
uri: getURI(path),
};
vault.read(path)
.then(assertRequest(request, params, done))
.catch(done);
});
it('should handle undefined options', done => {
const path = 'secret/hello';
const params = {
method: 'GET',
uri: getURI(path),
};
vault.read(path)
.then(assertRequest(request, params, done))
.catch(done);
});
});
describe('delete(path, options)', () => {
it('should delete data from path', done => {
const path = 'secret/hello';
const params = {
method: 'DELETE',
uri: getURI(path),
};
vault.delete(path)
.then(assertRequest(request, params, done))
.catch(done);
});
it('should handle undefined options', done => {
const path = 'secret/hello';
const params = {
method: 'DELETE',
uri: getURI(path),
};
vault.delete(path)
.then(assertRequest(request, params, done))
.catch(done);
});
});
describe('handleVaultResponse(response)', () => {
it('should return a function that handles errors from vault server', () => {
const fn = vault.handleVaultResponse;
fn.should.be.a('function');
});
it('should return a Promise with the body if successful', done => {
const data = { hello: 1 };
response.body = data;
const promise = vault.handleVaultResponse(response);
promise.then(body => {
body.should.equal(data);
return done();
});
});
it('should return a Promise with the error if failed', done => {
response.statusCode = 500;
response.body = {
errors: ['Something went wrong.'],
};
response.request = {
path: 'test',
};
const promise = vault.handleVaultResponse(response);
promise.catch(err => {
err.message.should.equal(response.body.errors[0]);
return done();
});
});
it('should return the status code if no error in the response', done => {
response.statusCode = 500;
response.request = {
path: 'test',
};
const promise = vault.handleVaultResponse(response);
promise.catch(err => {
err.message.should.equal(`Status ${response.statusCode}`);
return done();
});
});
it('should not handle response from health route as error', done => {
const data = {
initialized: true,
sealed: true,
standby: true,
server_time_utc: 1474301338,
version: 'Vault v0.6.1',
};
response.statusCode = 503;
response.body = data;
response.request = {
path: '/v1/sys/health',
};
const promise = vault.handleVaultResponse(response);
promise.then(body => {
body.should.equal(data);
return done();
});
});
it('should return error if error on request path with health and not sys/health', done => {
response.statusCode = 404;
response.body = {
errors: [],
};
response.request = {
path: '/v1/sys/policies/applications/im-not-sys-health/app',
};
vault.handleVaultResponse(response)
.then(() => done(error))
.catch(err => {
err.message.should.equal(`Status ${response.statusCode}`);
return done();
});
});
it('should return a Promise with the error if no response is passed', done => {
const promise = vault.handleVaultResponse();
promise.catch((err) => {
err.message.should.equal('No response passed');
return done();
});
});
});
describe('generateFunction(name, config)', () => {
const config = {
method: 'GET',
path: '/myroute',
};
const configWithSchema = {
method: 'GET',
path: '/myroute',
schema: {
req: {
type: 'object',
properties: {
testProperty: {
type: 'integer',
minimum: 1,
},
},
required: ['testProperty'],
},
},
};
const configWithQuerySchema = {
method: 'GET',
path: '/myroute',
schema: {
query: {
type: 'object',
properties: {
testParam1: {
type: 'integer',
minimum: 1,
},
testParam2: {
type: 'string',
},
},
required: ['testParam1', 'testParam2'],
},
},
};
it('should generate a function with name as defined in config', () => {
const name = 'myGeneratedFunction';
vault.generateFunction(name, config);
vault.should.have.property(name);
const fn = vault[name];
fn.should.be.a('function');
});
describe('generated function', () => {
it('should return a promise', done => {
const name = 'myGeneratedFunction';
vault.generateFunction(name, config);
const fn = vault[name];
const promise = fn();
request.calledOnce.should.be.ok();
/* eslint no-unused-expressions: 0*/
promise.should.be.promise;
promise.then(done)
.catch(done);
});
it('should handle config with schema property', done => {
const name = 'myGeneratedFunction';
vault.generateFunction(name, configWithSchema);
const fn = vault[name];
const promise = fn({ testProperty: 3 });
promise.then(done).catch(done);
});
it('should handle invalid arguments via schema property', done => {
const name = 'myGeneratedFunction';
vault.generateFunction(name, configWithSchema);
const fn = vault[name];
const promise = fn({ testProperty: 'wrong data type here' });
promise.catch(err => {
err.message.should.equal('Invalid type: string (expected integer)');
return done();
});
});
it('should handle schema with query property', done => {
const name = 'myGeneratedFunction';
vault.generateFunction(name, configWithQuerySchema);
const fn = vault[name];
const promise = fn({ testParam1: 3, testParam2: 'hello' });
const options = {
path: '/myroute?testParam1=3&testParam2=hello',
};
promise
.then(() => {
request.calledWithMatch(options).should.be.ok();
done();
})
.catch(done);
});
});
});
describe('request(options)', () => {
it('should reject if options are undefined', done => {
vault.request()
.then(() => done(error))
.catch(() => done());
});
it('should handle undefined path in options', done => {
const promise = vault.request({
method: 'GET',
});
promise.catch(err => {
err.message.should.equal('Missing required property: path');
return done();
});
});
it('should handle undefined method in options', done => {
const promise = vault.request({
path: '/',
});
promise.catch(err => {
err.message.should.equal('Missing required property: method');
return done();
});
});
});
});
});
|
'use strict';
function A() {
this._va = 0;
console.log('A');
}
A.prototype = {
va: 1,
fa: function() {
console.log('A->fa()');
}
};
function B() {
this._vb = 0;
console.log('B');
}
B.prototype = {
vb: 1,
fb: function() {
console.log('B->fb()');
}
};
function C() {
this._vc = 0;
console.log('C');
}
C.prototype = {
vc: 1,
fc: function() {
console.log('C->fc()');
}
};
function D(){
this._vd = 0;
console.log('D');
}
D.prototype = {
vd: 1,
fd: function() {
this.fa();
this.fb();
this.fc();
console.log('D->fd()');
}
};
var mixin = require('../mixin');
D = mixin(D, A);
D = mixin(D, B);
D = mixin(D, C);
var d = new D();
console.log(d);
console.log(d.constructor.name);
d.fd();
var a = new A();
console.log(a);
console.log(a.__proto__);
console.log(a.va);
|
export { default } from 'ember-transformer/transforms/array'; |
$( document ).ready( function() {
/**
*
* strict mode
*
*/
'use strict';
/**
*
* global variables
*
*/
var windowWidth = 0;
var windowHeight = 0;
/**
*
* actions after window load
*
*/
$( window ).load( function() {
/**
*
* window width
*
*/
windowWidth = $( window ).width();
/**
*
* window height
*
*/
windowHeight = $( window ).height();
/**
*
* configure agents slider
*
*/
$.martanianConfigureAgentsSlider();
/**
*
* configure value slider
*
*/
$.martanianConfigureValueSlider();
/**
*
* manage images
*
*/
$.martanianManageImages();
/**
*
* configure image slider
*
*/
$.martanianConfigureImageSlider();
/**
*
* configure insurance slider
*
*/
$.martanianConfigureInsuranceSlider();
/**
*
* heading slider
*
*/
$.martanianHeadingSlider();
/**
*
* references
*
*/
$.martanianManageReferences();
/**
*
* numbers highlighter
*
*/
$.martanianNumbersHighlighter();
/**
*
* autoloaded progress bars
*
*/
$.martanianProgressBarsAutoload();
/**
*
* configure tabs section
*
*/
$.martanianConfigureTabsSection();
/**
*
* set parallax
*
*/
$.martanianSetParallax();
/**
*
* load google map, if exists
*
*/
var elementA = $( '#google-map' );
if( typeof elementA[0] != 'undefined' && elementA[0] != '' ) {
$.martanianGoogleMapInit();
};
/**
*
* load bigger google map, if exists
*
*/
var elementB = $( '#google-map-full' );
if( typeof elementB[0] != 'undefined' && elementB[0] != '' ) {
$.martanianGoogleBigMapInit();
};
/**
*
* delete loader
*
*/
$( '#loader' ).animate({ 'opacity': 0 }, 300 );
setTimeout( function() {
$( '#loader' ).remove();
}, 600 );
/**
*
* end of actions
*
*/
});
/**
*
* actions after window resize
*
*/
$( window ).resize( function() {
/**
*
* window width
*
*/
windowWidth = $( window ).width();
/**
*
* window height
*
*/
windowHeight = $( window ).height();
/**
*
* manage images
*
*/
$.martanianManageImages();
/**
*
* manage references
*
*/
$.martanianManageReferences();
/**
*
* configure tabs section
*
*/
$.martanianResizeTabsSection();
/**
*
* resize manager
*
*/
$.martanianResizeManager();
/**
*
* set parallax
*
*/
$.martanianSetParallax();
/**
*
* show menu, if hidden
*
*/
if( windowWidth > 932 ) {
$( 'header .menu' ).show();
$( 'header .menu' ).find( 'ul.submenu' ).addClass( 'animated' );
}
else {
$( 'header .menu' ).hide();
$( 'header .menu' ).find( 'ul.submenu' ).removeClass( 'animated' );
}
/**
*
* end of actions
*
*/
});
/**
*
* initialize google map function
*
*/
$.martanianGoogleMapInit = function() {
var lat = $( '#google-map' ).data( 'lat' );
var lng = $( '#google-map' ).data( 'lng' );
var zoom_level = $( '#google-map' ).data( 'zoom-level' );
var map_center = new google.maps.LatLng( lat, lng );
var mapOptions = {
zoom: zoom_level,
center: map_center,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map( document.getElementById( 'google-map' ), mapOptions );
var beachMarker = new google.maps.Marker({
position: new google.maps.LatLng( lat, lng ),
map: map,
});
};
/**
*
* initialize biggest google map function
*
*/
$.martanianGoogleBigMapInit = function() {
var lat = $( '#google-map-full' ).data( 'lat' );
var lng = $( '#google-map-full' ).data( 'lng' );
var zoom_level = $( '#google-map-full' ).data( 'zoom-level' );
var map_center = new google.maps.LatLng( lat, lng );
var mapOptions = {
zoom: zoom_level,
center: map_center,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map( document.getElementById( 'google-map-full' ), mapOptions );
var beachMarker = new google.maps.Marker({
position: new google.maps.LatLng( lat, lng ),
map: map,
});
};
/**
*
* show contact form popup
*
*/
$.martanianShowContactPopup = function() {
var mode = windowWidth > 932 && windowHeight > 670 ? 'fixed' : 'absolute';
$( '#contact-popup #contact-popup-background' ).fadeIn( 300 );
if( mode == 'absolute' ) $( 'html, body' ).animate({ 'scrollTop': '0' }, 300 );
setTimeout( function() {
if( mode == 'fixed' ) $( '#contact-popup #contact-popup-content' ).addClass( 'bounceInDown' ).css({ 'top': '50%', 'position': 'fixed' });
else $( '#contact-popup #contact-popup-content' ).addClass( 'bounceInDown' ).css({ 'top': '50px', 'marginTop': '0px', 'position': 'absolute' });
}, 300 );
};
/**
*
* hide contact form popup
*
*/
$.martanianHideContactPopup = function() {
$( '#contact-popup #contact-popup-content' ).removeClass( 'bounceInDown' ).addClass( 'bounceOutUp' );
setTimeout( function() {
$( '#contact-popup #contact-popup-background' ).fadeOut( 300 );
$( '#contact-popup #contact-popup-content' ).css({ 'top': '-10000px' }).removeClass( 'bounceOutUp' );
}, 300 );
};
/**
*
* hooks to show contact form popup
*
*/
$( '*[data-action="show-contact-popup"]' ).click( function() {
$.martanianShowContactPopup();
});
/**
*
* hooks to hide contact form popup
*
*/
$( '#contact-popup-close' ).click( function() {
$.martanianHideContactPopup();
});
/**
*
* show quote form popup
*
*/
$.martanianShowQuotePopup = function( type ) {
var mode = windowWidth > 932 && windowHeight > 670 ? 'fixed' : 'absolute';
var selectedQuoteForm = $( '#quote-popup #quote-popup-content .quote-form[data-quote-form-for="'+ type +'"]' );
$( '#quote-popup #quote-popup-background' ).fadeIn( 300 );
$( '#quote-popup #quote-popup-content #quote-popup-tabs li[data-quote-tab-for="'+ type +'"]' ).addClass( 'active' );
if( mode == 'absolute' ) $( 'html, body' ).animate({ 'scrollTop': '0' }, 300 );
selectedQuoteForm.show();
setTimeout( function() {
if( mode == 'fixed' ) {
selectedQuoteForm.children( '.quote-form-background' ).css({ 'height': selectedQuoteForm.height() });
$( '#quote-popup #quote-popup-content' ).addClass( 'bounceInDown' ).css({ 'top': '50%', 'marginTop': - ( selectedQuoteForm.height() / 2 ), 'height': selectedQuoteForm.height(), 'position': 'fixed' });
}
else if( mode == 'absolute' ) {
if( windowWidth > 932 ) {
$( '#quote-popup #quote-popup-content' ).addClass( 'bounceInDown' ).css({ 'top': '50px', 'marginTop': '0px', 'height': selectedQuoteForm.height(), 'position': 'absolute' });
selectedQuoteForm.children( '.quote-form-background' ).css({ 'height': selectedQuoteForm.height() });
}
else {
if( windowWidth > 582 ) $( '#quote-popup #quote-popup-content' ).addClass( 'bounceInDown' ).css({ 'top': '50px', 'marginTop': '0px', 'height': selectedQuoteForm.height(), 'position': 'absolute' });
else {
$( '#quote-popup #quote-popup-content' ).addClass( 'bounceInDown' ).css({ 'top': '50px', 'marginTop': '0px', 'height': selectedQuoteForm.height() + $( '#quote-popup-tabs' ).height() + 50, 'position': 'absolute' });
}
}
}
}, 300 );
};
/**
*
* hide quote form popup
*
*/
$.martanianHideQuotePopup = function() {
$( '#quote-popup #quote-popup-content' ).removeClass( 'bounceInDown' ).addClass( 'bounceOutUp' );
setTimeout( function() {
$( '#quote-popup #quote-popup-background' ).fadeOut( 300 );
$( '#quote-popup #quote-popup-content' ).css({ 'top': '-10000px' }).removeClass( 'bounceOutUp' );
$( '#quote-popup #quote-popup-content .quote-form' ).hide();
$( '#quote-popup #quote-popup-content #quote-popup-tabs li' ).removeClass( 'active' );
}, 300 );
};
/**
*
* change quote form in popup
*
*/
$( '#quote-popup-tabs li' ).click( function() {
if( !$( this ).hasClass( 'active' ) ) {
var type = $( this ).data( 'quote-tab-for' );
var mode = windowWidth > 932 && windowHeight > 670 ? 'fixed' : 'absolute';
var newQuoteForm = $( '#quote-popup #quote-popup-content .quote-form[data-quote-form-for="'+ type +'"]' );
$( '#quote-popup #quote-popup-content #quote-popup-tabs li' ).removeClass( 'active' );
$( this ).addClass( 'active' );
$( '#quote-popup #quote-popup-content .quote-form' ).fadeOut( 300 );
if( mode == 'fixed' || windowWidth > 932 ) newQuoteForm.children( '.quote-form-background' ).animate({ 'height': newQuoteForm.height() }, 300 );
setTimeout( function() {
$( '#quote-popup #quote-popup-content .quote-form' ).hide();
newQuoteForm.fadeIn( 300 );
if( mode == 'fixed' ) $( '#quote-popup #quote-popup-content' ).animate({ 'height': newQuoteForm.height(), 'marginTop': - ( newQuoteForm.height() / 2 ) }, 300 );
else {
if( windowWidth > 582 ) $( '#quote-popup #quote-popup-content' ).animate({ 'height': newQuoteForm.height() }, 300 );
else {
$( '#quote-popup #quote-popup-content' ).animate({ 'height': newQuoteForm.height() + $( '#quote-popup-tabs' ).height() + 50 }, 300 );
}
}
}, 400 );
}
});
/**
*
* hooks to show contact form popup
*
*/
$( '*[data-action="show-quote-popup"]' ).click( function() {
var quoteKey = $( this ).data( 'quote-key' );
if( typeof quoteKey != 'undefined' && quoteKey !== false ) $.martanianShowQuotePopup( quoteKey );
});
/**
*
* hooks to hide quote popup
*
*/
$( '#quote-popup-close' ).click( function() {
$.martanianHideQuotePopup();
});
/**
*
* managing width of images
*
*/
$.martanianManageImages = function() {
if( windowWidth > 1332 ) {
var width = ( windowWidth - 37.5 ) / 2;
var height = 'math';
var margin = width - 531.5;
var padding = 75;
}
else if( windowWidth > 932 ) {
var width = ( windowWidth - 40 ) / 2;
var height = 'math';
var margin = width - 400;
var padding = 50;
}
else if( windowWidth > 582 ) {
var width = ( ( windowWidth - 540 ) / 2 ) + 540;
var height = 300;
var margin = ( windowWidth - 540 ) / 2;
var padding = 50;
}
else {
var width = windowWidth - 30;
var height = 300;
var margin = 0;
var padding = 30;
}
$( '.about-us .right, .agents .right, .contact-full #google-map-full, .box-with-image-right .image' ).css({ 'width': width +'px', 'margin-right': - margin +'px' });
$( '.insurances-slider .images, .box-with-image-left .image, section.quote-forms .quote-form-background' ).css({ 'width': width +'px', 'margin-left': - margin +'px' });
$( '.about-us, .agents' ).each( function() {
var contentHeight = height == 'math' ? $( this ).children( '.center' ).children( '.left' ).height() + padding : height;
$( this ).children( '.center' ).children( '.right' ).children( '.images-slider' ).css({ 'height': contentHeight });
});
$( '.contact-full' ).each( function() {
var contentHeight = height == 'math' ? $( this ).children( '.center' ).children( '.left' ).height() + padding : height;
$( this ).children( '.center' ).children( '.right' ).children( '#google-map-full' ).css({ 'height': contentHeight });
});
$( '.box-with-image-left' ).each( function() {
var contentHeight = height == 'math' ? $( this ).children( '.center' ).children( '.content' ).height() + padding : height;
$( this ).children( '.center' ).children( '.image' ).css({ 'height': contentHeight });
});
$( '.box-with-image-right' ).each( function() {
var contentHeight = height == 'math' ? $( this ).children( '.center' ).children( '.content' ).height() + padding : height;
$( this ).children( '.center' ).children( '.image' ).css({ 'height': contentHeight });
});
$( 'section.quote-forms' ).each( function() {
var element = $( this );
setTimeout( function() {
var contentHeight = height == 'math' ? element.children( '.center' ).children( '.quote-form-content' ).height() + padding : height;
element.children( '.center' ).children( '.quote-form-background' ).css({ 'height': contentHeight });
}, 100 );
});
};
/**
*
* heading slider
*
*/
$.martanianHeadingSlider = function() {
var currentHeadingSlideID = 1;
var slidesCount = 0;
$( '.heading .heading-slide-single' ).each( function() { slidesCount++; });
setInterval( function() {
$.martanianHideSlide( currentHeadingSlideID );
setTimeout( function() {
currentHeadingSlideID = currentHeadingSlideID + 1 > slidesCount ? 1 : currentHeadingSlideID + 1;
$.martanianShowSlide( currentHeadingSlideID );
}, 400 );
}, 10000 );
};
/**
*
* function hide single heading slide
*
*/
$.martanianHideSlide = function( slideID ) {
var currentSlide = $( '.heading .heading-slide-single[data-slide-id="'+ slideID +'"]' );
currentSlide.children( '.flying-1' ).addClass( 'animated bounceOutLeft' );
currentSlide.children( '.flying-2' ).addClass( 'animated bounceOutRight' );
setTimeout( function() {
currentSlide.children( '.flying-1' ).removeClass( 'animated bounceOutLeft' ).hide();
currentSlide.children( '.flying-2' ).removeClass( 'animated bounceOutRight' ).hide();
currentSlide.children( '.heading-content' ).addClass( 'animated fadeOutUp' );
currentSlide.addClass( 'animated fadeOut' );
setTimeout( function() {
currentSlide.children( '.heading-content' ).removeClass( 'animated fadeOutUp' ).hide();
currentSlide.removeClass( 'animated fadeOut' ).hide();
}, 800 );
}, 400 );
};
/**
*
* function show single heading slide
*
*/
$.martanianShowSlide = function( slideID ) {
var currentSlide = $( '.heading .heading-slide-single[data-slide-id="'+ slideID +'"]' );
currentSlide.children( '.flying-1' ).hide();
currentSlide.children( '.flying-2' ).hide();
currentSlide.children( '.heading-content' ).hide();
currentSlide.addClass( 'animated fadeIn' ).show();
setTimeout( function() {
currentSlide.children( '.flying-1' ).addClass( 'animated bounceInLeft' ).show();
currentSlide.children( '.flying-2' ).addClass( 'animated bounceInRight' ).show();
setTimeout( function() {
currentSlide.children( '.heading-content' ).addClass( 'animated fadeInDown' ).show();
setTimeout( function() {
currentSlide.removeClass( 'animated fadeIn' );
currentSlide.children( '.flying-1' ).removeClass( 'animated bounceInLeft' );
currentSlide.children( '.flying-2' ).removeClass( 'animated bounceInRight' );
currentSlide.children( '.heading-content' ).removeClass( 'animated fadeInDown' );
}, 1000 );
}, 400 );
}, 400 );
};
/**
*
* configure image slider
*
*/
$.martanianConfigureImageSlider = function() {
$( '.about-us .right .images-slider' ).each( function() {
var slider = $( this );
var slideID = 1;
slider.children( '.images-slider-single' ).each( function() {
$( this ).attr( 'data-slide-id', slideID );
slideID++;
});
slider.attr( 'data-active-slide-id', 1 );
slider.attr( 'data-slides-count', slideID - 1 );
});
};
/**
*
* next / prev image
*
*/
$( '.about-us .right .images-slider .images-slider-next' ).click( function() {
var imagesSlider = $( this ).parent().parent();
var currentImageID = parseInt( imagesSlider.data( 'active-slide-id' ) );
var slidesCount = parseInt( imagesSlider.data( 'slides-count' ) );
var nextImageID = currentImageID == slidesCount ? 1 : currentImageID + 1;
imagesSlider.children( '.images-slider-single[data-slide-id="'+ currentImageID +'"]' ).fadeOut( 300 );
imagesSlider.children( '.images-slider-single[data-slide-id="'+ nextImageID +'"]' ).fadeIn( 300 );
imagesSlider.data( 'active-slide-id', nextImageID );
});
$( '.about-us .right .images-slider .images-slider-prev' ).click( function() {
var imagesSlider = $( this ).parent().parent();
var currentImageID = parseInt( imagesSlider.data( 'active-slide-id' ) );
var slidesCount = parseInt( imagesSlider.data( 'slides-count' ) );
var prevImageID = currentImageID == 1 ? slidesCount : currentImageID - 1;
imagesSlider.children( '.images-slider-single[data-slide-id="'+ currentImageID +'"]' ).fadeOut( 300 );
imagesSlider.children( '.images-slider-single[data-slide-id="'+ prevImageID +'"]' ).fadeIn( 300 );
imagesSlider.data( 'active-slide-id', prevImageID );
});
/**
*
* configure insurance slider
*
*/
$.martanianConfigureInsuranceSlider = function() {
if( windowWidth > 1332 ) {
var padding = 75;
var height = 'math';
}
else if( windowWidth > 932 ) {
var padding = 50;
var height = 'math';
}
else {
var padding = 50;
var height = 300;
}
$( '.insurances-slider' ).each( function() {
var slider = $( this ).children( '.center' );
var descriptions = slider.children( '.content' ).children( '.descriptions' );
var activeInsurance = slider.children( '.content' ).children( '.tabs' ).children( 'li.active' ).data( 'insurance-key' );
if( typeof activeInsurance == 'undefined' || activeInsurance === false ) {
activeInsurance = slider.children( '.content' ).children( '.tabs' ).children( 'li' ).first().data( 'insurance-key' );
slider.children( '.content' ).children( '.tabs' ).children( 'li' ).first().addClass( 'active' );
}
descriptions.children( '.description[data-insurance-key="'+ activeInsurance +'"]' ).show();
descriptions.css({ 'height': descriptions.children( '.description[data-insurance-key="'+ activeInsurance +'"]' ).height() });
slider.children( '.images' ).children( '.image[data-insurance-key="'+ activeInsurance +'"]' ).show();
if( height == 'math' ) height = slider.children( '.content' ).height() + padding;
slider.children( '.images' ).css({ 'height': height });
});
};
/**
*
* change insurances slider single slide
*
*/
$( '.insurances-slider .tabs li' ).click( function() {
if( !$( this ).hasClass( 'active' ) ) {
if( windowWidth > 1332 ) {
var space = 213;
}
else if( windowWidth > 932 ) {
var space = 188;
}
var newInsuranceKey = $( this ).data( 'insurance-key' );
var oldInsuranceKey = $( this ).siblings( '.active' ).data( 'insurance-key' );
var slider = $( this ).parent().parent().parent();
var newHeight = 0;
var oldDescription = slider.children( '.content' ).children( '.descriptions' ).children( '.description[data-insurance-key="'+ oldInsuranceKey +'"]' );
var newDescription = slider.children( '.content' ).children( '.descriptions' ).children( '.description[data-insurance-key="'+ newInsuranceKey +'"]' );
$( '.insurances-slider .tabs li' ).removeClass( 'active' );
$( this ).addClass( 'active' );
oldDescription.addClass( 'animated speed fadeOutRight' );
slider.children( '.images' ).children( '.image[data-insurance-key="'+ oldInsuranceKey +'"]' ).fadeOut( 300 );
slider.children( '.images' ).children( '.image[data-insurance-key="'+ newInsuranceKey +'"]' ).fadeIn( 300 );
setTimeout( function() {
newDescription.addClass( 'animated speed fadeInRight' ).show();
newHeight = newDescription.height();
slider.children( '.content' ).children( '.descriptions' ).animate({ 'height': newHeight }, 200 );
slider.children( '.images' ).animate({ 'height': newHeight + space }, 200 );
setTimeout( function() {
oldDescription.removeClass( 'animated speed fadeOutRight' ).hide();
newDescription.removeClass( 'animated speed fadeInRight' );
}, 400 );
}, 300 );
}
});
/**
*
* manage references
*
*/
var referencesInterval = {};
$.martanianManageReferences = function() {
var referenceBoxID = 0;
$( 'section.references' ).each( function() {
referenceBoxID++;
clearInterval( referencesInterval[referenceBoxID] );
if( windowWidth > 1332 ) {
var padding = 150;
}
else if( windowWidth > 932 ) {
var padding = 100;
}
var referencesSection = $( this );
var references = $( this ).children( '.center' ).children( '.right' ).children( '.references' );
var referenceID = 1;
references.children( '.single-reference' ).each( function() {
$( this ).attr( 'data-reference-id', referenceID );
if( referenceID > 1 ) $( this ).hide();
else {
$( this ).show();
references.css({ 'marginTop': '', 'min-height': $( this ).height() });
references.css({ 'marginTop': ( referencesSection.height() - padding - ( $( this ).children( '.single-reference-content' ).height() + 40 ) ) / 2 });
}
referenceID++;
});
if( referenceID > 2 ) {
var currentReference = 1;
referencesInterval[referenceBoxID] = setInterval( function() {
var oldReference = references.children( '.single-reference[data-reference-id="'+ currentReference +'"]' );
currentReference = ( currentReference + 1 ) > ( referenceID - 1 ) ? 1 : currentReference + 1;
var newReference = references.children( '.single-reference[data-reference-id="'+ currentReference +'"]' );
oldReference.addClass( 'animated speed fadeOutLeft' );
newReference.addClass( 'animated speed fadeInLeft' ).show();
references.animate({ 'min-height': newReference.height(), 'marginTop': ( referencesSection.height() - padding - ( newReference.children( '.single-reference-content' ).height() + 40 ) ) / 2 }, 200 );
setTimeout( function() {
oldReference.removeClass( 'animated speed fadeOutLeft' ).hide();
newReference.removeClass( 'animated speed fadeInLeft' );
}, 500 );
}, 5000 );
}
});
};
/**
*
* numbers highlighter
*
*/
$.martanianNumbersHighlighter = function() {
var animation = 'shake';
$( '.key-number-values' ).each( function() {
var parent = $( this );
var boxes = [];
parent.children( '.single' ).each( function() {
boxes.push( $( this ).children( '.number' ) );
});
setInterval( function() {
$( boxes[0][0] ).addClass( 'animated '+ animation );
setTimeout( function() {
$( boxes[1][0] ).addClass( 'animated '+ animation );
setTimeout( function() {
$( boxes[2][0] ).addClass( 'animated '+ animation );
setTimeout( function() {
$( boxes[3][0] ).addClass( 'animated '+ animation );
setTimeout( function() {
$( boxes[0][0] ).removeClass( 'animated '+ animation );
$( boxes[1][0] ).removeClass( 'animated '+ animation );
$( boxes[2][0] ).removeClass( 'animated '+ animation );
$( boxes[3][0] ).removeClass( 'animated '+ animation );
}, 1000 );
}, 400 );
}, 400 );
}, 400 );
}, 5000 );
});
};
/**
*
* checkbox field
*
*/
$( '.checkbox' ).click( function() {
var checkbox = $( this );
var checked = checkbox.attr( 'data-checked' ) == 'yes' ? true : false;
if( checked == true ) {
checkbox.attr( 'data-checked', 'no' );
checkbox.data( 'checked', 'no' );
checkbox.children( '.checkbox-status' ).php( '<i class="fa fa-times"></i>' );
}
else {
checkbox.attr( 'data-checked', 'yes' );
checkbox.data( 'checked', 'yes' );
checkbox.children( '.checkbox-status' ).php( '<i class="fa fa-check"></i>' );
}
});
/**
*
* sliders
*
*/
$.martanianConfigureValueSlider = function() {
$( '#quote-popup .quote-form .slider, section.quote-forms .slider' ).each( function() {
var sliderValueMin = $( this ).data( 'slider-min' );
var sliderValueMax = $( this ).data( 'slider-max' );
var sliderValueStart = $( this ).data( 'slider-start' );
var sliderValueStep = $( this ).data( 'slider-step' );
var sliderID = $( this ).data( 'slider-id' );
$( this ).noUiSlider({ start: sliderValueStart, step: sliderValueStep, range: { 'min': sliderValueMin, 'max': sliderValueMax } });
$( this ).Link( 'lower' ).to( $( '.slider-value[data-slider-id="'+ sliderID +'"] span' ), null, wNumb({ thousand: '.', decimals: '0' }) );
});
};
/**
*
* send quote
*
*/
$( '.send-quote' ).click( function() {
var quoteForm = $( this ).parent();
var quoteFormParent = quoteForm.parent().parent();
var insuranceType = quoteFormParent.data( 'quote-form-for' );
var fields = {};
var fieldID = 0;
var fieldName = '';
var fieldValue = '';
var clientName = '';
var clientEmail = '';
var errorFound = false;
quoteForm.find( '.quote-form-element' ).each( function( fieldID ) {
fieldName = $( this ).attr( 'name' );
if( typeof fieldName == 'undefined' || fieldName === false ) {
fieldName = $( this ).data( 'name' );
}
if( $( this ).hasClass( 'checkbox' ) ) {
fieldValue = $( this ).data( 'checked' ) == 'yes' ? $( this ).children( '.checkbox-values' ).children( '.checkbox-value-checked' ).text() : $( this ).children( '.checkbox-values' ).children( '.checkbox-value-unchecked' ).text();
}
else {
fieldValue = $( this ).is( 'input' ) || $( this ).is( 'select' ) ? $( this ).val() : $( this ).text();
if( ( $( this ).is( 'input' ) && fieldValue == '' ) || ( $( this ).is( 'select' ) && fieldValue == '-' ) ) {
errorFound = true;
$( this ).addClass( 'error' );
}
else {
$( this ).removeClass( 'error' );
}
}
if( $( this ).hasClass( 'quote-form-client-name' ) ) clientName = $( this ).val();
if( $( this ).hasClass( 'quote-form-client-email' ) ) clientEmail = $( this ).val();
fields[fieldID] = { 'name': fieldName, 'value': fieldValue };
fieldID++;
});
if( errorFound == false ) {
$.ajax({ url: '_assets/submit.php',
data: { 'send': 'quote-form', 'values': fields, 'clientName': clientName, 'clientEmail': clientEmail },
type: 'post',
success: function( output ) {
quoteForm.children( '.quote-form-thanks' ).fadeIn( 300 );
}
});
}
});
/**
*
* close quote popup notice
*
*/
$( '.quote-form-thanks-close' ).click( function() {
var parent = $( this ).parent().parent();
parent.fadeOut( 300 );
});
/**
*
* send contact form
*
*/
$( '.send-contact' ).click( function() {
var contactForm = $( this ).parent();
var contactFormParent = contactForm.parent().parent();
var fields = {};
var fieldID = 0;
var fieldName = '';
var fieldValue = '';
var clientName = '';
var clientEmail = '';
var clientMessageTitle = '';
var errorFound = false;
contactForm.find( '.contact-form-element' ).each( function( fieldID ) {
fieldName = $( this ).attr( 'name' );
if( typeof fieldName == 'undefined' || fieldName === false ) {
fieldName = $( this ).data( 'name' );
}
if( $( this ).hasClass( 'checkbox' ) ) {
fieldValue = $( this ).data( 'checked' ) == 'yes' ? $( this ).children( '.checkbox-values' ).children( '.checkbox-value-checked' ).text() : $( this ).children( '.checkbox-values' ).children( '.checkbox-value-unchecked' ).text();
}
else {
fieldValue = $( this ).is( 'input' ) || $( this ).is( 'textarea' ) || $( this ).is( 'select' ) ? $( this ).val() : $( this ).text();
if( ( $( this ).is( 'input' ) && fieldValue == '' ) || ( $( this ).is( 'textarea' ) && fieldValue == '' ) || ( $( this ).is( 'select' ) && fieldValue == '-' ) ) {
errorFound = true;
$( this ).addClass( 'error' );
}
else {
$( this ).removeClass( 'error' );
}
}
if( $( this ).hasClass( 'contact-form-client-name' ) ) clientName = $( this ).val();
if( $( this ).hasClass( 'contact-form-client-email' ) ) clientEmail = $( this ).val();
if( $( this ).hasClass( 'contact-form-client-message-title' ) ) clientMessageTitle = $( this ).val();
fields[fieldID] = { 'name': fieldName, 'value': fieldValue };
fieldID++;
});
if( errorFound == false ) {
$.ajax({ url: '_assets/submit.php',
data: { 'send': 'contact-form', 'values': fields, 'clientName': clientName, 'clientEmail': clientEmail, 'clientMessageTitle': clientMessageTitle },
type: 'post',
success: function( output ) {
contactForm.children( '.contact-form-thanks' ).fadeIn( 300 );
}
});
}
});
/**
*
* close contact popup notice
*
*/
$( '.contact-form-thanks .contact-form-thanks-content .contact-form-thanks-close' ).click( function() {
var parent = $( this ).parent().parent();
parent.fadeOut( 300 );
});
/**
*
* get a phone call
*
*/
$( '.send-phone-call-quote' ).click( function() {
var element = $( this );
var phoneField = element.siblings( '.phone-number' );
var phoneNumber = phoneField.val();
if( phoneNumber == '' ) phoneField.addClass( 'error' );
else {
phoneField.removeClass( 'error' );
$.ajax({ url: '_assets/submit.php',
data: { 'send': 'phone-form', 'phoneNumber': phoneNumber },
type: 'post',
success: function( output ) {
element.siblings( '.call-to-action-thanks' ).fadeIn( 300 );
}
});
}
});
/**
*
* close phone call notice
*
*/
$( '.call-to-action-thanks .call-to-action-thanks-content .call-to-action-thanks-close' ).click( function() {
var parent = $( this ).parent().parent();
parent.fadeOut( 300 );
});
/**
*
* progress bars
*
*/
$.martanianProgressBars = function( progressBars ) {
if( progressBars.hasClass( 'animated-done' ) ) return;
var progressValue = '';
progressBars.children( '.progress-bar' ).each( function() {
var progressBar = $( this ).children( '.progress-bar-value' );
progressValue = progressBar.data( 'value' );
progressBar.animate({ 'width': progressValue }, 900 );
setTimeout( function() {
progressBar.children( '.progress-bar-value-tip' ).fadeIn( 300 );
}, 900 );
});
progressBars.addClass( 'animated-done' );
};
$.martanianProgressBarsAutoload = function() {
setTimeout( function() {
$( '.progress-bars.progress-bars-autoload' ).each( function() {
var progressBars = $( this );
var progressValue = '';
progressBars.children( '.progress-bar' ).each( function() {
var progressBar = $( this ).children( '.progress-bar-value' );
progressValue = progressBar.data( 'value' );
progressBar.animate({ 'width': progressValue }, 900 );
setTimeout( function() {
progressBar.children( '.progress-bar-value-tip' ).fadeIn( 300 );
}, 900 );
});
});
}, 500 );
};
/**
*
* configure insurance slider
*
*/
$.martanianConfigureAgentsSlider = function() {
$( 'section.agents' ).each( function() {
var agentID = 1;
var agentImageID = 1;
var agentsData = $( this ).children( '.center' ).children( '.left' ).children( '.agents-data' );
var agentsImages = $( this ).children( '.center' ).children( '.right' ).children( '.images-slider' );
agentsData.children( '.single-agent' ).each( function() {
$( this ).attr( 'data-agent-id', agentID );
if( agentID == 1 ) {
agentsData.css({ 'height': $( this ).height() - 45 });
var progressBars = $( this ).children( '.progress-bars' );
if( typeof progressBars[0] != 'undefined' && progressBars[0] != '' ) {
setTimeout( function() {
$.martanianProgressBars( progressBars );
}, 300 );
}
}
agentID++;
});
agentsData.attr( 'data-current-agent-id', 1 ).attr( 'data-agents-count', agentID - 1 );
agentsImages.children( '.images-slider-single' ).each( function() {
$( this ).attr( 'data-agent-id', agentImageID );
agentImageID++;
});
});
};
/**
*
* change insurances slider single slide
*
*/
$( '.agents .center .left .switch-agents button' ).click( function() {
var agentsData = $( this ).parent().siblings( '.agents-data' );
var agentsImages = $( this ).parent().parent().siblings( '.right' ).children( '.images-slider' );
var currentAgentID = parseInt( agentsData.attr( 'data-current-agent-id' ) );
var agentsCount = parseInt( agentsData.attr( 'data-agents-count' ) );
var action = $( this ).hasClass( 'prev-agent' ) ? 'prev' : ( $( this ).hasClass( 'next-agent' ) ? 'next' : false );
if( action == false ) return false;
else {
switch( action ) {
case 'prev':
var newAgentID = currentAgentID == 1 ? agentsCount : currentAgentID - 1;
break;
case 'next':
var newAgentID = currentAgentID == agentsCount ? 1 : currentAgentID + 1;
break;
}
agentsData.children( '.single-agent[data-agent-id="'+ currentAgentID +'"]' ).fadeOut( 300 );
agentsData.children( '.single-agent[data-agent-id="'+ newAgentID +'"]' ).fadeIn( 300 );
agentsImages.children( '.images-slider-single[data-agent-id="'+ currentAgentID +'"]' ).fadeOut( 300 );
agentsImages.children( '.images-slider-single[data-agent-id="'+ newAgentID +'"]' ).fadeIn( 300 );
agentsData.attr( 'data-current-agent-id', newAgentID );
agentsData.animate({ 'height': agentsData.children( '.single-agent[data-agent-id="'+ newAgentID +'"]' ).height() - 30 }, 300 );
if( windowWidth > 932 ) agentsImages.animate({ 'height': agentsData.children( '.single-agent[data-agent-id="'+ newAgentID +'"]' ).height() + 124 }, 300 )
var progressBars = agentsData.children( '.single-agent[data-agent-id="'+ newAgentID +'"]' ).children( '.progress-bars' );
if( typeof progressBars[0] != 'undefined' && progressBars[0] != '' ) {
setTimeout( function() {
$.martanianProgressBars( progressBars );
}, 300 );
}
}
});
/**
*
* tabs section
*
*/
$.martanianConfigureTabsSection = function() {
var padding = windowWidth > 1332 ? 150 : 100;
$( 'section.tabs' ).each( function() {
var tabID = 1;
var content = $( this ).children( '.center' ).children( '.content' );
var tabs = $( this ).children( '.center' ).children( '.tabs-selector' );
content.children( '.content-tab-single' ).each( function() {
$( this ).attr( 'data-tab-id', tabID );
if( tabID == 1 ) {
content.css({ 'height': $( this ).height() + padding });
}
tabID++;
});
tabID = 1;
tabs.children( 'li' ).each( function() {
$( this ).attr( 'data-tab-id', tabID );
if( tabID == 1 ) {
$( this ).addClass( 'active' );
}
tabID++;
});
});
};
$.martanianResizeTabsSection = function() {
var padding = windowWidth > 1332 ? 150 : 100;
$( 'section.tabs' ).each( function() {
var content = $( this ).children( '.center' ).children( '.content' );
var activeTabID = $( this ).children( '.center' ).children( '.tabs-selector' ).children( 'li.active' ).data( 'tab-id' );
content.css({ 'height': content.children( '.content-tab-single[data-tab-id="'+ activeTabID +'"]' ).height() + padding });
});
};
$( 'section.tabs .tabs-selector li' ).click( function() {
if( $( this ).hasClass( 'active' ) ) return;
var padding = windowWidth > 1332 ? 150 : 80;
var tabsContent = $( this ).parent().siblings( '.content' );
var newTabID = $( this ).data( 'tab-id' );
var oldTabID = $( this ).siblings( 'li.active' ).data( 'tab-id' );
$( this ).siblings( 'li.active' ).removeClass( 'active' );
$( this ).addClass( 'active' );
tabsContent.children( '.content-tab-single[data-tab-id="'+ oldTabID +'"]' ).fadeOut( 300 );
setTimeout( function() {
tabsContent.children( '.content-tab-single[data-tab-id="'+ newTabID +'"]' ).fadeIn( 300 );
tabsContent.animate({ 'height': tabsContent.children( '.content-tab-single[data-tab-id="'+ newTabID +'"]' ).height() + padding }, 300 );
}, 100 );
});
/**
*
* open menu in responsive mode
*
*/
$( 'header .menu-responsive' ).click( function() {
var menu = $( 'header .menu' );
if( menu.css( 'display' ) == 'block' ) menu.hide();
else {
menu.find( 'ul.submenu' ).removeClass( 'animated' );
menu.show();
}
});
/**
*
* set parallax
*
*/
$.martanianSetParallax = function() {
var speed = windowWidth > 1120 ? 0.25 : 0.1;
$( '.with-parallax' ).css({ 'background-position': '' }).parallax( '50%', speed );
};
/**
*
* resize manager
*
*/
$.martanianResizeManager = function() {
/**
*
* mode
*
*/
var mode = windowWidth > 932 && windowHeight > 670 ? 'fixed' : 'absolute';
/**
*
* insurances slider
*
*/
$( '.insurances-slider' ).each( function() {
if( windowWidth > 1332 ) {
var padding = 75;
var height = 'math';
}
else if( windowWidth > 932 ) {
var padding = 50;
var height = 'math';
}
else {
var padding = 50;
var height = 300;
}
var slider = $( this ).children( '.center' );
var activeInsurance = slider.children( '.content' ).children( '.tabs' ).children( 'li.active' ).data( 'insurance-key' );
var image = slider.children( '.images' ).children( '.image[data-insurance-key="'+ activeInsurance +'"]' );
if( height == 'math' ) height = slider.children( '.content' ).height() + padding;
image.css({ 'height': height });
});
/**
*
* quote popup
*
*/
if( $( '#quote-popup #quote-popup-background' ).css( 'display' ) == 'block' ) {
var type = $( '#quote-popup #quote-popup-content #quote-popup-tabs li.active' ).data( 'quote-tab-for' );
var selectedQuoteForm = $( '#quote-popup #quote-popup-content .quote-form[data-quote-form-for="'+ type +'"]' );
setTimeout( function() {
if( mode == 'fixed' ) {
selectedQuoteForm.children( '.quote-form-background' ).css({ 'height': selectedQuoteForm.height() });
$( '#quote-popup #quote-popup-content' ).css({ 'top': '50%', 'marginTop': - ( selectedQuoteForm.height() / 2 ), 'height': selectedQuoteForm.height(), 'position': 'fixed' });
}
else if( mode == 'absolute' ) {
if( windowWidth > 932 ) {
$( '#quote-popup #quote-popup-content' ).addClass( 'bounceInDown' ).css({ 'top': '50px', 'marginTop': '0px', 'height': selectedQuoteForm.height(), 'position': 'absolute' });
selectedQuoteForm.children( '.quote-form-background' ).css({ 'height': selectedQuoteForm.height() });
}
else {
$( '#quote-popup .quote-form-background' ).css({ 'height': '' });
if( windowWidth > 582 ) $( '#quote-popup #quote-popup-content' ).css({ 'top': '50px', 'marginTop': '0px', 'height': selectedQuoteForm.height(), 'position': 'absolute' });
else {
$( '#quote-popup #quote-popup-content' ).css({ 'top': '50px', 'marginTop': '0px', 'height': selectedQuoteForm.height() + $( '#quote-popup-tabs' ).height() + 50, 'position': 'absolute' });
}
}
}
}, 300 );
}
/**
*
* contact popup
*
*/
if( $( '#contact-popup #contact-popup-background' ).css( 'display' ) == 'block' ) {
setTimeout( function() {
if( mode == 'fixed' ) $( '#contact-popup #contact-popup-content' ).css({ 'top': '50%', 'position': 'fixed', 'marginTop': '-300px' });
else $( '#contact-popup #contact-popup-content' ).css({ 'top': '50px', 'marginTop': '0px', 'position': 'absolute' });
}, 300 );
}
/**
*
* end of resize manager
*
*/
};
/**
*
* end of file
*
*/
}); |
var mongodb = require('mongodb'),
ObjectId = mongodb.ObjectId;
/**
* Quips Quarantine
**/
var quips_quarantine = function ( app ) {
/**
* Return a list of all (for now) quips in quips_quarantine
**/
app.get('/v1/quips_quarantine', function ( req, res ) {
app.mdbConnect(function ( err, db ) {
db.collection('quips_quarantine').find().toArray(function ( err, results ) {
if (err) { throw err; }
if (results) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify( results ));
}
db.close();
});
});
});
app.get('/v1/quips_quarantine/:id', function ( req, res ) {
app.mdbConnect(function ( err, db ) {
if (err) { throw err; }
db.collection('quips_quarantine').findOne({ "_id": new ObjectId( req.params.id ) }, function ( err, doc ) {
if (err) { throw err; }
if (doc) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify( doc ));
}
db.close();
});
});
});
app.get('/v1/quips_quarantine/:id/approve', function ( req, res ) {
app.mdbConnect(function ( err, db ) {
if (err) { throw err; }
db.collection('quips_quarantine').findOne({ "_id": new ObjectId( req.params.id ) }, function ( err, doc ) {
if (err) { throw err; }
if (doc) {
db.collection('quips').insert( doc );
db.collection('quips_quarantine').remove( doc );
res.send(JSON.stringify( doc ));
}
db.close();
});
});
});
app.get('/v1/quips_quarantine/:id/reject', function ( req, res ) {
app.mdbConnect(function ( err, db ) {
if (err) { throw err; }
// db.collection('quips_quarantine').findOne({ "_id": new ObjectId( req.params.id ) }, function ( err, doc ) {
// if (err) { throw err; }
// if (doc) {
// db.collection('quips_quarantine').remove( doc );
// res.send(JSON.stringify( doc ));
// }
// db.close();
// });
});
});
};
module.exports = quips_quarantine; |
/*jshint esversion: 6 */
import './flowtext.js';
|
var ig = {};
// !!! USE YOUR OWN TOKEN
ig.token = '43619676.1677ed0.5ca7163640fc4a7f89ca21dc02475134';
ig.init = function() {
$('.instagram').each(function(i) {
var args = {};
args.container = $(this);
args.userid = args.container.data('userid');
args.limit = args.container.data('limit');
args.feedurl = 'https://api.instagram.com/v1/users/'+args.userid+'/media/recent/?access_token='+ig.token+'&count='+args.limit+'&callback=?';
args.html = '';
// PASS ARGS TO QUERY
ig.query(args);
});
}
ig.query = function(args) {
$.getJSON(args.feedurl, {}, function(data) {
// PASS QUERY DATA TO BUILDER
ig.build(data, args);
});
}
ig.build = function(data, args) {
$.each(data.data,function (i,item) {
console.log(item);
if (item.caption) var caption = item.caption.text;
var thumb = item.images.low_resolution.url;
var img = item.images.standard_resolution.url;
//get 1280 size photo [hack until avail in api]
var hires = img.replace('s640x640', '1080x1080');
args.html += '<a class="image" style="background-image: url('+thumb+');" data-img="'+hires+'">';
if (caption) args.html += '<span class="caption">'+caption+'</span>';
args.html += '</a>';
// PASS TO OUTPUT
ig.output(args);
});
}
ig.output = function(args) {
args.container.html(args.html);
}
ig.view = {
viewer: $('.igviewer'),
image: $('.igviewer img'),
open: function(img) {
ig.view.viewer.removeClass('hidden');
ig.view.image.attr('src', img);
},
close: function() {
ig.view.viewer.addClass('hidden');
ig.view.image.attr('src', '');
}
}
ig.init();
//Listeners
$('.instagram').on('click', '.image', function(){
var img = this.dataset.img;
ig.view.open(img);
});
$('.igviewer').on('click', function(){
ig.view.close();
});
|
'use strict';
var handyJS = {};
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
handyJS.ajax = {};
handyJS.ajax.request = function (options) {
var self = this;
var blankFun = function blankFun() {};
self.xhr = new XMLHttpRequest();
if (options.method === undefined) {
options.method = 'GET';
} else {
options.method = options.method.toUpperCase();
}
if (options.async === undefined) {
options.async = true;
}
if (!options.data) {
options.segments = null;
} else if (!Array.isArray(options.data)) {
throw Error('Option.data must be an Array.');
} else if (options.data.length === 0) {
options.segments = null;
} else {
//detect the form to send data.
if (options.method === 'POST') {
options.data.forEach(function (segment) {
if (segment === null) {
throw Error('Do not send null variable.');
} else if ((typeof segment === 'undefined' ? 'undefined' : _typeof(segment)) === 'object') {
for (var key in segment) {
if (segment.hasOwnProperty(key)) {
if (segment[key] === undefined) {
continue;
}
if (segment[key] instanceof Blob) {
if (options.enctype === undefined) {
options.enctype = 'FORMDATA';
break;
}
if (options.enctype.toUpperCase() !== 'FORMDATA') {
throw Error('You have to set dataForm to \'FormData\'' + ' because you about to send file, or just ignore this property.');
}
}
if (options.enctype === undefined) {
options.enctype = 'URLENCODE';
}
}
}
} else {
throw Error('You have to use {key: value} structure to send data.');
}
});
} else {
options.enctype = 'URLINLINE';
}
}
//transform some type of value
var transformValue = function transformValue(value) {
if (value === null) {
return '';
}
if (value === undefined) {
return '';
}
switch (typeof value === 'undefined' ? 'undefined' : _typeof(value)) {
case 'object':
if (value instanceof Blob) {
return value;
} else {
return JSON.stringify(value);
}
break;
case 'string':
return value;
default:
return value;
}
};
//encode uri string
//Copied from MDN, if wrong, pls info me.
var encodeUriStr = function encodeUriStr(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16);
});
};
//add event handler. These handlers must added before open method.
//set blank functions
options.onProgress = options.onProgress || blankFun;
options.onComplete = options.onComplete || blankFun;
options.onFailed = options.onFailed || blankFun;
options.onCanceled = options.onCanceled || blankFun;
options.onLoadEnd = options.onLoadEnd || blankFun;
self.xhr.addEventListener('progress', options.onProgress);
self.xhr.addEventListener('load', options.onComplete);
self.xhr.addEventListener('error', options.onFailed);
self.xhr.addEventListener('abort', options.onCanceled);
self.xhr.addEventListener('loadend', options.onLoadEnd);
self.xhr.open(options.method, options.url, options.async, options.user, options.password);
//digest the data decided by encode type
//header setting must be done here
switch (options.enctype.toUpperCase()) {
case 'FORMDATA':
console.log('Encode data as FormData type.');
options.segments = new FormData();
options.data.forEach(function (segment) {
if (segment.fileName) {
for (var key in segment) {
if (segment.hasOwnProperty(key)) {
if (key !== 'fileName') {
options.segments.append(key, segment[key], segment.fileName);
}
}
}
} else {
for (var _key in segment) {
if (segment.hasOwnProperty(_key)) {
options.segments.append(_key, transformValue(segment[_key]));
}
}
}
});
break;
case 'URLINLINE':
console.log('Encode data as url inline type.');
options.segments = null;
options.data.forEach(function (segment, index) {
for (var key in segment) {
if (segment.hasOwnProperty(key)) {
var value = encodeUriStr(transformValue(segment[key]));
if (index === 0) {
options.url = options.url + '?' + value;
} else {
options.url = options.url + '&' + value;
}
}
}
});
break;
case 'URLENCODE':
console.log('Encode data as url encode type.');
self.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
options.segments = '';
options.data.forEach(function (segment, index) {
for (var key in segment) {
if (segment.hasOwnProperty(key)) {
var value = encodeUriStr(transformValue(segment[key]));
if (index === 0) {
options.segments = options.segments + key + '=' + value;
} else {
options.segments = options.segments + '&' + key + '=' + value;
}
}
}
});
break;
}
self.xhr.send(options.segments);
};
handyJS.ajax.post = function (url, data, cb) {
var self = this;
self.request({
method: 'POST',
url: url,
data: data,
onComplete: function onComplete() {
//get response content types
var contentType = handyJS.string.removeWhitespace(this.getResponseHeader('content-type').toLowerCase()).split(';');
//callback with probably variables.
if (contentType.indexOf('application/json') === -1) {
cb(this.responseText);
} else {
cb(JSON.parse(this.responseText));
}
}
});
};
'use strict';
//All bout file manipulate
handyJS.file = {};
// sources:
// http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript
handyJS.file.getExtension = function (fileName) {
return fileName.slice((Math.max(0, fileName.lastIndexOf('.')) || Infinity) + 1);
};
//usage: changeFileName('ding.js', 'dong'); => dong.js
handyJS.file.changeName = function (originalName, newName) {
var extension = this.getExtension(originalName);
return newName + '.' + extension;
};
'use strict';
handyJS.string = {};
//remove whitespace, tab and new line
handyJS.string.removeAllSpace = function (string) {
return string.replace(/\s/g, '');
};
//only remove whitespace
handyJS.string.removeWhitespace = function (string) {
return string.replace(/ /g, '');
};
"use strict"; |
var Chat = function(socket) {
this.socket = socket;
};
// function to send chat messages
Chat.prototype.sendMessage = function(room, text) {
var message = {
room: room,
text: text
};
this.socket.emit('message', message);
};
// function to change rooms
Chat.prototype.changeRoom = function(room) {
this.socket.emit('join', {
newRoom: room
});
};
// processing chat commands
Chat.prototype.processCommand = function(command) {
var words = command.split(' ');
var command = words[0]
.substring(1, words[0].length)
.toLowerCase(); // parse command from first word
var message = false;
switch(command) {
case 'join':
words.shift();
var room = words.join(' ');
this.changeRoom(room); // handle room changing/creating
break;
case 'nick':
words.shift();
var name = words.join(' ');
this.socket.emit('nameAttempt', name); // handle name-change attempts
break;
default:
message = 'Unrecognized command.'; // return error message if command isn't Unrecognized
break;
}
return message;
}; |
import Ember from 'ember';
import layout from '../templates/components/ons-back-button';
export default Ember.Component.extend({
layout,
tagName: 'ons-back-button',
attributeBindings: ['modifier']
});
|
"use strict";
var chai = require('chai');
var chaiHttp = require('chai-http');
var expect = require('chai').expect;
var app = require('../app');
var port = 3001;
var user1 = {
username: 'Laura',
password: 'tiger',
address: {
street: '123 Main St',
city: 'Beaverton',
state: 'OR',
zip: 97007,
},
_id: '',
};
chai.use(chaiHttp);
function chaiRequest() {
return chai.request(`localhost:${port}`);
}
describe('Single Resource REST API', function() {
before(function(done) {
app.listen(port, done);
});
it('POST /users request should add a user to DB', function(done) {
chaiRequest()
.post('/users')
.send(user1)
.end(function(err, res) {
expect(res).to.have.status(200);
//expect(res.text).to.have.string('Welcome to');
expect(res.body).to.have.property('_id');
user1._id = res.body._id;
expect(res.body.username).to.equal(user1.username);
done();
});
});
it('GET /users/:id request for user1 ID should user1 from DB', function(done) {
chaiRequest()
.get('/users/' + user1._id)
.end(function(err, res) {
expect(res).to.have.status(200);
expect(res.body._id).to.equal(user1._id);
expect(res.body.username).to.equal(user1.username);
done();
});
});
it('GET /users request should return all users from DB', function(done) {
chaiRequest()
.get('/users')
.end(function(err, res) {
expect(res).to.have.status(200);
expect(res.body.length).to.be.above(0);
done();
});
});
it('GET /users/:id request for INVALID ID should return empty object', function(done) {
chaiRequest()
.get('/users/999999')
.end(function(err, res) {
expect(res.body).to.be.empty;
done();
});
});
// it('PUT /users/:id request for user1 ID should update user1 password in DB', function(done) {
// chaiRequest()
// .put('/users/' + user1._id)
// .send({password: 'NewPassword'})
// .end(function(err, res) {
// console.log(res.redirects);
// expect(res).to.have.status(200);
// expect(res.body._id).to.equal(user1._id);
// expect(res.body.password).to.equal('NewPassword');
// done();
// });
// });
it('DELETE /users/:id should delete user1 from DB', function(done) {
chaiRequest()
.del('/users/' + user1._id)
.end(function(err, res) {
expect(err).to.be.null;
expect(res).to.have.status(200);
expect(res).to.be.json;
expect(res.body.message).to.equal('ID: ' + user1._id + ' deleted from DB');
done();
});
});
});
|
/**
* Clone a copy of the object passed as parameter using JQuery extension
* @param {object} o
* @return {object} copy of the parameter object
*/
function clone(o) {
return jQuery.extend({}, o);
}
function disableZoomHandlers(map) {
map.touchZoom.disable();
map.doubleClickZoom.disable();
map.scrollWheelZoom.disable();
if (map.tap) map.tap.disable();
}
// on('click') => changeColor
function changeColor(e) {
for (var i = 0; i < geoJson.length; i++) {
geoJson[i].properties['marker-color'] =
geoJson[i].properties['old-color'] || geoJson[i].properties['marker-color'];
}
addImages(e);
e.layer.feature.properties['old-color'] = e.layer.feature.properties['marker-color'];
e.layer.feature.properties['marker-color'] = '#ff8888';
myLayer.setGeoJSON(geoJson);
}
// on('click') => centerOnMarker
function centerOnMarker(e) {
goo = clone(e.layer.getLatLng());
goo["lat"] += 3.3;
map.panTo(goo);
}
// map button - onclick => hideQuotes
function hideQuotes() {
$('#quotes').fadeTo(2000, 0.0, function() {
// get focus on the map again
$('#quotes').hide();
});
$('#map').fadeTo(2000, 1.0);
}
// quotes button - onclick => hideQuotes
function showQuotes() {
$('#quotes').fadeTo(2000, 1.0);
$('#map').fadeTo(2000, 0.3);
}
// on('layeradd') => addImages
function addImages(e) {
var marker = e.layer;
var feature = marker.feature;
var images = feature.properties.images
var slideshowContent = '';
for(var i = 0; i < images.length; i++) {
var img = images[i];
slideshowContent +=
'<div class="image' + (i === 0 ? ' active' : '') + '">' +
'<img src="' + img[0] + '" />';
if (img[1]) {
slideshowContent +=
'<div class="caption">' +
img[1] +
'</div>';
}
slideshowContent += '</div>';
}
var popupContent =
'<div id="' + feature.properties.id + '" class="popup">' +
'<h2>' + feature.properties.title + '</h2>' +
'<div class="slideshow">' +
slideshowContent +
'</div>' +
'<div class="cycle">' +
'<a href="#" class="prev">«</a>' +
'<a href="#" class="next">»</a>' +
'</div>'
'</div>';
var popUpOpt = {closeButton: false, minWidth: 320};
marker.bindPopup(popupContent, popUpOpt);
}
// on('ready') => addLines
function addLines() {
var polyline = newLine();
polyline.addTo(map);
myLayer.eachLayer(function(l) {
if (mustDraw(l.feature.properties)) {
polyline.addLatLng(l.getLatLng());
}
});
}
function newLine() {
var lineOpt = {weight: 5, color: "#fff", opacity: 0.7, clickable: false};
return L.polyline([], lineOpt);
}
// draw a line between large markers only
function mustDraw(properties) {
return properties["marker-size"] == "large";
}
// on('click') => createPopUpHTML
function createPopUpHTML() {
var $slideshow = $('.slideshow'),
$newSlide;
if ($(this).hasClass('prev')) {
$newSlide = $slideshow.find('.active').prev();
if ($newSlide.index() < 0) {
$newSlide = $('.image').last();
}
} else {
$newSlide = $slideshow.find('.active').next();
if ($newSlide.index() < 0) {
$newSlide = $('.image').first();
}
}
$slideshow.find('.active').removeClass('active').hide();
$newSlide.addClass('active').show();
return false;
}
/**
* Menu mouse over position
* Stackoverflow: 19618103
* http://jsfiddle.net/ravikumaranantha/Wtfpx/2/
*/
var mouse_position;
var animating = false;
$(document).mousemove(function (e) {
if (animating) {return;}
mouse_position = e.clientX;
if (mouse_position <= 100) {
animating = true;
$('#cms_bar').animate({left: 0, opacity: 0.9}, 200, function () {
animating = false;
});
} else if (mouse_position > 100) {
animating = true;
$('#cms_bar').animate({left: -80, opacity: 0.7}, 500, function () {
animating = false;
});
}
});
|
module("funcunit-syn integration")
test("Type and slow Click", function(){
S.open("//funcunit/test/myapp.html", null, 10000);
S("#typehere").type("javascriptmvc", function(){
equals(S("#seewhatyoutyped").text(), "typed javascriptmvc","typing");
})
S("#copy").click(function(){
equals(S("#seewhatyoutyped").text(), "copied javascriptmvc","copy");
});
})
test("Nested actions", function(){
S.open("//funcunit/test/myapp.html", null, 10000);
S("#typehere").exists(function(){
this.type("javascriptmvc", function(){
equals(S("#seewhatyoutyped").text(), "typed javascriptmvc","typing");
})
S("#copy").click(function(){
equals(S("#seewhatyoutyped").text(), "copied javascriptmvc","copy");
});
})
})
test("Move To", function(){
S.open("//funcunit/test/drag.html", null, 10000);
S("#start").move("#end")
S("#typer").visible().type("javascriptmvc",function(){
equals(S("#typer").val(), "javascriptmvc","move test worked correctly");
})
})
test("Drag To", function(){
S.open("//funcunit/test/drag.html", null, 10000);
S("#drag").drag("#drop")
S("#clicker").click(function(){
equals(S(".status").text(), "dragged", 'drag worked correctly')
})
})
test("RightClick", function(){
S.open("//funcunit/test/myapp.html", null, 10000);
S("#rightclick").rightClick()
S(".rightclickResult").text("Right Clicked")
}) |
frappe.provide("frappe.ui");
frappe.provide("frappe.web_form");
import EventEmitterMixin from '../../frappe/event_emitter';
export default class WebForm extends frappe.ui.FieldGroup {
constructor(opts) {
super();
Object.assign(this, opts);
frappe.web_form = this;
frappe.web_form.events = {};
Object.assign(frappe.web_form.events, EventEmitterMixin);
}
prepare(web_form_doc, doc) {
Object.assign(this, web_form_doc);
this.fields = web_form_doc.web_form_fields;
this.doc = doc;
}
make() {
super.make();
this.set_field_values();
if (this.introduction_text) this.set_form_description(this.introduction_text);
if (this.allow_print && !this.is_new) this.setup_print_button();
if (this.allow_delete && !this.is_new) this.setup_delete_button();
if (this.is_new) this.setup_cancel_button();
this.setup_primary_action();
$(".link-btn").remove();
// webform client script
frappe.init_client_script && frappe.init_client_script();
frappe.web_form.events.trigger('after_load');
this.after_load && this.after_load();
}
on(fieldname, handler) {
let field = this.fields_dict[fieldname];
field.df.change = () => {
handler(field, field.value);
};
}
set_field_values() {
if (this.doc.name) this.set_values(this.doc);
else return;
}
set_default_values() {
let values = frappe.utils.get_query_params();
delete values.new;
this.set_values(values);
}
set_form_description(intro) {
let intro_wrapper = document.getElementById('introduction');
intro_wrapper.innerHTML = intro;
}
add_button(name, type, action, wrapper_class=".web-form-actions") {
const button = document.createElement("button");
button.classList.add("btn", "btn-" + type, "btn-sm", "ml-2");
button.innerHTML = name;
button.onclick = action;
document.querySelector(wrapper_class).appendChild(button);
}
add_button_to_footer(name, type, action) {
this.add_button(name, type, action, '.web-form-footer');
}
add_button_to_header(name, type, action) {
this.add_button(name, type, action, '.web-form-actions');
}
setup_primary_action() {
this.add_button_to_header(this.button_label || "Save", "primary", () =>
this.save()
);
this.add_button_to_footer(this.button_label || "Save", "primary", () =>
this.save()
);
}
setup_cancel_button() {
this.add_button_to_header(__("Cancel"), "light", () => this.cancel());
}
setup_delete_button() {
this.add_button_to_header(
'<i class="fa fa-trash" aria-hidden="true"></i>',
"light",
() => this.delete()
);
}
setup_print_button() {
this.add_button_to_header(
'<i class="fa fa-print" aria-hidden="true"></i>',
"light",
() => this.print()
);
}
save() {
if (this.validate && !this.validate()) {
frappe.throw(__("Couldn't save, please check the data you have entered"), __("Validation Error"));
}
// validation hack: get_values will check for missing data
let doc_values = super.get_values(this.allow_incomplete);
if (!doc_values) return;
if (window.saving) return;
let for_payment = Boolean(this.accept_payment && !this.doc.paid);
Object.assign(this.doc, doc_values);
this.doc.doctype = this.doc_type;
this.doc.web_form_name = this.name;
// Save
window.saving = true;
frappe.form_dirty = false;
frappe.call({
type: "POST",
method: "frappe.website.doctype.web_form.web_form.accept",
args: {
data: this.doc,
web_form: this.name,
docname: this.doc.name,
for_payment
},
callback: response => {
// Check for any exception in response
if (!response.exc) {
// Success
this.handle_success(response.message);
frappe.web_form.events.trigger('after_save');
this.after_save && this.after_save();
}
},
always: function() {
window.saving = false;
}
});
return true;
}
delete() {
frappe.call({
type: "POST",
method: "frappe.website.doctype.web_form.web_form.delete",
args: {
web_form_name: this.name,
docname: this.doc.name
}
});
}
print() {
window.open(`/printview?
doctype=${this.doc_type}
&name=${this.doc.name}
&format=${this.print_format || "Standard"}`, '_blank');
}
cancel() {
window.location.href = window.location.pathname;
}
handle_success(data) {
if (this.accept_payment && !this.doc.paid) {
window.location.href = data;
}
const success_dialog = new frappe.ui.Dialog({
title: __("Saved Successfully"),
secondary_action: () => {
if (this.success_url) {
window.location.href = this.success_url;
} else if(this.login_required) {
window.location.href =
window.location.pathname + "?name=" + data.name;
}
}
});
success_dialog.show();
const success_message =
this.success_message || __("Your information has been submitted");
success_dialog.set_message(success_message);
}
}
|
var asyncplify = require('../dist/asyncplify');
var tests = require('asyncplify-tests');
describe('debounce', function () {
asyncplify
.interval(15)
.debounce(10)
.take(1)
.pipe(tests.itShouldClose())
.pipe(tests.itShouldEndAsync())
.pipe(tests.itShouldEmitValues([0]));
}); |
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
// parent, args, callback
frappe.upload = {
make: function(opts) {
if(!opts.args) opts.args = {};
if(opts.allow_multiple === undefined) {
opts.allow_multiple = 1
}
// whether to show public/private checkbox or not
opts.show_private = !("is_private" in opts);
// make private by default
if (!("options" in opts) || ("options" in opts &&
(opts.options && !opts.options.toLowerCase()=="public" && !opts.options.toLowerCase()=="image"))) {
opts.is_private = 1;
}
var d = null;
// create new dialog if no parent given
if(!opts.parent) {
d = new frappe.ui.Dialog({
title: __('Upload Attachment'),
primary_action_label: __('Attach'),
primary_action: function() {}
});
opts.parent = d.body;
opts.btn = d.get_primary_btn();
d.show();
}
var $upload = $(frappe.render_template("upload", {opts:opts})).appendTo(opts.parent);
var $file_input = $upload.find(".input-upload-file");
var $uploaded_files_wrapper = $upload.find('.uploaded-filename');
// bind pseudo browse button
$upload.find(".btn-browse").on("click",
function() { $file_input.click(); });
// dropzone upload
const $dropzone = $('<div style="padding: 20px 10px 0px 10px;"/>');
new frappe.ui.DropZone($dropzone, {
drop: function (files) {
$dropzone.hide();
opts.files = opts.files ? [...opts.files, ...files] : files;
$file_input.trigger('change');
}
});
// end dropzone
$upload.append($dropzone);
$file_input.on("change", function() {
if (this.files.length > 0 || opts.files) {
var fileobjs = null;
if (opts.files) {
// files added programmatically
fileobjs = opts.files;
delete opts.files;
} else {
// files from input type file
fileobjs = $upload.find(":file").get(0).files;
}
var file_array = $.makeArray(fileobjs);
$upload.find(".web-link-wrapper").addClass("hidden");
$upload.find(".btn-browse").removeClass("btn-primary").addClass("btn-default");
$uploaded_files_wrapper.removeClass('hidden').empty();
$uploaded_files_wrapper.css({ 'margin-bottom': '25px' });
file_array = file_array.map(
file => Object.assign(file, {is_private: opts.is_private ? 1 : 0})
)
$upload.data('attached_files', file_array);
// List of files in a grid
$uploaded_files_wrapper.append(`
<div class="list-item list-item--head">
<div class="list-item__content list-item__content--flex-2">
${__('Filename')}
</div>
${opts.show_private
? `<div class="list-item__content file-public-column">
${__('Public')}
</div>`
: ''}
<div class="list-item__content list-item__content--activity" style="flex: 0 0 32px">
</div>
</div>
`);
var file_pills = file_array.map(
file => frappe.upload.make_file_row(file, opts)
);
$uploaded_files_wrapper.append(file_pills);
} else {
frappe.upload.show_empty_state($upload);
}
});
if(opts.files && opts.files.length > 0) {
$file_input.trigger('change');
}
// events
$uploaded_files_wrapper.on('click', '.list-item-container', function (e) {
var $item = $(this);
var filename = $item.attr('data-filename');
var attached_files = $upload.data('attached_files');
var $target = $(e.target);
if ($target.is(':checkbox')) {
var is_private = !$target.is(':checked');
attached_files = attached_files.map(file => {
if (file.name === filename) {
file.is_private = is_private ? 1 : 0;
}
return file;
});
$uploaded_files_wrapper
.find(`.list-item-container[data-filename="${filename}"] .fa.fa-fw`)
.toggleClass('fa-lock fa-unlock-alt');
$upload.data('attached_files', attached_files);
}
else if ($target.is('.uploaded-file-remove, .fa-remove')) {
// remove file from attached_files object
attached_files = attached_files.filter(file => file.name !== filename);
$upload.data('attached_files', attached_files);
// remove row from dom
$uploaded_files_wrapper
.find(`.list-item-container[data-filename="${filename}"]`)
.remove();
if(attached_files.length === 0) {
frappe.upload.show_empty_state($upload);
}
}
});
if(!opts.btn) {
opts.btn = $('<button class="btn btn-default btn-sm attach-btn">' + __("Attach")
+ '</div>').appendTo($upload);
} else {
$(opts.btn).unbind("click");
}
// Primary button handler
opts.btn.click(function() {
// close created dialog
d && d.hide();
// convert functions to values
if(opts.get_params) {
opts.args.params = opts.get_params();
}
// Get file url if input is visible
var file_url = $upload.find('[name="file_url"]:visible');
file_url = file_url.length && file_url.get(0).value;
if(opts.args.gs_template) {
frappe.integration_service.gsuite.create_gsuite_file(opts.args,opts);
} else if(file_url) {
opts.args.file_url = file_url;
frappe.upload.upload_file(null, opts.args, opts);
} else {
var files = $upload.data('attached_files');
frappe.upload.upload_multiple_files(files, opts.args, opts);
}
});
},
make_file_row: function(file, { show_private } = {}) {
var template = `
<div class="list-item-container" data-filename="${file.name}">
<div class="list-item">
<div class="list-item__content list-item__content--flex-2 ellipsis">
<span>${file.name}</span>
<span style="margin-top: 1px; margin-left: 5px;"
class="fa fa-fw text-warning ${file.is_private ? 'fa-lock': 'fa-unlock-alt'}">
</span>
</div>
${show_private?
`<div class="list-item__content file-public-column ellipsis">
<input type="checkbox" ${!file.is_private ? 'checked' : ''}/></div>`
: ''}
<div class="list-item__content list-item__content--activity ellipsis" style="flex: 0 0 32px;">
<button class="btn btn-default btn-xs text-muted uploaded-file-remove">
<span class="fa fa-remove"></span>
</button>
</div>
</div>
</div>`;
return $(template);
},
show_empty_state: function($upload) {
$upload.find(".uploaded-filename").addClass("hidden");
$upload.find(".web-link-wrapper").removeClass("hidden");
$upload.find(".private-file").addClass("hidden");
$upload.find(".btn-browse").removeClass("btn-default").addClass("btn-primary");
},
upload_multiple_files: function(files /*FileData array*/, args, opts) {
var i = -1;
frappe.upload.total_files = files ? files.length : 0;
// upload the first file
upload_next();
// subsequent files will be uploaded after
// upload_complete event is fired for the previous file
$(document).on('upload_complete', on_upload);
function upload_next() {
if(files) {
i += 1;
var file = files[i];
args.is_private = file.is_private;
if(!opts.progress) {
frappe.show_progress(__('Uploading'), i, files.length);
}
}
frappe.upload.upload_file(file, args, opts);
}
function on_upload(e, attachment) {
if (!files || i === files.length - 1) {
$(document).off('upload_complete', on_upload);
frappe.hide_progress();
return;
}
upload_next();
}
},
upload_file: function(fileobj, args, opts) {
if(!fileobj && !args.file_url) {
if(opts.on_no_attach) {
opts.on_no_attach();
} else {
frappe.msgprint(__("Please attach a file or set a URL"));
}
return;
}
if(fileobj) {
frappe.upload.read_file(fileobj, args, opts);
} else {
// with file_url
frappe.upload._upload_file(fileobj, args, opts);
}
},
_upload_file: function(fileobj, args, opts, dataurl) {
if (args.file_size) {
frappe.upload.validate_max_file_size(args.file_size);
}
if(opts.on_attach) {
opts.on_attach(args, dataurl)
} else {
if (opts.confirm_is_private) {
frappe.prompt({
label: __("Private"),
fieldname: "is_private",
fieldtype: "Check",
"default": 1
}, function(values) {
args["is_private"] = values.is_private;
frappe.upload.upload_to_server(fileobj, args, opts);
}, __("Private or Public?"));
} else {
if (!("is_private" in args) && "is_private" in opts) {
args["is_private"] = opts.is_private;
}
frappe.upload.upload_to_server(fileobj, args, opts);
}
}
},
read_file: function(fileobj, args, opts) {
args.filename = fileobj.name.split(' ').join('_');
args.file_url = null;
if(opts.options && opts.options.toLowerCase()=="image") {
if(!frappe.utils.is_image_file(args.filename)) {
frappe.msgprint(__("Only image extensions (.gif, .jpg, .jpeg, .tiff, .png, .svg) allowed"));
return;
}
}
let start_complete = frappe.cur_progress ? frappe.cur_progress.percent : 0;
var upload_with_filedata = function() {
let freader = new FileReader();
freader.onload = function() {
var dataurl = freader.result;
args.filedata = freader.result.split(",")[1];
args.file_size = fileobj.size;
frappe.upload._upload_file(fileobj, args, opts, dataurl);
};
freader.readAsDataURL(fileobj);
}
const file_not_big_enough = fileobj.size <= 24576;
if (opts.no_socketio || frappe.flags.no_socketio || file_not_big_enough) {
upload_with_filedata();
return;
}
frappe.socketio.uploader.start({
file: fileobj,
filename: args.filename,
is_private: args.is_private,
fallback: () => {
// if fails, use old filereader
upload_with_filedata();
},
callback: (data) => {
args.file_url = data.file_url;
frappe.upload._upload_file(fileobj, args, opts);
},
on_progress: (percent_complete) => {
let increment = (flt(percent_complete) / frappe.upload.total_files);
frappe.show_progress(__('Uploading'),
start_complete + increment);
}
});
},
upload_to_server: function(file, args, opts) {
if(opts.start) {
opts.start();
}
var ajax_args = {
"method": "uploadfile",
args: args,
callback: function(r) {
if(!r._server_messages) {
// msgbox.hide();
}
if(r.exc) {
// if no onerror, assume callback will handle errors
opts.onerror ? opts.onerror(r) : opts.callback(null, r);
frappe.hide_progress();
return;
}
var attachment = r.message;
opts.loopcallback && opts.loopcallback();
opts.callback && opts.callback(attachment, r);
$(document).trigger("upload_complete", attachment);
},
error: function(r) {
// if no onerror, assume callback will handle errors
opts.onerror ? opts.onerror(r) : opts.callback(null, null, r);
frappe.hide_progress();
return;
}
}
// copy handlers etc from opts
$.each(['queued', 'running', "progress", "always", "btn"], function(i, key) {
if(opts[key]) ajax_args[key] = opts[key];
});
return frappe.call(ajax_args);
},
get_string: function(dataURI) {
// remove filename
var parts = dataURI.split(',');
if(parts[0].indexOf(":")===-1) {
var a = parts[2];
} else {
var a = parts[1];
}
return decodeURIComponent(escape(atob(a)));
},
validate_max_file_size: function(file_size) {
var max_file_size = frappe.boot.max_file_size || 5242880;
if (file_size > max_file_size) {
// validate max file size
frappe.throw(__("File size exceeded the maximum allowed size of {0} MB", [max_file_size / 1048576]));
}
},
multifile_upload:function(fileobjs, args, opts={}) {
//loop through filenames and checkboxes then append to list
var fields = [];
for (var i =0,j = fileobjs.length;i<j;i++) {
var filename = fileobjs[i].name;
fields.push({'fieldname': 'label1', 'fieldtype': 'Heading', 'label': filename});
fields.push({'fieldname': filename+'_is_private', 'fieldtype': 'Check', 'label': 'Private', 'default': 1});
}
var d = new frappe.ui.Dialog({
'title': __('Make file(s) private or public?'),
'fields': fields,
primary_action: function(){
var i =0,j = fileobjs.length;
d.hide();
opts.loopcallback = function (){
if (i < j) {
args.is_private = d.fields_dict[fileobjs[i].name + "_is_private"].get_value();
frappe.upload.upload_file(fileobjs[i], args, opts);
i++;
}
};
opts.loopcallback();
}
});
d.show();
opts.confirm_is_private = 0;
},
create_gsuite_file: function(args, opts) {
return frappe.call({
type:'POST',
method: 'frappe.integrations.doctype.gsuite_templates.gsuite_templates.create_gsuite_doc',
args: args,
callback: function(r) {
var attachment = r.message;
opts.callback && opts.callback(attachment, r);
}
});
}
}
|
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {
"Content-Type": "application/json"
});
response.write(JSON.stringify({
"api": "data"
}));
response.end();
}).listen(3000);
|
module.exports = function (ctx, next) {
if (ctx.method === 'GET' && ctx.path === '/ping') {
ctx.body = 'pong'
}
}
|
'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.Base.extend({
prompting: function () {
this.log(yosay(
'Welcome to the ' + chalk.red('generator-react-app-boilerplate') + ' generator!'
));
var prompts = [{
type: 'input',
name: 'name',
message: 'Your project name',
//Defaults to the project's folder name if the input is skipped
default: this.appname
}];
return this.prompt(prompts).then(function (answers) {
this.props = answers;
this.log(answers.name);
}.bind(this));
},
writing: function () {
this.fs.copy(
this.templatePath('app'),
this.destinationPath(this.props.name+'/app')
);
this.fs.copy(
this.templatePath('configs'),
this.destinationPath(this.props.name+'/configs')
);
this.fs.copyTpl(
this.templatePath('_README'),
this.destinationPath(this.props.name+'/README.md'), {
name: this.props.name
}
);
this.fs.copy(
this.templatePath('babelrc'),
this.destinationPath(this.props.name+'/.babelrc')
);
this.fs.copy(
this.templatePath('eslintrc'),
this.destinationPath(this.props.name+'/.eslintrc')
);
this.fs.copy(
this.templatePath('gitignore'),
this.destinationPath(this.props.name+'/.gitignore')
);
this.fs.copyTpl(
this.templatePath('_package.json'),
this.destinationPath(this.props.name+'/package.json'), {
name: this.props.name
}
);
this.fs.copy(
this.templatePath('server.js'),
this.destinationPath(this.props.name+'/server.js')
);
this.fs.copy(
this.templatePath('user.yml.example'),
this.destinationPath(this.props.name+'/user.yml.example')
);
},
install: function () {
var elementDir = process.cwd() + '/' + this.props.name;
process.chdir(elementDir);
var prompts = [{
type: 'confirm',
name: 'install',
message: 'Would you like to enable install Dependencies?',
default: true
}];
return this.prompt(prompts).then(function (props) {
if(props.install){
this.installDependencies();
}
}.bind(this));
},
end: function() {
this.log("All Done!");
},
});
|
/**
* @module ngeo.routing.module
*/
import ngeoRoutingRoutingComponent from 'ngeo/routing/RoutingComponent.js';
import './routing.less';
/**
* @type {angular.Module}
*/
const exports = angular.module('ngeoRoutingModule', [
ngeoRoutingRoutingComponent.module.name
]);
export default exports;
|
const {suite} = require('suitape');
const snakeobj = require('./../index');
suite('snakeobj object', (test) => {
test('Returns same as input if input is not an object', (assert) => {
[1, 'hola', true, new Date()].forEach(input => {
const out = snakeobj(input);
assert('equal', out, input);
});
});
test('Snakeizes single property object', (assert) => {
const input = {lastName: 'last_name'};
const out = snakeobj(input);
Object.keys(out).forEach(key => assert('equal', key, out[key]));
});
test('Snakeizes multiple property object', (assert) => {
const input = {lastName: 'last_name', name: 'name', isFullName: 'is_full_name'};
const out = snakeobj(input);
Object.keys(out).forEach(key => assert('equal', key, out[key]));
});
test('Snakeizes nested objects', (assert) => {
const input = {person: {lastName: 'doe', job: {jobTitle: 'programmer'}}};
const out = snakeobj(input);
assert('equal', out.person.last_name, 'doe');
assert('equal', out.person.job.job_title, 'programmer');
});
test('Snakeizes nested in arrays objects', (assert) => {
const input = {persons: [{lastName: 'doe', job: {jobTitle: 'programmer'}}]};
const out = snakeobj(input);
assert('equal', out.persons[0].last_name, 'doe');
assert('equal', out.persons[0].job.job_title, 'programmer');
});
test('Snakeizes double nested in arrays objects', (assert) => {
const elem = {itemsInArray: [{item: 1}, {item: 2}]};
const elems = [Object.assign({}, elem), Object.assign({}, elem)];
const out = snakeobj({elems});
assert('equal', out.elems[0].items_in_array[0].item, 1);
assert('equal', out.elems[0].items_in_array[1].item, 2);
assert('equal', out.elems[1].items_in_array[0].item, 1);
assert('equal', out.elems[1].items_in_array[1].item, 2);
});
test('Snakeizes nested dot notation objects', (assert) => {
const input = {'person.lastName': 'doe'};
const out = snakeobj(input);
assert('equal', out['person.last_name'], 'doe');
});
test('Snakeizes all but excented keys', (assert) => {
const date = new Date();
const input = {person: {birthDate: {'$gt': date}}};
const out = snakeobj(input, ['$gt']);
assert('equal', out.person.birth_date['$gt'], date);
});
test('Snakeizes all but nested in arrays excented keys', (assert) => {
const date = new Date();
const input = {persons: [{birthDate: {$gt: date}}, {birthDate: {$lt: date}}]};
const out = snakeobj(input, ['$gt', '$lt']);
assert('equal', out.persons[0].birth_date['$gt'], date);
assert('equal', out.persons[1].birth_date['$lt'], date);
});
test('Snakeizes arrays', (assert) => {
const input = [{fooBar: 'baz'}, {hogeKage: 'piyo'}];
const out = snakeobj(input);
assert('equal', out[0].foo_bar, 'baz');
assert('equal', out[1].hoge_kage, 'piyo');
});
});
|
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var lang_1 = require('angular2/src/core/facade/lang');
var api_1 = require('angular2/src/core/render/api');
exports.ViewEncapsulation = api_1.ViewEncapsulation;
/**
* Declares the available HTML templates for an application.
*
* Each angular component requires a single `@Component` and at least one `@View` annotation. The
* `@View` annotation specifies the HTML template to use, and lists the directives that are active
* within the template.
*
* When a component is instantiated, the template is loaded into the component's shadow root, and
* the expressions and statements in the template are evaluated against the component.
*
* For details on the `@Component` annotation, see {@link ComponentMetadata}.
*
* ## Example
*
* ```
* @Component({
* selector: 'greet'
* })
* @View({
* template: 'Hello {{name}}!',
* directives: [GreetUser, Bold]
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
*/
var ViewMetadata = (function () {
function ViewMetadata(_a) {
var _b = _a === void 0 ? {} : _a, templateUrl = _b.templateUrl, template = _b.template, directives = _b.directives, pipes = _b.pipes, encapsulation = _b.encapsulation, styles = _b.styles, styleUrls = _b.styleUrls;
this.templateUrl = templateUrl;
this.template = template;
this.styleUrls = styleUrls;
this.styles = styles;
this.directives = directives;
this.pipes = pipes;
this.encapsulation = encapsulation;
}
ViewMetadata = __decorate([
lang_1.CONST(),
__metadata('design:paramtypes', [Object])
], ViewMetadata);
return ViewMetadata;
})();
exports.ViewMetadata = ViewMetadata;
//# sourceMappingURL=view.js.map |
document.write('<script src="js/goog/base.js"></script>');
document.write('<script src="js/deps.js"></script>');
document.write("<script>goog.require('AlignShop');</script>");
|
//================================================
// show_reply_thumbnails.js
// Author: @iihoshi
//================================================
(function ($, jn) {
var my_filename = 'show_reply_thumbnails.js';
// プラグイン情報 ここから
// プラグイン情報の初期化
if (!jn.pluginInfo)
jn.pluginInfo = {};
// プラグイン情報本体
jn.pluginInfo[my_filename.split('.')[0]] = {
'name' : {
'ja' : 'リプライサムネイル表示',
'en' : 'Show thumbnails in reply chain'
},
'author' : {
'en' : '@iihoshi'
},
'version' : '1.0.1',
'file' : my_filename,
'language' : ['en', 'ja'],
'last_update' : "2015/9/24",
'update_timezone' : '9',
'jnVersion' : '4.3.1.0',
'description' : {
'ja' : 'リプライにサムネイル画像があれば表示します。',
'en' : 'Shows thumbnails if a tweet in a reply chain has them.'
},
'updateinfo' : 'http://www.colorless-sight.jp/archives/JanetterPluginUpdateInfo.txt'
};
// プラグイン情報ここまで
if ((_Janetter_Window_Type != "main") && (_Janetter_Window_Type != "profile")) {
return;
}
function initForThumbnail() {
var orig_janetterThumbnail = $.fn.janetterThumbnail.toString();
var re_siblings = /_content\.siblings\('div\.tweet-thumb'\);$/m;
var re_find = /_content\.find\('div\.tweet-body /gm;
if (!re_siblings.test(orig_janetterThumbnail) ||
!re_find.test(orig_janetterThumbnail)) {
return false;
}
var replaced = orig_janetterThumbnail
.replace(re_siblings, "_content.children('div.tweet-thumb');")
.replace(re_find, "_content.find('div.tweet-reply-body ");
// console.log(replaced);
eval('$.fn.janetterThumbnailForReply = ' + replaced);
var tnMouseOverHandler = function () {
var $this = $(this),
tweet_reply = $this.parents('div.tweet-reply:first');
$this.unbind('mouseover', tnMouseOverHandler);
if (tweet_reply.length > 0) {
tweet_reply.janetterThumbnailForReply($this.attr('href'));
}
};
$.fn.janetterThumbnailForReplyEventSet = function () {
this.bind('mouseover', tnMouseOverHandler);
return this;
};
return true;
}
function initForExpandUrl() {
var orig_jn_expandUrl = jn.expandUrl.toString();
var re_tweet_content = /div\.tweet-content:first/m;
var re_janetterThumbnail = /\.janetterThumbnail(\W)/gm;
if (!re_tweet_content.test(orig_jn_expandUrl) ||
!re_janetterThumbnail.test(orig_jn_expandUrl)) {
return false;
}
var replaced = orig_jn_expandUrl
.replace(re_tweet_content, 'div.tweet-reply:first')
.replace(re_janetterThumbnail, '.janetterThumbnailForReply$1');
// console.log(replaced);
eval('var expandUrl = ' + replaced);
var euMouseOverHandler = function () {
var $this = $(this);
$this.unbind('mouseover', euMouseOverHandler);
expandUrl($this);
}
$.fn.janetterExpandUrlForReplyEventSet = function () {
this.bind('mouseover', euMouseOverHandler);
return this;
}
return true;
}
// 本プラグインの初期化処理(onInitializeDone 時)
function initOnInitialized() {
if (!initForThumbnail() || !initForExpandUrl()) {
new jn.msgdialog({
title: my_filename,
icon: '',
message: 'Sorry, ' + my_filename+ ' cannot be installed.',
buttons: [ janet.msg.ok ],
});
return;
}
var orig_generateReply = jn.generateReply;
jn.generateReply = function (item, is_default) {
var reply = orig_generateReply(item, is_default);
reply.append('<div class="tweet-thumb"/>');
var a = reply.find('.tweet-reply-body > p.text').children('a.link');
a.janetterExpandUrlForReplyEventSet();
if (jn.conf.disp_thumbnail == 'over')
a.janetterThumbnailForReplyEventSet();
else
reply.janetterThumbnailForReply(a);
return reply;
};
console.log(my_filename + ' has been initialized.');
}
if (jn.temp.initialized) {
// The original onInitializeDone() has already been called!
initOnInitialized();
} else {
var orig_onInitializeDone = jn.onInitializeDone;
jn.onInitializeDone = function () {
orig_onInitializeDone && orig_onInitializeDone.apply(this, arguments);
initOnInitialized();
};
}
})(jQuery, janet);
|
/**
* a tabbed pane based on a definition list
*/
var openmdao = (typeof openmdao === "undefined" || !openmdao ) ? {} : openmdao ;
openmdao.TabbedPane = function(id) {
jQuery("#"+id+" dl").css({
'margin': '0',
'width': '100%',
'position': 'relative'
});
jQuery("#"+id+" dt").css({
'top':'0',
'margin': '0',
'position': 'relative',
'float': 'left',
'display': 'block',
'width': '75px',
'height': '20px',
'text-align': 'center',
'border': '1px solid #222',
'background-color':'#6a6a6a',
'color': 'white',
'font-size': '14px'
});
jQuery("#"+id+" dd").css({
'margin': '0',
'position': 'absolute',
'left': '0',
'top': '25px',
'height': '100%',
'width': '100%',
'min-height': '400px',
'overflow' : 'auto'
});
jQuery("#"+id+" dd").hide();
jQuery("#"+id+" dt").click(function() {
var tgt = jQuery(this).attr("target");
jQuery("#"+id+" dd:visible").hide();
jQuery("#"+id+" dt.tab_here").removeClass("tab_here");
jQuery("#"+tgt).show();
jQuery(this).addClass("tab_here");
});
};
|
var mouseMoveControl = true;
function initializeChoropleth(data) {
var map = L.map('map2', {
center: [40, -120],
zoom: 4
})
createTileLayer(map)
var dataLayer = setEnumerationUnits(map, dataLayer, data)
return {
map: map,
dataLayer: dataLayer
// projection:projection,
// path:path,
}
}
function createTileLayer(map) {
var mapboxAccessToken = "pk.eyJ1IjoiY2F0aGVyaW5lc3RyZWlmZmVyIiwiYSI6ImNpa3BrOTVlaTEyNmZ0aWo3eDlyaThraGMifQ.bYUxm5s4cRD2iRGqvpNNBA"
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + mapboxAccessToken, {
id: 'mapbox.light',
attribution: '© <a href="http://mapbox.com/">Mapbox</a>; data source: Census Bureau'
}).addTo(map);
}
function setEnumerationUnits(map, dataLayer, data) {
var dataLayer = L.geoJson(data, {
className: "counties",
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.NAME + " County");
layer.on('mouseover', function(e) {
this.openPopup();
});
layer.on('mouseout', function(e) {
//this.closePopup();
});
}
}).addTo(map)
/*
//selection
var RADIUS = 500000;
var filterCircle = L.circle(L.latLng(40, -75), RADIUS, {
opacity: 1,
weight: 1,
fillOpacity: 0
}).addTo(map);
map.on('mousemove', function(e) {
filterCircle.setLatLng(e.latlng);
dataLayer.filter(function showAirport(feature) {
return e.latlng.distanceTo(L.latLng(
feature.geometry.coordinates[1],
feature.geometry.coordinates[0])) < RADIUS;
});
});
*/
dataLayer.setStyle(function(feature) {
return {
weight: .1,
color: 'black',
dashArray: '3',
opacity: 1,
fillOpacity: .7,
}
})
//var counties = map.selectAll()
// .attr("class","counties")
// .attr("fips", function(d){
// return d.properties.FIPS;
// })
// .attr("d", path)
// .style("fill", function(d){
// return choropleth(d.properties, bivariates);
// })
//add style descriptor to each path
//var desc = counties.append("desc")
// .text('{"stroke": "#000", "stroke-width": "0.5px"}');
return dataLayer
};
function updateChoropleth(choropleth, xTitle, yTitle, FIPSxData, xCol, FIPSyData, yCol, year, bivariate) {
errorControl01 = true;
colors = {}
colors[[-1, 1]] = window.getComputedStyle(document.getElementById("A1")).fill
colors[[0, 1]] = window.getComputedStyle(document.getElementById("B1")).fill
colors[[1, 1]] = window.getComputedStyle(document.getElementById("C1")).fill
colors[[-1, 0]] = window.getComputedStyle(document.getElementById("A2")).fill
colors[[0, 0]] = window.getComputedStyle(document.getElementById("B2")).fill
colors[[1, 0]] = window.getComputedStyle(document.getElementById("C2")).fill
colors[[-1, -1]] = window.getComputedStyle(document.getElementById("A3")).fill
colors[[0, -1]] = window.getComputedStyle(document.getElementById("B3")).fill
colors[[1, -1]] = window.getComputedStyle(document.getElementById("C3")).fill
choropleth.dataLayer.eachLayer(function(layer) {
xVal = FIPSxData[layer.feature.properties.FIPS]
yVal = FIPSyData[layer.feature.properties.FIPS]
lookupXCoord = -1 + (xVal >= xQuantile01) + (xVal >= xQuantile02)
lookupYCoord = -1 + (yVal >= yQuantile01) + (yVal >= yQuantile02)
layer.setStyle({
fillColor: colors[[lookupXCoord, lookupYCoord]]
});
layer.bindPopup(
"<p>"+layer.feature.properties.NAME + " County" + "</p><p>" + xTitle + ": " + xVal + "</p><p>" + yTitle + ": " + yVal + "</p> ");
})
}
|
/*
* To change this tealias: 'widget.listCompressorStopReason',mplate, choose Tools | Templates
* and open the template in the editor.
*/
Ext.define('sisprod.view.CompressorStopReason.ListCompressorStopReason', {
extend: 'sisprod.view.base.TabPanelGridItem',
alias: 'widget.listCompressorStopReason',
require: [
'sisprod.view.base.TabPanelGridItem'
],
options: {},
messages:{
idCompressorStopReasonHeader:"ID",
compressorStopReasonNameHeader:"Compressor Stop Reason",
compressorStopReasonAcronymHeader:"Acronym",
discountedHeader:"Is Discounted"
},
entityName: '',
title: '',
listTitle: 'Compressor Stop Reason List',
gridOptions: {
region: 'center'
},
initComponent: function(){
var me = this;
var storeName = sisprod.getApplication().getStoreName(me.entityName);
var modelName = sisprod.getApplication().getModelName(me.entityName);
me.gridOptions = {
title: me.listTitle,
entityName: me.entityName,
autoGenerationOptions:{
model: modelName,
autoGenerateColumns: true,
columnOptions: {
idCompressorStopReason:{header:me.messages.idCompressorStopReasonHeader},
compressorStopReasonName:{header:me.messages.compressorStopReasonNameHeader},
compressorStopReasonAcronym:{header:me.messages.compressorStopReasonAcronymHeader},
discounted:{header:me.messages.discountedHeader}
}
},
region: 'center',
store: me.controller.getStore(storeName)
};
me.callParent(arguments);
}
}); |
'use strict';
var seleniumServerJar =
'/usr/local/lib/node_modules/protractor' +
'/selenium/selenium-server-standalone-2.41.0.jar';
// A reference configuration file.
exports.config = {
// ----- How to setup Selenium -----
//
// There are three ways to specify how to use Selenium. Specify one of the
// following:
//
// 1. seleniumServerJar - to start Selenium Standalone locally.
// 2. seleniumAddress - to connect to a Selenium server which is already
// running.
// 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs.
//
// If the chromeOnly option is specified, no Selenium server will be started,
// and chromeDriver will be used directly (from the location specified in
// chromeDriver)
// The location of the selenium standalone server .jar file, relative
// to the location of this config. If no other method of starting selenium
// is found, this will default to
// node_modules/protractor/selenium/selenium-server...
seleniumServerJar: seleniumServerJar,
// The port to start the selenium server on, or null if the server should
// find its own unused port.
seleniumPort: null,
// Chromedriver location is used to help the selenium standalone server
// find chromedriver. This will be passed to the selenium jar as
// the system property webdriver.chrome.driver. If null, selenium will
// attempt to find chromedriver using PATH.
chromeDriver: './selenium/chromedriver',
// If true, only chromedriver will be started, not a standalone selenium.
// Tests for browsers other than chrome will not run.
chromeOnly: false,
// Additional command line options to pass to selenium. For example,
// if you need to change the browser timeout, use
// seleniumArgs: ['-browserTimeout=60'],
seleniumArgs: [],
// The address of a running selenium server. If specified, Protractor will
// connect to an already running instance of selenium. This usually looks like
// seleniumAddress: 'http://localhost:4444/wd/hub'
seleniumAddress: null,
// The timeout for each script run on the browser. This should be longer
// than the maximum time your application needs to stabilize between tasks.
allScriptsTimeout: 11000,
// ----- What tests to run -----
//
// Spec patterns are relative to the location of this config.
specs: [
'test/e2e/*-spec.js'
],
// Patterns to exclude.
exclude: [],
// ----- Capabilities to be passed to the webdriver instance ----
//
// For a full list of available capabilities, see
// https://code.google.com/p/selenium/wiki/DesiredCapabilities and
// https://code.google.com/p/selenium/source/browse/javascript/
// webdriver/capabilities.js
capabilities: {
'browserName': 'chrome'
},
// If you would like to run more than one instance of webdriver on the same
// tests, use multiCapabilities, which takes an array of capabilities.
// If this is specified, capabilities will be ignored.
multiCapabilities: [],
// ----- More information for your tests ----
//
// A base URL for your application under test. Calls to protractor.get()
// with relative paths will be prepended with this.
//baseUrl: 'http://localhost:3000',
baseUrl: 'http://localhost:3000',
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'body',
// A callback function called once protractor is ready and available, and
// before the specs are executed
// You can specify a file containing code to run by setting onPrepare to
// the filename string.
onPrepare: function() {
// At this point, global 'protractor' object will be set up, and jasmine
// will be available. For example, you can add a Jasmine reporter with:
// jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter(
// 'outputdir/', true, true));
},
// ----- The test framework -----
//
// Jasmine and Cucumber are fully supported as a test and assertion framework.
// Mocha has limited beta support. You will need to include your own
// assertion framework if working with mocha.
framework: 'jasmine',
// ----- Options to be passed to minijasminenode -----
//
// See the full list at https://github.com/juliemr/minijasminenode
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: false,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 30000
}
};
|
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
context: path.resolve(__dirname, '../src'),
entry: './index.js',
output: {
path: path.resolve(__dirname, '../dist'),
filename: 'index.js'
},
module: {
rules: [
{
test: /\.san$/,
use: 'san-loader'
},
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: 'url-loader'
},
{
test: /\.(woff2?|eot|ttf)(\?.*)?$/,
use: 'url-loader'
}
]
},
resolve: {
alias: {
'@': path.resolve(__dirname, '../src')
}
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '../src/template.html')
})
]
}
|
var install = function () {
var step = $('body').find('[data-step]').first();
var progress = $('.progress');
var label = $('#label');
label.text(step.data('step'));
$.ajax({
url: step.data('action'),
success: function () {
step.remove();
if ($('body').find('[data-step]').length) {
progress.attr('value', step.data('progress'));
install();
} else {
progress.attr('value', '100');
label.text('Almost done...');
window.location = APPLICATION_URL + '/installer/finish'
}
},
error: function () {
progress.addClass('progress-danger');
label.addClass('text-danger').text('There was an error. Please check your error logs.');
}
});
};
$(document).ready(function () {
install();
});
; |
import { BINARY_COLOR_SAND_90 } from 'binary-ui-styles';
import styled from 'styled-components/native';
export default styled.View`
align-items: center;
border-bottom-color: ${BINARY_COLOR_SAND_90};
border-bottom-width: 1px;
height: 50px;
justify-content: center;
overflow: hidden;
width: 100%;
`;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var chai = require("chai");
var Q = require("q");
var Defer = require("ts-promises/Defer");
var Tasks = require("../task/Tasks");
var TaskSet = require("../task/TaskSet");
var asr = chai.assert;
suite("TaskSet", function TaskSetTest() {
function createTaskRes1(res) {
return Q.resolve(res);
}
function createTaskRes2(res, waitMillis) {
var dfd = Q.defer();
setTimeout(function () { return dfd.resolve(res); }, waitMillis);
return dfd.promise;
}
function createTaskErr1(res) {
return Q.reject(res);
}
function createTaskErr2(res, waitMillis) {
var dfd = Q.defer();
setTimeout(function () { return dfd.reject(res); }, waitMillis);
return dfd.promise;
}
function startTasks(taskSet, namePrefix, resMsgPrefix, count) {
var tasks = [];
for (var i = 0; i < count; i++) {
var rr = Math.random() < 0.5 ? createTaskRes1(resMsgPrefix + i) : createTaskRes2(resMsgPrefix + i, Math.round(Math.random() * 10));
var t = taskSet.startTask(namePrefix + i, rr);
tasks.push(t);
}
return tasks;
}
test("README-example", function README_exampleTest(done) {
var taskSet = new TaskSet(null, function (name) { return console.log("success:", name); }, function (name) { return console.log("failure:", name); });
taskSet.startTask("task-1", Tasks.startTask("a", createTaskRes1("result a")).getPromise());
taskSet.startTask("task-2", createTaskRes1("result b"));
taskSet.startTask("task-3", createTaskRes1("error c"));
Q.all(taskSet.getPromises())
.then(function (results) { console.log("done:", results); done(); }, function (err) { console.error("error:", err); done(); });
});
test("task-set-function-and-promise-task-mix", function taskSetFunctionAndPromiseTaskMixTest(done) {
var taskSet = new TaskSet(null, null, null);
taskSet.startTask("task-1", createTaskRes1("result a"));
taskSet.startTask("task-2", Tasks.startTask("b", createTaskRes1("result b")).getPromise());
taskSet.startTask("task-3", createTaskRes1("result c"));
taskSet.startTask("task-4", createTaskErr1("error d"));
asr.equal(taskSet.getTasks().size, 4);
asr.equal(taskSet.getPromises().length, taskSet.getTasks().size);
Q.all(taskSet.getPromises()).done(function (results) {
done("unexpected success");
}, function (err) {
Q.all(taskSet.getPromises()).done(function (results) {
var allResults = taskSet.getCompletedTasks().map(function (t) { return t.task.getResult(); });
asr.deepEqual(allResults.sort(), ["result a", "result b", "result c"]);
asr.equal(err, "error d");
done();
}, function (err2) {
done("unexpected 2nd error");
});
});
});
test("task-set-success", function taskSetSuccessTest(done) {
// test success
var taskSet = new TaskSet();
var task1 = taskSet.startTask("task-res-1", createTaskRes1("success-1"));
var task2 = taskSet.startTask("task-res-2", createTaskRes2("success-2", 10));
Defer.when(taskSet.getPromises()).then(function (res) {
asr.deepEqual(res.sort(), ["success-1", "success-2"]);
asr.equal(task1.getResult(), "success-1");
asr.equal(task1.state, "COMPLETED");
asr.equal(task2.getResult(), "success-2");
asr.equal(task2.state, "COMPLETED");
done();
}, function (err) {
done("unexpected error");
});
});
test("task-set-failure", function taskSetFailureTest(done) {
// test success
var taskSet = new TaskSet();
var task1 = taskSet.startTask("task-res-1", createTaskRes1("success-1"));
var task2 = taskSet.startTask("task-res-2", createTaskRes2("success-2", 10));
var task3 = taskSet.startTask("task-err-1", createTaskErr1("error-1"));
var task4 = taskSet.startTask("task-err-2", createTaskErr2("error-2", 10));
Defer.when(taskSet.getPromises()).then(function (res) {
done("unexpected success");
}, function (err) {
asr.isTrue(err == "error-1" || err == "error-2");
done();
});
});
test("task-drop-completed", function taskSetDropCompleted(done) {
var taskSet = new TaskSet();
// test 4 tasks, limit 3, drop 25%
taskSet.maxCompletedTasks = 3;
taskSet.dropCompletedTasksPercentage = 0.25;
startTasks(taskSet, "task-res-", "success-", 4);
Defer.when(taskSet.getPromises()).then(function (res) {
asr.equal(taskSet.getCompletedTasks().length, 2);
taskSet.clearCompletedTasks();
}).then(function () {
// test 6 tasks, limit 5, drop 60%
taskSet.maxCompletedTasks = 5;
taskSet.dropCompletedTasksPercentage = 0.6;
startTasks(taskSet, "task-res-", "success-", 6);
return Defer.when(taskSet.getPromises());
}).then(function (res) {
asr.equal(taskSet.getCompletedTasks().length, 2);
taskSet.clearCompletedTasks();
done();
}, function (err) {
done("unexpected error");
});
});
});
|
/*
name: MapTile.js
des: 地图全屏操作
date: 2016-06-02
author: liulin
修改为用js加载
*/
ES.MapControl.ESMapFull = ES.Evented.extend({
oOption: {
// 加载全屏按钮容器
cSelfDiv: 'ex-map-full',
// 父级容器
acParentDivClass: [
'ex-layout-maptool',
'ex-theme-maptool',
'ex-map-top',
'ex-map-right'
],
className: '',
title: '地图全屏',
},
oUIConfig: {
div: {
'class': 'ex-maptool-box ex-map-full',
i: {'class': 'ec-icon-expand'},
html: ' 全屏'
}
},
// 构造函数
initialize: function (oMapBase, options) {
ES.setOptions(this, options);
// 获得地图控件
this._oMapBase = oMapBase;
this._oMap = oMapBase._oMap;
//图层
this._layers = {};
//记录最近一次的div Z-index
this._lastZIndex = 0;
this._oContainer = $('.' + this.oOption.acParentDivClass.join('.')).eq(0);
//var aoLayer = this._oMapBase.getBaseLayers();
// 设置父级容器的事件
this.setParentEvent();
this.initUI();
},
// 设置父级容器的事件
setParentEvent: function () {
// 屏蔽事件
//L.DomEvent.addListener(this._oContainer.get(0), 'dblclick', L.DomEvent.stopPropagation);
//L.DomEvent.addListener(this._oContainer.get(0), 'mousemove', L.DomEvent.stopPropagation);
//L.DomEvent.addListener(this._oContainer.get(0), 'mousewheel', L.DomEvent.stopPropagation);
},
//加载工具事件,初始化工具栏
initUI: function () {
ES.initTag(this._oContainer, this.oUIConfig);
this.initToolEvent();
},
//初始化工具栏事件
initToolEvent: function () {
//地图全屏按钮
$('.' + this.oOption.cSelfDiv).bind('click', function () {
if (!($.AMUI.fullscreen.isFullscreen)) {
$('body').addClass('map_full');
$(this).html('<i class="ec-icon-compress"></i> 恢复');
} else {
$('body').removeClass('map_full');
$(this).html('<i class="ec-icon-expand"></i> 全屏');
}
$.AMUI.fullscreen.toggle();
});
},
});
|
'use strict'
let React = require('react'),
ReactDOM = require('react-dom'),
$ = require('jquery'),
d3 = require('d3'),
storage = window.localStorage,
ProgressBar = require('react-progress-bar-plus'),
CheckOptionBox = require('../components/check-option-box'),
CandleStickStockScaleChartWithVolumeHistogramV3 = require('../components/candle-stick-stock'),
alert = require('../components/alert'),
PageHeader = require('../components/page-header');
import { Button, Input, Modal, Grid, Row, Col, Glyphicon, Panel } from 'react-bootstrap';
let parseDate = d3.time.format("%Y-%m-%d").parse;
let formatDate = d3.time.format("%Y-%m-%d");
// 筛选选项区域
const FilterOptionsBox = React.createClass({
// 过滤股票按钮点击事件
handleFilterClick: function handleFilterClick(event) {
this.setState({
percent: 0,
autoIncrement: true,
intervalTime: 100
});
$.ajax({
url: this.props.filterUrl,
dataType: 'json',
data: {
dealDate: this.state.dealDate,
stockId: this.state.stockId,
rsi: this.state.rsi,
top: this.state.top,
priceScale: this.state.priceScale,
crossStar: this.state.crossStar,
crossStarCount: this.state.crossStarCount,
inconUpPriceScale: this.state.inconUpPriceScale
},
cache: false,
success: function(data) {
this.setState({'filteredData': data});
this.props.onFilterClick(data);
this.setState({
percent: -1
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
this.setState({
percent: -1
});
}.bind(this)
});
},
// 保存股票模型按钮点击事件
handleSaveModuleClick: function handleSaveModuleClick(event) {
this.setState({
percent: 0,
autoIncrement: true,
intervalTime: 100
});
alert.clearMessage();
if (storage.getItem('user.token')) {
$.ajax({
url: this.props.saveModuleUrl,
type: 'POST',
dataType: 'json',
headers: {authorization: storage.getItem('user.token')},
data: {
moduleId: this.state.moduleId,
options: JSON.stringify({
dealDate: this.state.dealDate,
stockId: this.state.stockId,
rsi: this.state.rsi,
top: this.state.top,
priceScale: this.state.priceScale,
crossStar: this.state.crossStar,
crossStarCount: this.state.crossStarCount,
inconUpPriceScale: this.state.inconUpPriceScale
}
)},
cache: false,
success: function(data) {
if (data.ok) {
alert.setMessage('info', '保存成功');
this.setState({moduleId: data.result})
} else {
alert.setMessage('error', data.message);
}
this.setState({
percent: -1
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
this.setState({
percent: -1
});
}.bind(this)
});
} else {
this.setState({
percent: -1
});
alert.setMessage('error', '请先登录');
}
},
// 模拟买入按钮点击事件
handleMockBuyClick: function handleMockBuyClick(event) {
this.setState({
percent: 0,
autoIncrement: true,
intervalTime: 100
});
$.ajax({
url: this.props.mockBuyUrl,
dataType: 'json',
type: 'POST',
data: {jsonData: JSON.stringify(this.state)},
cache: false,
success: function(data) {
console.log(data);
let diffPercent = (Math.round(data.diff / data.buyAmount * 10000) / 100);
this.setState({
showBuyResult: true,
buyAmount: data.buyAmount,
holdDay: data.holdDay,
saleAmount: data.saleAmount,
diff: data.diff,
diffPercent: diffPercent,
percent: -1
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
this.setState({
percent: -1
});
}.bind(this)
});
},
handleDealDateChange: function(data) {
this.setState({dealDate: data});
},
handleStockIdChange: function(data) {
this.setState({stockId: data});
},
handleTopChange: function(data) {
this.setState({top: data});
},
handleRSIChange: function(data) {
this.setState({rsi: data});
},
handleHoldDateChange: function(data) {
this.setState({holdDay: data});
},
handlePriceScaleChange: function(data) {
this.setState({priceScale: data});
},
handleCrossStarChange: function(data) {
this.setState({crossStar: data});
},
handleCrossStarCountChange: function(data) {
this.setState({crossStarCount: data});
},
handleInconUpPriceScaleChange: function(data) {
this.setState({inconUpPriceScale: data});
},
componentDidMount() {
if (this.state.moduleId) {
this.setState({
percent: 0,
autoIncrement: true,
intervalTime: 100
});
$.ajax({
url: this.props.getModuleUrl + this.state.moduleId,
dataType: 'json',
headers: {authorization: storage.getItem('user.token')},
cache: false,
success: function(result) {
if (result.ok) {
if (this.isMounted()) {
this.setState(result.data.options);
}
} else {
alert.setMessage('error', result.message);
}
this.setState({
percent: -1,
initDone: true
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
this.setState({
percent: -1,
initDone: true
});
}.bind(this)
});
} else {
this.setState({initDone: true});
}
},
getInitialState: function() {
return {
initDone: false,
moduleId: this.props.moduleId,
showBuyResult: false,
buyAmount: 0,
holdDay: 0,
saleAmount: 0,
diff: 0,
percent: -1,
autoIncrement: false,
intervalTime: 200
};
},
close() {
this.setState({ showBuyResult: false });
},
open() {
this.setState({ showBuyResult: true });
},
render: function() {
if (this.state.initDone) {
return (
<Grid>
<ProgressBar percent={this.state.percent}
autoIncrement={this.state.autoIncrement}
intervalTime={this.state.intervalTime} />
<alert.Alert />
<PageHeader.PageHeader title='创建模型' />
<Row className="show-grid">
<Col lg={12}>
<h4>股票筛选</h4>
</Col>
</Row>
<Panel collapsible defaultExpanded header="基础设置">
<CheckOptionBox label="指定交易日期" holder="请输入交易日期"
defaultChecked={false}
defaultValue={this.state.dealDate}
help="如果不输入则默认为当前日期。样例:2015-01-01"
onContentChange={this.handleDealDateChange} />
<CheckOptionBox label="指定股票代码" holder="请输入股票代码"
defaultChecked={false}
defaultValue={this.state.stockId}
help="样例:000001"
onContentChange={this.handleStockIdChange} />
<CheckOptionBox label="龙头股"
holder="请输入日期范围、涨幅和取板块头X个股票"
defaultChecked={false}
defaultValue={this.state.top}
help="样例:2015-12-01,2015-12-31,7,3"
onContentChange={this.handleTopChange} />
</Panel>
<Panel collapsible defaultExpanded header="涨跌相关">
<CheckOptionBox label="连续涨跌规律"
holder="请输入连续涨跌规律"
defaultChecked={false}
defaultValue={this.state.priceScale}
help="样例:2015-12-01,2015-12-31,7,7,-7(解释:从2015-12-01日到2015-12-31日,其中有一天涨幅超过7%,随后第二天涨幅超过7%,随后第三天[跌]幅超过7%)"
onContentChange={this.handlePriceScaleChange} />
<CheckOptionBox label="间断上涨规律"
holder="请输入间断上涨规律。"
defaultChecked={false}
defaultValue={this.state.inconUpPriceScale}
help="样例:2015-12-01,2015-12-31,2,7(解释:从2015-12-01日到2015-12-31日,出现2次上涨幅度在7%以上的股票)"
onContentChange={this.handleInconUpPriceScaleChange} />
</Panel>
<Panel collapsible defaultExpanded header="十字星相关">
<CheckOptionBox label="十字星定义" holder="请输入十字星定义"
defaultChecked={false}
defaultValue={this.state.crossStar}
help="样例:2015-11-01,2015-11-30,0.5,1,1(解释:从2015-12-01日到2015-12-31日,开盘价和收盘价之差在0.5%以内,上影线在1%以上,下影线在1%以上)"
onContentChange={this.handleCrossStarChange} />
<CheckOptionBox label="间断出现十字星数量" holder="请输入间断十字星数量"
defaultChecked={false}
defaultValue={this.state.crossStarCount}
help="样例:3(解释:大于等于3个十字星,不输入则默认为1)"
onContentChange={this.handleCrossStarCountChange} />
</Panel>
<Panel collapsible defaultExpanded header="指数相关">
<CheckOptionBox label="RSI1" holder="请输入范围"
defaultChecked={false}
defaultValue={this.state.rsi}
help="样例:>80 or <=20"
onContentChange={this.handleRSIChange} />
</Panel>
<Button bsStyle="default" onClick={this.handleFilterClick}>
<Glyphicon glyph="filter" /> 过滤股票
</Button>
<Button bsStyle="danger" onClick={this.handleSaveModuleClick} style={{marginLeft: 10}}>
<Glyphicon glyph="save-file" /> 保存模型
</Button>
<Row className="show-grid">
<Col lg={12}>
<hr />
<h4>模拟买入筛选股票</h4>
</Col>
</Row>
<CheckOptionBox label="持有天数" holder="请输入持有天数(如果不输入则默认为7天)。样例:7"
defaultChecked={false}
onContentChange={this.handleHoldDateChange} />
<Button bsStyle="danger" onClick={this.handleMockBuyClick}>
<Glyphicon glyph="yen" /> 模拟买入
</Button>
<hr />
<Modal show={this.state.showBuyResult} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>模拟买入结果</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>您的成绩如下:</p>
<p>每股各买入100股,总买入金额为:{this.state.buyAmount}元</p>
<p>持有{this.state.holdDay}天后卖出,总卖出金额为:{this.state.saleAmount}元</p>
<p>结果为:{this.state.diff}元 / {this.state.diffPercent}%</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>关闭</Button>
</Modal.Footer>
</Modal>
</Grid>
);
}
return (
<Grid>
<ProgressBar percent={this.state.percent}
autoIncrement={this.state.autoIncrement}
intervalTime={this.state.intervalTime} />
<alert.Alert />
</Grid>
);
}
});
// 股票列表
import {Table, Column, Cell} from 'fixed-data-table';
const DateCell = ({rowIndex, data, col}) => (
<Cell>
{data[rowIndex][col]}
</Cell>
);
const TextCell = ({rowIndex, data, col}) => (
<Cell>
{data[rowIndex][col]}
</Cell>
);
const StockTable = React.createClass({
handleNextTransDayChange: function(data) {
this.setState({nextTransDay: data});
},
getLastTransData: function(needShowMockBuyResult) {
if (this.state.selectedStockId) {
let nextTransDate = new Date();
// 检查是否指定随后天数,没有就默认为当天
if (this.state.nextTransDay) {
nextTransDate = new Date((new Date(parseDate(this.state.selectedDealDate))).getTime() +
this.state.nextTransDay * 24 * 60 * 60 * 1000);
}
this.setState({
percent: 0,
autoIncrement: true,
intervalTime: 100
});
$.ajax({
url: "/api/stock/transactions",
dataType: 'json',
data: {
dealDate: formatDate(nextTransDate),
stockId: this.state.selectedStockId
},
cache: false,
success: function(data) {
data.forEach((d, i) => {
d.date = new Date(parseDate(d.date).getTime());
d.open = +d.open;
d.high = +d.high;
d.low = +d.low;
d.close = +d.close;
d.volume = (+d.volume) / 100; // 需要将股转成手
// console.log(d);
});
/* change the type from hybrid to svg to compare the performance between svg and canvas */
ReactDOM.render(
<CandleStickStockScaleChartWithVolumeHistogramV3 data={data} type="hybrid" />,
document.getElementById("chart"));
if (needShowMockBuyResult) {
console.log(data[data.length - 1]);
console.log(this.state.selectedClose);
let buyAmount = Math.round(this.state.selectedClose * 100);
let saleAmount = data[data.length - 1].close * 100;
let diff = saleAmount - buyAmount;
let diffPercent = (Math.round(diff / buyAmount * 10000) / 100);
let holdDay = Math.ceil((nextTransDate - parseDate(this.state.selectedDealDate)) /
(1000 * 3600 * 24));
this.setState({
showBuyResult: true,
buyAmount: buyAmount,
holdDay: holdDay,
saleAmount: saleAmount,
diff: diff,
diffPercent: diffPercent,
percent: -1
});
}
}.bind(this),
error: function(xhr, status, err) {
console.error("/api/stock/transactions", status, err.toString());
this.setState({
percent: -1
});
}.bind(this)
});
}
},
handleMockBuyClick: function() {
this.getLastTransData(true);
},
handleGetLastTransDataClick: function() {
this.getLastTransData(false);
},
getInitialState: function() {
return {
selectedStockId: null, selectedStockName: "", selectedDealDate: null,
showBuyResult: false, buyAmount: 0, holdDay: 0, saleAmount: 0, diff: 0
};
},
close() {
this.setState({ showBuyResult: false });
},
open() {
this.setState({ showBuyResult: true });
},
render: function() {
let self = this;
return (
<Grid>
<ProgressBar percent={this.state.percent}
autoIncrement={this.state.autoIncrement}
intervalTime={this.state.intervalTime} />
<Row>
<Col lg={12}>
<Table
rowHeight={50}
rowsCount={this.props.data.length}
width={1000}
height={400}
headerHeight={50}
rowClassNameGetter={function(rowIndex) { return ''; }}
onRowClick={
function(e, rowIndex) {
self.setState({
selectedStockId: self.props.data[rowIndex].stock_id,
selectedStockName: self.props.data[rowIndex].stock_name,
selectedDealDate: self.props.data[rowIndex].date,
selectedClose: self.props.data[rowIndex].close,
percent: 0,
autoIncrement: true,
intervalTime: 100
});
$.ajax({
url: "/api/stock/transactions",
dataType: 'json',
data: {
dealDate: self.props.data[rowIndex].date,
stockId: self.props.data[rowIndex].stock_id
},
cache: false,
success: function(data) {
data.forEach((d, i) => {
d.date = new Date(parseDate(d.date).getTime());
d.open = +d.open;
d.high = +d.high;
d.low = +d.low;
d.close = +d.close;
d.volume = (+d.volume) / 100; // 需要将股转成手
// console.log(d);
});
console.log(data);
/* change the type from hybrid to svg to compare the performance between svg and canvas */
ReactDOM.render(
<CandleStickStockScaleChartWithVolumeHistogramV3 data={data} type="hybrid" />,
document.getElementById("chart"));
self.setState({
percent: -1
});
}.bind(this),
error: function(xhr, status, err) {
console.error("/api/stock/transactions", status, err.toString());
self.setState({
percent: -1
});
}.bind(this)
});
}
}
{...this.props}>
<Column
header={<Cell>股票代码</Cell>}
cell={<TextCell data={this.props.data} col="stock_id" />}
width={100}
/>
<Column
header={<Cell>股票名称</Cell>}
cell={<TextCell data={this.props.data} col="stock_name" />}
width={100}
/>
<Column
header={<Cell>所属行业</Cell>}
cell={<TextCell data={this.props.data} col="industry" />}
width={100}
/>
<Column
header={<Cell>统计最后日期</Cell>}
cell={<DateCell data={this.props.data} col="date" />}
width={140}
/>
<Column
header={<Cell>收盘价</Cell>}
cell={<TextCell data={this.props.data} col="close" />}
width={100}
/>
<Column
header={<Cell>RSI1</Cell>}
cell={<TextCell data={this.props.data} col="rsi1" />}
width={100}
/>
<Column
header={<Cell>RSI2</Cell>}
cell={<TextCell data={this.props.data} col="rsi2" />}
width={100}
/>
<Column
header={<Cell>RSI3</Cell>}
cell={<TextCell data={this.props.data} col="rsi3" />}
width={100}
/>
</Table>
<small>* 点击股票可以查看该股票的K线图</small>
</Col>
</Row>
<Row>
<Col lg={12}>
<h3>{this.state.selectedStockName}</h3>
<div id="chart" ></div>
<hr />
<CheckOptionBox label="查看随后X天走势"
holder="请输入想要看的随后走势天数(如果不输入则默认为到当前日期)。样例:7"
defaultChecked={false}
onContentChange={this.handleNextTransDayChange} />
<Button onClick={this.handleGetLastTransDataClick}>
<Glyphicon glyph="search" /> 查看随后走势
</Button>
<Button bsStyle="danger" onClick={this.handleMockBuyClick} style={{marginLeft: 10}}>
<Glyphicon glyph="yen" /> 查看随后走势并模拟买入
</Button>
</Col>
</Row>
<Modal show={this.state.showBuyResult} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>模拟买入结果</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>您的成绩如下:</p>
<p>买入【{this.state.selectedStockName}】100股,买入金额为:{this.state.buyAmount}元</p>
<p>持有{this.state.holdDay}天后卖出,卖出金额为:{this.state.saleAmount}元</p>
<p>结果为:{this.state.diff}元 / {this.state.diffPercent}%</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>关闭</Button>
</Modal.Footer>
</Modal>
</Grid>
);
}
});
const FilterStockBox = React.createClass({
handleFilterClick: function(data) {
this.setState({data: data});
},
getInitialState: function() {
return {
data: []
};
},
render: function() {
return (
<div className="filterStockBox">
<FilterOptionsBox
moduleId={this.props.moduleId}
getModuleUrl="/api/module/"
filterUrl="/api/stock/filter"
mockBuyUrl="/api/stock/mockBuy"
saveModuleUrl="/api/module/save"
onFilterClick={this.handleFilterClick} />
<Row>
<Col lg={12}>
<StockTable data={this.state.data} />
</Col>
</Row>
</div>
);
}
});
const CreateModule = React.createClass({
render: function() {
return (
<FilterStockBox moduleId={this.props.params.moduleId} />
);
}
});
module.exports = CreateModule; |
/**
* Tom Select v1.7.5
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.js')) :
typeof define === 'function' && define.amd ? define(['../../tom-select'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TomSelect));
}(this, (function (TomSelect) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var TomSelect__default = /*#__PURE__*/_interopDefaultLegacy(TomSelect);
/**
* Plugin: "input_autogrow" (Tom Select)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*/
TomSelect__default['default'].define('no_backspace_delete', function () {
var self = this;
var orig_deleteSelection = self.deleteSelection;
this.hook('instead', 'deleteSelection', function () {
if (self.activeItems.length) {
return orig_deleteSelection.apply(self, arguments);
}
return false;
});
});
})));
//# sourceMappingURL=no_backspace_delete.js.map
|
export default {
"_id": "60228e64f2e20ca84010999a",
"type": "form",
"components": [{
"label": "Form",
"tableView": true,
"useOriginalRevision": false,
"components": [{
"label": "Text Field Child",
"tableView": true,
"key": "textFieldChild",
"type": "textfield",
"input": true
}, {
"label": "Time Child",
"inputType": "text",
"tableView": true,
"key": "timeChild",
"type": "time",
"input": true,
"inputMask": "99:99"
}, {
"title": "Panel Child",
"collapsible": false,
"key": "panelChild",
"type": "panel",
"label": "Panel",
"input": false,
"tableView": false,
"components": [{
"label": "Number Inside Child Panel",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "numberInsideChildPanel",
"type": "number",
"input": true
}]
}, {
"label": "Data Grid Child",
"reorder": false,
"addAnotherPosition": "bottom",
"layoutFixed": false,
"enableRowGroups": false,
"initEmpty": false,
"tableView": false,
"defaultValue": [{}],
"key": "dataGridChild",
"type": "datagrid",
"input": true,
"components": [{
"label": "Text Area Inside Child DataGrid",
"autoExpand": false,
"tableView": true,
"key": "textAreaInsideChildDataGrid",
"type": "textarea",
"input": true
}]
}],
"key": "form",
"type": "form",
"input": true,
"form": "6034b4ef914866a81c060533"
},
{
"label": "Text Field",
"tableView": true,
"key": "textField",
"type": "textfield",
"input": true
}, {
"label": "Text Area",
"autoExpand": false,
"tableView": true,
"key": "textArea",
"type": "textarea",
"input": true
}, {
"label": "Number",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "number",
"type": "number",
"input": true
}, {
"label": "Password",
"tableView": false,
"key": "password",
"type": "password",
"input": true,
"protected": true
}, {
"label": "Checkbox",
"tableView": false,
"key": "checkbox",
"type": "checkbox",
"input": true
}, {
"label": "Select Boxes",
"optionsLabelPosition": "right",
"tableView": false,
"values": [{
"label": "a",
"value": "a",
"shortcut": ""
}, {
"label": "b",
"value": "b",
"shortcut": ""
}, {
"label": "c",
"value": "c",
"shortcut": ""
}],
"validate": {
"onlyAvailableItems": false
},
"key": "selectBoxes",
"type": "selectboxes",
"input": true,
"inputType": "checkbox",
}, {
"label": "Select",
"widget": "choicesjs",
"tableView": true,
"data": {
"values": [{
"label": "A",
"value": "a"
}, {
"label": "B",
"value": "b"
}, {
"label": "C",
"value": "c"
}]
},
"selectThreshold": 0.3,
"validate": {
"onlyAvailableItems": false
},
"key": "select",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}, {
"label": "Radio",
"optionsLabelPosition": "right",
"inline": false,
"tableView": false,
"values": [{
"label": "a",
"value": "a",
"shortcut": ""
}, {
"label": "b",
"value": "b",
"shortcut": ""
}, {
"label": "c",
"value": "c",
"shortcut": ""
}],
"validate": {
"onlyAvailableItems": false
},
"key": "radio",
"type": "radio",
"input": true
}, {
"label": "Email",
"tableView": true,
"key": "email",
"type": "email",
"input": true
}, {
"label": "Url",
"tableView": true,
"key": "url",
"type": "url",
"input": true
}, {
"label": "Phone Number",
"tableView": true,
"key": "phoneNumber",
"type": "phoneNumber",
"input": true
}, {
"label": "Tags",
"tableView": false,
"key": "tags",
"type": "tags",
"input": true
}, {
"label": "Address",
"tableView": false,
"provider": "nominatim",
"key": "address",
"type": "address",
"providerOptions": {
"params": {
"autocompleteOptions": {}
}
},
"input": true,
"components": [{
"label": "Address 1",
"tableView": false,
"key": "address1",
"type": "textfield",
"input": true,
"customConditional": "show = _.get(instance, 'parent.manualMode', false);"
}, {
"label": "Address 2",
"tableView": false,
"key": "address2",
"type": "textfield",
"input": true,
"customConditional": "show = _.get(instance, 'parent.manualMode', false);"
}, {
"label": "City",
"tableView": false,
"key": "city",
"type": "textfield",
"input": true,
"customConditional": "show = _.get(instance, 'parent.manualMode', false);"
}, {
"label": "State",
"tableView": false,
"key": "state",
"type": "textfield",
"input": true,
"customConditional": "show = _.get(instance, 'parent.manualMode', false);"
}, {
"label": "Country",
"tableView": false,
"key": "country",
"type": "textfield",
"input": true,
"customConditional": "show = _.get(instance, 'parent.manualMode', false);"
}, {
"label": "Zip Code",
"tableView": false,
"key": "zip",
"type": "textfield",
"input": true,
"customConditional": "show = _.get(instance, 'parent.manualMode', false);"
}]
}, {
"label": "Date / Time",
"tableView": false,
"enableMinDateInput": false,
"datePicker": {
"disableWeekends": false,
"disableWeekdays": false
},
"enableMaxDateInput": false,
"key": "dateTime",
"type": "datetime",
"input": true,
"widget": {
"type": "calendar",
"displayInTimezone": "viewer",
"locale": "en",
"useLocaleSettings": false,
"allowInput": true,
"mode": "single",
"enableTime": true,
"noCalendar": false,
"format": "yyyy-MM-dd hh:mm a",
"hourIncrement": 1,
"minuteIncrement": 1,
"time_24hr": false,
"minDate": null,
"disableWeekends": false,
"disableWeekdays": false,
"maxDate": null
}
}, {
"label": "Day",
"hideInputLabels": false,
"inputsLabelPosition": "top",
"useLocaleSettings": false,
"tableView": false,
"fields": {
"day": {
"hide": false
},
"month": {
"hide": false
},
"year": {
"hide": false
}
},
"key": "day",
"type": "day",
"input": true,
"defaultValue": "00/00/0000"
}, {
"label": "Time",
"tableView": true,
"key": "time",
"type": "time",
"input": true,
"inputMask": "99:99"
}, {
"label": "Currency",
"mask": false,
"spellcheck": true,
"tableView": false,
"currency": "USD",
"inputFormat": "plain",
"key": "currency",
"type": "currency",
"input": true,
"delimiter": true
}, {
"label": "Survey",
"tableView": false,
"questions": [{
"label": "Question 1",
"value": "question1"
}, {
"label": "Question 2",
"value": "question2"
}],
"values": [{
"label": "yes",
"value": "yes"
}, {
"label": "no",
"value": "no"
}],
"key": "survey",
"type": "survey",
"input": true
}, {
"label": "Signature",
"tableView": false,
"key": "signature",
"type": "signature",
"input": true
}, {
"label": "HTML",
"attrs": [{
"attr": "",
"value": ""
}],
"content": "some test HTML content",
"refreshOnChange": false,
"key": "html",
"type": "htmlelement",
"input": false,
"tableView": false
}, {
"html": "<p>some text content</p>",
"label": "Content",
"refreshOnChange": false,
"key": "content",
"type": "content",
"input": false,
"tableView": false
}, {
"label": "Columns",
"columns": [{
"components": [{
"label": "Number Column",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "numberColumn",
"type": "number",
"input": true,
"hideOnChildrenHidden": false
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0,
"size": "md"
}, {
"components": [{
"label": "Text Field Column",
"tableView": true,
"key": "textFieldColumn",
"type": "textfield",
"input": true,
"hideOnChildrenHidden": false
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0,
"size": "md"
}],
"key": "columns",
"type": "columns",
"input": false,
"tableView": false
}, {
"legend": "test legend",
"key": "fieldset",
"type": "fieldset",
"label": "test legend",
"input": false,
"tableView": false,
"components": [{
"label": "Number Fieldset",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "numberFieldset",
"type": "number",
"input": true
}]
}, {
"collapsible": false,
"key": "panel",
"type": "panel",
"label": "Panel",
"input": false,
"tableView": false,
"components": [{
"label": "Number Panel",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "numberPanel",
"type": "number",
"input": true
}]
}, {
"label": "Table",
"cellAlignment": "left",
"key": "table",
"type": "table",
"numRows": 2,
"numCols": 2,
"input": false,
"tableView": false,
"rows": [
[{
"components": [{
"label": "Select Table",
"widget": "choicesjs",
"tableView": true,
"data": {
"values": [{
"label": "one",
"value": "one"
}, {
"label": "two",
"value": "two"
}]
},
"selectThreshold": 0.3,
"validate": {
"onlyAvailableItems": false
},
"key": "selectTable",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}]
}, {
"components": [{
"label": "Checkbox Table",
"tableView": false,
"key": "checkboxTable",
"type": "checkbox",
"input": true,
"defaultValue": false
}]
}],
[{
"components": [{
"label": "Date / Time Table",
"tableView": false,
"enableMinDateInput": false,
"datePicker": {
"disableWeekends": false,
"disableWeekdays": false
},
"enableMaxDateInput": false,
"key": "dateTimeTable",
"type": "datetime",
"input": true,
"widget": {
"type": "calendar",
"displayInTimezone": "viewer",
"locale": "en",
"useLocaleSettings": false,
"allowInput": true,
"mode": "single",
"enableTime": true,
"noCalendar": false,
"format": "yyyy-MM-dd hh:mm a",
"hourIncrement": 1,
"minuteIncrement": 1,
"time_24hr": false,
"minDate": null,
"disableWeekends": false,
"disableWeekdays": false,
"maxDate": null
}
}]
}, {
"components": [{
"label": "Currency Table",
"mask": false,
"spellcheck": true,
"tableView": false,
"currency": "USD",
"inputFormat": "plain",
"key": "currencyTable",
"type": "currency",
"input": true,
"delimiter": true
}]
}]
]
}, {
"label": "Tabs",
"components": [{
"label": "Tab 1",
"key": "tab1",
"components": [{
"label": "Number Tab",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "numberTab",
"type": "number",
"input": true
}]
}, {
"label": "Tab 2",
"key": "tab2",
"components": [{
"label": "Text Field Tab",
"tableView": true,
"key": "textFieldTab",
"type": "textfield",
"input": true
}]
}],
"key": "tabs",
"type": "tabs",
"input": false,
"tableView": false
}, {
"label": "Well",
"key": "well",
"type": "well",
"input": false,
"tableView": false,
"components": [{
"label": "Text Field Well",
"tableView": true,
"key": "textFieldWell",
"type": "textfield",
"input": true
}]
}, {
"label": "Hidden",
"key": "hidden",
"type": "hidden",
"input": true,
"tableView": false
}, {
"label": "Container",
"tableView": false,
"key": "container",
"type": "container",
"hideLabel": false,
"input": true,
"components": [{
"label": "Text Field Container",
"tableView": true,
"key": "textFieldContainer",
"type": "textfield",
"input": true
}]
}, {
"label": "Data Map",
"tableView": false,
"key": "dataMap",
"type": "datamap",
"input": true,
"valueComponent": {
"type": "textfield",
"key": "key",
"label": "Value",
"input": true,
"hideLabel": true,
"tableView": true
}
}, {
"label": "Data Grid",
"reorder": false,
"addAnotherPosition": "bottom",
"layoutFixed": false,
"enableRowGroups": false,
"initEmpty": false,
"tableView": false,
"defaultValue": [{}],
"key": "dataGrid",
"type": "datagrid",
"input": true,
"components": [{
"label": "Text Field DataGrid",
"tableView": true,
"key": "textFieldDataGrid",
"type": "textfield",
"input": true
}]
}, {
"label": "Edit Grid",
"tableView": false,
"rowDrafts": false,
"key": "editGrid",
"type": "editgrid",
"input": true,
"components": [{
"label": "Text Field EditGrid",
"tableView": true,
"key": "textFieldEditGrid",
"type": "textfield",
"input": true
}]
}, {
"label": "Tree",
"tableView": false,
"key": "tree",
"type": "tree",
"input": true,
"tree": true,
"components": [{
"label": "Text Field Tree",
"tableView": true,
"key": "textFieldTree",
"type": "textfield",
"input": true
}]
}, {
"label": "Upload",
"tableView": false,
"storage": "base64",
"webcam": false,
"fileTypes": [{
"label": "",
"value": ""
}],
"key": "file",
"type": "file",
"input": true
}, {
"type": "button",
"label": "Submit",
"key": "submit",
"input": true,
"tableView": false
}
],
"title": "form for automated tests",
"display": "form",
"name": "formForAutomatedTests",
"path": "formforautomatedtests",
}
|
search_result['213']=["topic_0000000000000068_events--.html","ChatTokenResponseDto Events",""]; |
'use strict'
module.exports = {
info: {
key: 'javascript',
title: 'JavaScript',
extname: '.js',
default: 'xhr'
},
jquery: require('./jquery'),
fetch: require('./fetch'),
xhr: require('./xhr'),
axios: require('./axios')
}
|
function ord (string) {
// From: http://phpjs.org/functions
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: incidence
// * example 1: ord('K');
// * returns 1: 75
// * example 2: ord('\uD800\uDC00'); // surrogate pair to create a single Unicode character
// * returns 2: 65536
var str = string + '',
code = str.charCodeAt(0);
if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
var hi = code;
if (str.length === 1) {
return code; // This is just a high surrogate with no following low surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know
}
var low = str.charCodeAt(1);
return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
}
if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
return code; // This is just a low surrogate with no preceding high surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know
}
return code;
}
|
/**
* Todo:
* - Allow hiding of trades (seperates upcoming and finished games)
* - Allow auto-retry for when bots are down
* - Allow auto-accept offers
* - Create popup for browser action (next X games, my winnings)
*/
// CONSTANTS
var GREEN = "#76EE00",
ORANGE = "#FFA500",
RED = "#FF0000",
IMG_PATHS_19 = ["imgs/action/bad_19.png", "imgs/action/unstable_19.png", "imgs/action/good_19.png", "imgs/action/empty_19.png"],
IMG_PATHS_38 = ["imgs/action/bad_38.png", "imgs/action/unstable_38.png", "imgs/action/good_38.png", "imgs/action/empty_38.png"];
// VARIABLES
var lastError;
chrome.runtime.onStartup.addListener(function(){
console.log("onStartup called");
set_icon(3);
})
// INIT
function init() {
console.log("Starting extension");
chrome.alarms.clearAll();
// create alarm to call icon updater every minute
get_status(status_loop);
chrome.alarms.create("loopAlarm", {periodInMinutes: 1});
chrome.alarms.onAlarm.addListener(function(a){
var d = new Date();
console.log("Checking status ("+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+")");
get_status(status_loop);
});
}
chrome.runtime.onInstalled.addListener(init);
/**
* Listens for message
*/
chrome.runtime.onMessage.addListener(function(request,sender,callback) {
// if we're getting upcoming matches
if (request.get === "games") {
get_games(request.num, (function(callback){
return function(arr){
callback(arr);
}
})(callback));
}
// if we're getting status
if (request.get === "status") {
if (!callback)
callback = status_loop;
chrome.storage.local.get("status", callback);
}
// if we're asked to highlight a tab
if (request.post === "highlight") {
chrome.tabs.highlight({tabs: [sender.tab.index]}, callback);
}
return true;
});
/**
* Get the next X games
* Can return less than X games, if no more exist
* @param {int} num - number of games to return
* @param {function} callback - callback function
* Calls callback with one parameter:
* {array} - array of match objects, each formatted as follows:
* {time: string,
* link: string
* team1: {
* name: string,
* percent: int,
* imgUrl: string
* },
* team2: {
* name: string,
* percent: int,
* imgUrl: string
* }}
*/
function get_games(num, callback) {
// since we need logic in the callback, we gotta do it like this
var func = (function(num,callback){return function(){
// this function is called by XMLHttpRequest
// all logic is in here
// if site failed to load, error
if (this.status !== 200) {
callback({error: this.statusText, errno: this.status});
return;
} else {
// note: to save a bit on DOM parsing, I extract a substring first
// this might break in the future; possible TODO: create more reliable method
// extract the relevant part of the markup
var str = this.responseText,
startInd = str.indexOf("<article class=\"standard\" id=\"bets"),
endInd = str.indexOf("<div id=\"modalPreview", startInd),
containerStr = this.responseText.substring(startInd,endInd);
// parse
var parser = new DOMParser(),
doc = parser.parseFromString(containerStr, "text/html"),
matches = doc.querySelectorAll(".matchmain");
// TODO: add error handling
var output = [];
// loop through all matches
for (var i = 0, j = matches.length; i < j && output.length < num; i++) {
var match = matches[i],
finished = match.querySelector(".match").className.indexOf("notaviable") !== -1,
timeStr = match.querySelector(".matchheader div:first-child").innerHTML.replace('"', '\"').trim();
// if match is over or live, skip it
if (finished || timeStr.indexOf("LIVE") !== -1)
continue;
// extract data
var matchLink = "http://csgolounge.com/"+match.querySelector(".matchleft > a").getAttribute("href"),
team1Container = match.querySelector(".match a > div:first-child"),
team1 = {name: team1Container.querySelector("b:first-child").textContent,
percent: parseInt(team1Container.querySelector("i").textContent),
imgUrl: /url\('(.*?)'\)/.exec(team1Container.querySelector(".team").getAttribute("style"))[1]},
team2Container = match.querySelector(".match a > div:nth-child(3)"),
team2 = {name: team2Container.querySelector("b:first-child").textContent,
percent: parseInt(team2Container.querySelector("i").textContent),
imgUrl: /url\('(.*?)'\)/.exec(team2Container.querySelector(".team").getAttribute("style"))[1]};
// format object, and push to output
output.push({time: timeStr,
link: matchLink,
team1: team1,
team2: team2});
}
// end
callback(output);
}
}})(num, callback);
get("http://csgolounge.com/", func);
}
/**
* Repeatedly checks the status of the lounge bots
* Only to be used as callback for get_status
*/
function status_loop(vals) {
if (!vals)
console.error("status_loop should only be used as callback for get_status");
var iconNum = vals.error ? 3 : // if error, change to grey
(vals.status.indexOf(ORANGE) === -1 && vals.status.indexOf(RED) === -1) ? 2 : // if good, change to green
(!vals.offline) ? 1 : // if bots are online, but service(s) are down
0; // if down, change to red
if (vals.error)
console.error("Failed to get status: [#"+vals.errno+"] "+vals.error);
set_icon(iconNum);
}
/**
* Get the current bot status on CSGOLounge
* @param {function} callback - callback function
* Calls callback with one parameter:
* {array} - array of color values for top-most row in status table (see csgolounge.com/status)
*/
function get_status(callback) {
// since we need logic in the callback, we gotta do it like this
var func = (function(callback, timeout){return function(){
// this function is called by XMLHttpRequest
// all logic is in here
// clear timeout, so icon isn't changed to grey
clearTimeout(timeout);
// if site failed to load, error
if (this.status !== 200) {
callback({error: this.statusText, errno: this.status});
return;
} else {
// extract colors
var response = this.responseText.replace(/\s/g,""), // remove whitespace
offline = (response.indexOf("BOTSAREOFFLINE") !== -1),
tableReg = /<tablealign="center"cellpadding="7"[0-9a-z=%"]+>.*?<\/table>/,
table = tableReg.exec(response)[0],
colorReg = /#[0-8A-F]+/g,
colors = table.match(colorReg); // extract color codes from table
// save to status, so we don't need to retrieve again on popup
chrome.storage.local.set({status: colors}, function(){});
// call actual callback
callback({offline: offline,
status: colors});
}
}})(callback, setTimeout(function(){set_icon(3)}, 5000));
// request status page, running the above function
get("http://csgolounge.com/status", func);
}
/* =============================================================== *
* Helper functions
* =============================================================== */
/**
* Sets the browserAction icon
* @param {int} type - icon to change to: red (0), orange (1), green (2) or grey (3)
*/
function set_icon(type) {
chrome.browserAction.setIcon({path: {19: IMG_PATHS_19[type],
38: IMG_PATHS_38[type]}});
}
/**
* Perform a GET request to a url
* @param {string} url - The URL to request to
* @param {function} callback - The function to call once the request is performed
* @param {object} headers - a header object in the format {header: value}
*/
function get(url, callback, headers) {
// create xmlhttprequest instance
var xhr = new XMLHttpRequest();
// init
xhr.addEventListener("load", callback);
xhr.open("GET", url, true);
// set headers
for (var h in headers) {
if (headers.hasOwnProperty(h))
xhr.setRequestHeader(h, headers[h]);
}
// send
xhr.send();
}
/**
* Perform a POST request to a url
* @param {string} url - The URL to request to
* @param {object} data - the POST data
* @param {function} callback - The function to call once the request is performed
* @param {object} headers - a header object in the format {header: value}
*/
function post(url, data, callback, headers) {
// create xmlhttprequest instance
var xhr = new XMLHttpRequest(),
formatted = [];
if (typeof data === "object") {
for (var k in data) {
formatted.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k]));
}
formatted = formatted.join("&");
} else {
formatted = data;
}
// init
xhr.addEventListener("load", callback);
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// set headers
for (var h in headers) {
if (headers.hasOwnProperty(h))
xhr.setRequestHeader(h, headers[h]);
}
// send
xhr.send(formatted);
} |
export type PhenomicDB = {
destroy: () => Promise<*>,
put: (sub: string | Array<string>, key: string, value: any) => Promise<*>,
get: (sub: string | Array<string>, key: string) => Promise<*>,
getPartial: (sub: string | Array<string>, key: string) => Promise<*>,
getList: (
sub: string | Array<string>,
config: LevelStreamConfig,
filter?: string,
filterValue: string
) => Promise<*>
};
export type PhenomicInputPlugins = {
plugins?: Array<(arg: PhenomicInputConfig) => PhenomicPlugin>,
presets?: Array<(arg: PhenomicInputConfig) => PhenomicInputPlugins>
};
export type PhenomicInputConfig = {
path?: string,
outdir?: string,
port?: number,
bundleName?: string,
plugins?: Array<(arg: PhenomicInputConfig) => PhenomicPlugin>,
presets?: Array<(arg: PhenomicInputConfig) => PhenomicInputPlugins>
};
export type PhenomicContentFile = {
name: string,
fullpath: string
// exists: boolean,
// type: string
};
type PhenomicTransformResult = {
data: Object,
partial: Object
};
type PhenomicHtmlPropsType = {
body: React$Element<*>,
state?: React$Element<*>,
script: React$Element<*>
};
type PhenomicHtmlType = (props: PhenomicHtmlPropsType) => React$Element<*>;
type PhenomicPluginRenderHTMLType = (
config: PhenomicConfig,
props?: { body?: string, state?: Object },
html?: PhenomicHtmlType
) => string;
export type PhenomicPlugin = {
name: string,
// transformer
supportedFileTypes?: Array<string>,
transform?: ({
config?: PhenomicConfig,
file: PhenomicContentFile,
contents: Buffer
}) => Promise<PhenomicTransformResult> | PhenomicTransformResult,
// api
define?: (api: express$Application, db: PhenomicDB) => mixed,
// collector
collect?: (db: PhenomicDB, fileName: string, parsed: Object) => Array<mixed>,
// bunder
buildForPrerendering?: Function,
// renderer
getRoutes?: Function,
renderServer?: Function,
renderHTML?: PhenomicPluginRenderHTMLType,
// common
addDevServerMiddlewares?: (
config: PhenomicConfig
) => Array<express$Middleware | Promise<express$Middleware>>
};
export type PhenomicPlugins = Array<PhenomicPlugin>;
export type PhenomicPresets = Array<PhenomicPreset>;
export type PhenomicExtensions = PhenomicPreset;
export type PhenomicConfig = {
path: string,
outdir: string,
port: number,
bundleName: string,
plugins: Array<PhenomicPlugin>
};
export type PhenomicQueryConfig = {
collection?: string,
id?: string,
after?: string,
by?: string,
value?: string,
limit?: number
};
export type PhenomicRoute = {
path: string,
params?: { [key: string]: any },
component: {
getQueries?: (props: { params: { [key: string]: any } }) => {
[key: string]: PhenomicQueryConfig
}
},
collection?: string | PhenomicQueryConfig
};
// @todo why this inconsistency?
export type PhenomicFetch =
| IsomorphicFetch
| ((config: PhenomicQueryConfig) => Promise<any>);
export type phenomic$Query = string;
export type phenomic$Queries = Array<phenomic$Query>;
|
'use strict';
const assert = require('assert');
const app = require('../../../src/app');
describe('authority service', function() {
it('registered the authorities service', () => {
assert.ok(app.service('authorities'));
});
});
|
/**
* @license Highcharts JS v8.0.2 (2020-03-03)
* @module highcharts/modules/sonification
* @requires highcharts
*
* Sonification module
*
* (c) 2012-2019 Øystein Moseng
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../modules/sonification/sonification.js';
|
"use strict";
exports.__esModule = true;
exports.OTPRequiredError = void 0;
var _base = require("./base");
var _includes = _interopRequireDefault(require("lodash/includes"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class OTPRequiredError extends _base.BaseError {
static hasError({
headers
} = {}) {
if (!headers || !headers['otp-token']) {
return false;
}
return (0, _includes.default)(['OPTIONAL', 'REQUIRED'], headers['otp-token'].toUpperCase());
}
constructor() {
super('otp_required', ...arguments);
}
}
exports.OTPRequiredError = OTPRequiredError; |
'use strict';
const gulpMocha = require('gulp-mocha');
module.exports = function (simpleBuild) {
const gulp = simpleBuild.gulp;
gulp.task('test', ['test:server']);
gulp.task('test:watch', ['test:server:watch']);
gulp.task('test:server', function () {
return gulp.src('./src/server/**/*.spec.js', { read: false })
.pipe(gulpMocha({ reporter: 'spec' }));
});
gulp.task('test:server:watch', ['test:server'], function () {
gulp.watch('./src/server/**/*.js', ['test:server']);
});
};
|
const EventEmitter = require('events')
const stable = require('stable')
const glMatrix = require('gl-matrix')
const Transform = require('./transform')
const AnimatedNumber = require('./animated-number')
const AnimatedBoolean = require('./animated-boolean')
const Utils = require('./utils')
module.exports = class TraceObject extends EventEmitter {
constructor () {
super()
this.parentNode = null
this.transform = new Transform()
this.opacity = new AnimatedNumber(1)
this.enabled = new AnimatedBoolean(true)
this.zIndex = new AnimatedNumber(0)
this.children = new Set()
this.on('connected', () => {
for (let i of this.children.values()) i.emit('connected')
})
this.on('disconnected', () => {
for (let i of this.children.values()) i.emit('disconnected')
})
}
sortChildren (currentTime, deltaTime) {
let values = new Map()
for (let i of this.children.values()) {
values.set(i, [i.zIndex.getValue(currentTime, deltaTime),
i.enabled.getValue(currentTime, deltaTime)])
}
let sortedChildren = stable([...values.keys()], (a, b) => {
return values.get(a)[0] > values.get(b)[0]
})
return {
values,
children: sortedChildren
}
}
drawChildren (ctx, transform, currentTime, deltaTime) {
let {values, children} = this.sortChildren(currentTime, deltaTime)
for (let node of children) {
if (values.get(node)[1] === true) {
Utils.resetCtx(ctx)
node.draw(ctx, transform, currentTime, deltaTime)
}
}
}
draw (ctx, parentTransform, currentTime, deltaTime) {
let rawTransform = this.transform.getMatrix(currentTime, deltaTime)
let transform = glMatrix.mat4.create()
glMatrix.mat4.multiply(transform, parentTransform, rawTransform)
this.drawSelf(ctx, transform, currentTime, deltaTime)
this.drawChildren(ctx, transform, currentTime, deltaTime)
}
drawSelf (ctx, transform, currentTime, deltaTime) {}
addChild (...childNodes) {
for (let childNode of childNodes) {
if (childNode.parentNode !== null && childNode.parentNode !== this) {
throw new Error('Child node already has a parent')
}
this.children.add(childNode)
childNode.parentNode = this
childNode.emit('connected')
}
}
removeChild (...childNodes) {
let removed = []
for (let childNode of childNodes) {
if (childNode.parentNode !== this) {
throw new Error('Not a child node of this object')
}
childNode.emit('disconnected')
childNode.parentNode = null
removed.push(this.children.delete(childNode))
}
return removed.length === 1 ? removed[0] : removed
}
hasChild (childNode) {
return this.children.has(childNode)
}
closest (fn) {
if (fn(this)) return this
if (this.parentNode) return this.parentNode.closest(fn)
return null
}
addKeys (props) {
for (let prop in props) {
let property = this
for (let key of prop.split('.')) {
property = property[key]
if (!property) break
}
if (!property) {
console.warn('property not found: ' + prop)
continue
}
let val = props[prop]
let didWarn = false
if (typeof val === 'object') {
for (let time in val) {
if (!time.match(/^[+-]?(?:\d+?(?:\.\d+?)?|\.\d+?)?$/)) {
this.addKeys({ [`${prop}.${time}`]: val[time] })
continue
}
let t = parseFloat(time)
let v = val[time]
if (!Array.isArray(v)) v = [v]
if (property.addKey) property.addKey(t, ...v)
else if (!didWarn) {
console.warn(prop + ' has no addKey method')
didWarn = true
}
}
} else {
property.defaultValue = val
}
}
}
}
|
$(function() {
var select = $( "#minbeds" );
var slider = $( "<div id='slider'></div>" ).insertAfter( select ).slider({
min: 1,
max: 4,
range: "min",
value: select[ 0 ].selectedIndex + 1,
slide: function( event, ui ) {
select[ 0 ].selectedIndex = ui.value - 1;
}
});
$( "#minbeds" ).change(function() {
slider.slider( "value", this.selectedIndex + 1 );
});
}); |
angular.module('app.controllers.kda', ['app.services.data', 'app.services.options'])
.controller('KdaController', ['$scope', 'Data', 'Options', function ($scope, Data, Options) {
console.log('kda chart controller', $scope)
Data.data.getKdaData($scope);
$scope.$watch('kills + deaths + assists', function() {
if($scope.kills && $scope.deaths && $scope.assists) {
$scope.chart = [
{
value: $scope.kills,
color: "rgba(22,79,16,1)"
},
{
value : $scope.deaths,
color : "rgba(189,16,13,1)"
},
{
value: $scope.assists,
color: "rgba(88,156,173,1)"
}
];
}
})
$scope.options = Options.kdaOptions
}]) |
var elements = document.getElementsByTagName('script')
Array.prototype.forEach.call(elements, function(element) {
if (element.type.indexOf('math/tex') != -1) {
// Extract math markdown
var textToRender = element.innerText || element.textContent;
// Create span for KaTeX
var katexElement = document.createElement('span');
katexElement.style = "text-align:center";
// Support inline and display math
if (element.type.indexOf('mode=display') != -1){
katexElement.className += "math-display";
textToRender = '\\displaystyle {' + textToRender + '}';
} else {
katexElement.className += "math-inline";
}
katex.render(textToRender, katexElement);
element.parentNode.insertBefore(katexElement, element);
}
});
|
$(function () {
$('div').browser();
}); |
'use strict';
import assert from 'assert';
import bot from '../bot.js';
import * as interval from '../interval.js';
import FakeClient from './util/fakeclient.js';
import FakeMessage from './util/fakemessage.js';
describe('./bot.js', () => {
let client;
beforeEach(() => {
interval.enableTestMode();
client = bot(new FakeClient());
client.emit('ready');
});
afterEach(() => {
client.emit('disconnected');
interval.disableTestMode();
});
it('help doesn\'t fail', () => {
const message = new FakeMessage('!help');
client.emit('message', message);
assert.equal(message.replies.length, 1);
});
it('ping works', () => {
const message = new FakeMessage('!ping');
client.emit('message', message);
assert.equal(message.replies.length, 1);
assert.equal(message.replies[0], 'pong');
});
});
|
/**
* Created by 勇 on 2015/7/3.
*/
|
var express = require('express');
var hsv = require("hsv-rgb");
var fs = require('fs');
var profile = require('../modules/profile');
var milight = require('../modules/milight-controller.js');
var harmony = require('../modules/harmony-controller.js');
var tplink = require('../modules/hs100-controller');
var blinkstick = require('blinkstick');
var led = blinkstick.findFirst();
if(led != undefined) {
led.setMode(1);
}
var router = express.Router();
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
console.log(JSON.stringify(req.body, null, 4));
var event = req.body;
var token = event.directive.payload.scope ? event.directive.payload.scope.token : event.directive.endpoint.scope.token;
profile.getProfile(token, function(error, user) {
if(error) { console.log(error); }
// Only the authorised user can call this
if (user === null || user.email !== process.env.authorised_email) {
res.status(403).send('Not allowed!');
}
res.user = user;
next();
});
});
router.post('/alexa', function(req, res){
var event = req.body;
var header = event.directive ? event.directive.header : event.header;
switch (header.namespace) {
case 'Alexa.Discovery':
handleDiscovery(req, res);
break;
case 'Alexa.PowerController':
powerController(req, res);
break;
case 'Alexa.BrightnessController':
brightnessController(req, res);
break;
case 'Alexa.ColorController':
colorController(req, res);
break;
case 'Alexa':
stateController(req, res);
break;
/**
* We received an unexpected message
*/
default:
log('Err', 'No supported namespace: ' + header.namespace);
res.setHeader('Content-Type', 'application/json');
res.json(constructError(event));
break;
}
});
var handleDiscovery = function (req, res) {
var event = req.body;
var payload = JSON.parse(fs.readFileSync(__dirname + '/../devices.json', 'utf8'));
var headers = {
messageId: event.directive.header.messageId,
name: "Discover.Response",
namespace: "Alexa.Discovery",
payloadVersion: "3"
};
var result = {
event: {
header: headers,
payload: payload
}
};
res.setHeader('Content-Type', 'application/json');
res.json(result);
};
var powerController = function(req, res) {
var event = req.body;
var endpoint = event.directive.endpoint.endpointId;
if(endpoint === 'everything') {
controlEverything(event);
}
if(endpoint === 'milights') {
milight.setIp(event.directive.endpoint.cookie.ip);
event.directive.header.name === "TurnOff" ? milight.off() : milight.on();
}
if(endpoint === 'ikea-led') {
if(event.directive.header.name === "TurnOn") {
led.setColor('#FFFFFF', function() { /* called when color is changed */ });
} else {
led.turnOff();
}
}
if(endpoint === 'heater') {
harmony.heatingOn(event.directive.endpoint.cookie.harmonyIP, event.directive.endpoint.cookie.harmonyId);
}
var response = constructResponse(event, "powerState", event.directive.header.name === "TurnOff" ? "OFF": "ON");
res.setHeader('Content-Type', 'application/json');
res.json(response);
};
var brightnessController = function(req, res) {
var event = req.body;
// default to error
var response = constructError(event);
var endpoint = event.directive.endpoint.endpointId;
if(endpoint === 'milights') {
milight.setIp(event.directive.endpoint.cookie.ip);
if(event.directive.header.name === "SetBrightness") {
var brightnessPercentage = event.directive.payload.brightness;
milight.brightness(brightnessPercentage, 0);
response = constructResponse(event, "brightness", brightnessPercentage);
} else {
var brightnessDelta = event.directive.payload.brightnessDelta < 0 ? 20 : 100;
milight.brightness(brightnessDelta, 0);
response = constructResponse(event, "brightness", brightnessDelta);
}
}
res.setHeader('Content-Type', 'application/json');
res.json(response);
};
var colorController = function(req, res) {
var event = req.body;
// default to error
var response = constructError(event);
var endpoint = event.directive.endpoint.endpointId;
if(endpoint === 'milights') {
milight.setIp(event.directive.endpoint.cookie.ip);
if(event.directive.header.name === "SetColor") {
var color = event.directive.payload.color;
if(color.hue === 0 && color.saturation === 0) {
// Set to White
milight.on(0);
} else {
// Set to provided Colour
milight.colorHsv([color.hue, color.saturation, color.brightness]);
}
response = constructResponse(event, "color", color);
}
}
if(endpoint === 'ikea-led') {
var color = event.directive.payload.color;
var h = color.hue;
var s = Math.floor(color.saturation * 100);
var b = Math.floor(color.brightness * 100);
var rgb = hsv(h, s, b);
led.setColor(rgb[0], rgb[1], rgb[2]);
response = constructResponse(event, "color", color);
}
res.setHeader('Content-Type', 'application/json');
res.json(response);
};
var stateController = function(req, res){
var event = req.body;
// default to error
var response = constructError(event);
var exampleResponse = {
"context": {
"properties":[
{
"namespace":"Alexa.PowerController",
"name":"powerState",
"value":"ON"
},
{
"namespace":"Alexa.BrightnessController",
"name":"brightness",
"value":100
},
{
"namespace":"Alexa.ColorController",
"name":"color",
"value":{
"hue": 0,
"saturation": 0,
"brightness": 1
}
}
]
},
"event":{
"header":{
"messageId":event.directive.header.messageId,
"correlationToken":event.directive.header.correlationToken,
"namespace":"Alexa",
"name":"StateReport",
"payloadVersion":"3"
},
"endpoint":event.directive.endpoint,
"payload":{
}
}
}
if(event.directive.endpoint.endpointId === 'milights'){
response = exampleResponse;
}
res.setHeader('Content-Type', 'application/json');
res.json(response);
};
var controlEverything = function(event) {
if(event.directive.header.name === "TurnOff") {
milight.off();
led.turnOff();
tplink.off(event.directive.endpoint.cookie.ip, event.directive.endpoint.cookie.port);
harmony.tvOff();
} else {
milight.on();
led.setColor('#FFFFFF', function() { /* called when color is changed */ });
tplink.on(event.directive.endpoint.cookie.ip, event.directive.endpoint.cookie.port);
harmony.tvOn();
}
}
var constructResponse = function(event, name, value) {
var response = {
"context": {
"properties": [ {
"namespace": event.directive.header.namespace,
"name": name,
"value": value,
//"timeOfSample": "2017-02-03T16:20:50.52Z",
//"uncertaintyInMilliseconds": 500
} ]
},
"event": {
"header": {
"namespace": "Alexa",
"name": "Response",
"payloadVersion": "3",
"messageId": event.directive.header.messageId,
"correlationToken": event.directive.header.correlationToken
},
"endpoint": event.directive.endpoint,
"payload": {}
}
}
return response;
}
var constructError = function(event) {
return {
"event": {
"header": {
"namespace": "Alexa",
"name": "ErrorResponse",
"messageId": event.directive.header.messageId,
"correlationToken": event.directive.header.correlationToken,
"payloadVersion": "3"
},
"endpoint":{
"endpointId":event.directive.endpoint.endpointId
},
"payload": {
"type": "ENDPOINT_UNREACHABLE",
"message": "Unable to reach device because it appears to be offline"
}
}
}
}
module.exports = router; |
Noted.ItemView = Ember.View.extend({
templateName: "item_static",
didInsertElement: function() {
if (this.listItem.get("isEditing") === true) {
this._toEditingView();
}
else if (this.get("listItem.isActive")) {
this._updateScrollPosition();
}
},
editingObserver: function() {
if (this.listItem.get("isEditing")) {
this._toEditingView();
}
else {
this.set("templateName", "item_static");
this.rerender();
}
}.observes("listItem.isEditing"),
activeObserver: function() {
if (this.get('listItem.isActive')) {
this._updateScrollPosition();
}
else {
if (this.get("listItem.isEditing")) {
this.set("listItem.isEditing", false);
}
}
}.observes('listItem.isActive'),
click: function(e) {
if (this.get("listItem.isEditing")) {
if ($(e.target).prop("tagName") != "TEXTAREA") {
this.set('listItem.isEditing', false);
}
}
else {
this.set('parentView.active', this.get('listItem'));
}
},
focusOut: function(e) {
if (!this.get("listItem.isCanceling")) {
var value = this.get("listItem.text");
if(/^\s+$/.test(value) || value === "") {
this.get('controller').deleteItem(this.get('listItem'));
this.get("parentView")._changeActiveByOffset(-1);
}
else {
this.set('listItem.isEditing', false);
this.set('listItem.text', value);
}
Noted.store.commit();
}
else {
if (this.get("oldValue") === "") {
this.get('controller').deleteItem(this.get('listItem'));
this.get("parentView")._changeActiveByOffset(-1);
};
this.set("listItem.isEditing", false);
this.set("listItem.isCanceling", false);
}
},
doubleClick: function() {
// make de-selectable so that a triple click will not select
this.listItem.set("isEditing", true);
},
_toEditingView: function() {
this.set("templateName", "item_editing");
this.rerender();
this.didInsertElement = function() {
this.$("textarea").focus();
this.$("textarea").height(this.$("textarea").prop("scrollHeight"));
};
},
_updateScrollPosition: function() {
var activeView = this.$();
var container = $(".body-pane .scroller"); // don't like how hard coded this is - alternatives?
var viewportTop = $(container).scrollTop();
var viewportBottom = viewportTop + $(container).height();
var activeTop = $(activeView).position().top;
var activeBottom = activeTop + $(activeView).height();
var offset;
if (viewportTop > activeTop) {
offset = viewportTop - activeTop;
$(container).scrollTop($(container).scrollTop() - offset);
}
else if (viewportBottom < activeBottom) {
offset = activeBottom - viewportBottom;
$(container).scrollTop($(container).scrollTop() + offset);
}
}
});
Noted.ItemTextArea = Ember.TextArea.extend({
old: undefined,
cancel: false,
didInsertElement: function() {
this._super();
this.resize();
this.$().bind('paste', function(e) {
// workaround: paste actually fires BEFORE the text has been pasted in
setTimeout(function() {this.resize();}.bind(this), 0);
}.bind(this));
this.old = this.$().val();
this.set("parentView.oldValue", this.old);
},
willDestroyElement: function() {
this._super();
this.$().unbind('paste');
if (this.get("item.isCanceling")) {
this.set("value", this.old);
}
},
keyDown: function() {
this._super();
// wait for letter to be inserted before measuring resize
setTimeout(function () {
// checks to make sure the element still exists - i.e. ignore esc/enter
if (this.$())
this.resize();
}.bind(this), 0)
},
resize: function() {
var textarea = this.$();
textarea.height(textarea.prop('scrollHeight'));
}
});
|
/**! Qoopido.nucleus 3.2.4 | http://nucleus.qoopido.com | (c) 2020 Dirk Lueth */
!function(e){"use strict";provide(["/demand/pledge","../canvas"],(function(n,t){var c=n.defer();return t.then((function(){"toDataURL"in e.createElement("canvas")?c.resolve():c.reject()}),c.reject),c.pledge}))}(document);
//# sourceMappingURL=todataurl.js.map
|
module("funcunit - jQuery API",{
setup: function() {
S.open("//funcunit/test/confirm.html")
}
})
test("confirm overridden", function(){
S('#confirm').click().wait(1000, function(){
equal(S('#confirm').text(), "I was confirmed", "confirmed overriden to return true");
});
});
test("alert overridden", function(){
S('#alert').click().wait(1000, function(){
equal(S('#alert').text(), "I was alert", "alert overriden to return true");
});
}); |
let express = require('express');
let config = require('./config/main');
let path = require('path');
// providing route prefixing for express Router
express.application.prefix = express.Router.prefix = function (path, configure) {
let router = express.Router();
this.use(path, router);
configure(router);
return router;
};
let app = express();
let mongodbURL;
// Get env args
let port_string = process.argv[2];
let env_value = process.argv[3];
if (typeof port_string !== "undefined" && port_string.length > 0) {
console.log("port string: " + port_string);
config.port_number = port_string;
}
// Default env value is DEV
if (typeof env_value === "undefined") {
console.log("env_value is not set , Default env is DEV");
env_value = "DEV";
}
switch (env_value) {
case "DEV":
mongodbURL = config.localDB.connection;
console.log("environment = " + mongodbURL);
break;
case "PROD":
mongodbURL = config.db.connection;
console.log("environment = " + mongodbURL);
break;
default:
console.log("env_value is not correct: " + env_value);
return -1;
}
// Set the public folder
app.set('public', path.join(__dirname, 'public'));
app.set("config",config);
app.set("mongoUrl", mongodbURL);
require('./boot/boot')(app);
|
import React, { Fragment } from 'react'
import noop from '@utils/noop'
const DEFAULT_TAB = {
id: 'blank',
onClick: noop,
renderTab: () => <div />,
renderContents: () => <div />,
}
const TabSet = ({ activeTabId, buttons, onTabClicked = noop, showTabs = true, tabs = [] }) => {
if (tabs.length === 0) tabs.push(DEFAULT_TAB)
const activeId = activeTabId || tabs[0].id
const activeTab = tabs.find(tab => tab.id === activeId) || tabs[0]
const className = [
'tab-set',
!showTabs ? 'no-tabs' : '',
].filter(Boolean).join(' ')
return (
<div className={className}>
{showTabs &&
<Fragment>
<ul className={`tabs ${activeTabId}`}>
{tabs.map((tab) => {
// eslint-disable-next-line no-param-reassign
if (!tab.onClick) tab.onClick = () => onTabClicked(tab.id)
const liClassName = [
'tab',
tab.className,
tab.id,
activeTab.id === tab.id && 'is-active',
].filter(Boolean).join(' ')
return <li key={tab.id} className={liClassName} onClick={tab.onClick}>{tab.tab}</li>
})}
<li className="buttons">{buttons}</li>
</ul>
</Fragment>
}
<div className="tab-contents">
{activeTab.contents}
</div>
</div>
)
}
TabSet.displayName = 'TabSet'
export default TabSet
|
(function () {
'use strict';
angular
.module('app.hotels')
.controller('HotelsController', HotelsController);
/* @ngInject */
function HotelsController($q, hotelService, logger) {
/*jshint validthis: true */
var vm = this;
vm.title = 'Hotels';
vm.categories = [];
activate();
function activate() {
var promises = [
/*
* We get the first set of categories
* In a real application we would need to perform paging here
*/
getHotelCategories({from: 0, to:3}),
];
return $q.all(promises).then(function() {
logger.info('Activated Hotels View');
});
}
function getHotelCategories(indices) {
return hotelService.getHotelCategories(indices)
.subscribe(categories => {
vm.categories = categories;
return vm.categories;
});
}
}
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.