code
stringlengths
2
1.05M
var express = require('express'); var router = express.Router(); router.get('/', function(req,res){ res.send('hello from api route.'); }); module.exports = router;
import is from 'is_js'; import Strategy from './strategy'; export class TimerStrategy extends Strategy { constructor(config) { super(config); if (! is.number(config.intervalMs)) return; window.setInterval(() => { this.emit('notification'); }, config.intervalMs); } } export default TimerStrategy;
'use strict'; module.exports = function (environment) { let ENV = { modulePrefix: 'ember-demo', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. EMBER_NATIVE_DECORATOR_SUPPORT: true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false, }, }, APP: { // Here you can pass flags/options to your application instance // when it is created }, }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { // here you can enable a production-specific feature } return ENV; };
/** * Graphology Louvain Indices * =========================== * * Undirected & Directed Louvain Index structures used to compute the famous * Louvain community detection algorithm. * * Most of the rationale is explained in `graphology-metrics`. * * Note that this index shares a lot with the classic Union-Find data * structure. It also relies on a unused id stack to make sure we can * increase again the number of communites when isolating nodes. * * [Articles] * M. E. J. Newman, « Modularity and community structure in networks », * Proc. Natl. Acad. Sci. USA, vol. 103, no 23, 2006, p. 8577–8582 * https://dx.doi.org/10.1073%2Fpnas.0601602103 * * Newman, M. E. J. « Community detection in networks: Modularity optimization * and maximum likelihood are equivalent ». Physical Review E, vol. 94, no 5, * novembre 2016, p. 052315. arXiv.org, doi:10.1103/PhysRevE.94.052315. * https://arxiv.org/pdf/1606.02319.pdf * * Blondel, Vincent D., et al. « Fast unfolding of communities in large * networks ». Journal of Statistical Mechanics: Theory and Experiment, * vol. 2008, no 10, octobre 2008, p. P10008. DOI.org (Crossref), * doi:10.1088/1742-5468/2008/10/P10008. * https://arxiv.org/pdf/0803.0476.pdf * * Nicolas Dugué, Anthony Perez. Directed Louvain: maximizing modularity in * directed networks. [Research Report] Université d’Orléans. 2015. hal-01231784 * https://hal.archives-ouvertes.fr/hal-01231784 * * R. Lambiotte, J.-C. Delvenne and M. Barahona. Laplacian Dynamics and * Multiscale Modular Structure in Networks, * doi:10.1109/TNSE.2015.2391998. * https://arxiv.org/abs/0812.1770 * * [Latex]: * * Undirected Case: * ---------------- * * \Delta Q=\bigg{[}\frac{\sum^{c}_{in}-(2d_{c}+l)}{2m}-\bigg{(}\frac{\sum^{c}_{tot}-(d+l)}{2m}\bigg{)}^{2}+\frac{\sum^{t}_{in}+(2d_{t}+l)}{2m}-\bigg{(}\frac{\sum^{t}_{tot}+(d+l)}{2m}\bigg{)}^{2}\bigg{]}-\bigg{[}\frac{\sum^{c}_{in}}{2m}-\bigg{(}\frac{\sum^{c}_{tot}}{2m}\bigg{)}^{2}+\frac{\sum^{t}_{in}}{2m}-\bigg{(}\frac{\sum^{t}_{tot}}{2m}\bigg{)}^{2}\bigg{]} * \Delta Q=\frac{d_{t}-d_{c}}{m}+\frac{l\sum^{c}_{tot}+d\sum^{c}_{tot}-d^{2}-l^{2}-2dl-l\sum^{t}_{tot}-d\sum^{t}_{tot}}{2m^{2}} * \Delta Q=\frac{d_{t}-d_{c}}{m}+\frac{(l+d)\sum^{c}_{tot}-d^{2}-l^{2}-2dl-(l+d)\sum^{t}_{tot}}{2m^{2}} * * Directed Case: * -------------- * \Delta Q_d=\bigg{[}\frac{\sum^{c}_{in}-(d_{c.in}+d_{c.out}+l)}{m}-\frac{(\sum^{c}_{tot.in}-(d_{in}+l))(\sum^{c}_{tot.out}-(d_{out}+l))}{m^{2}}+\frac{\sum^{t}_{in}+(d_{t.in}+d_{t.out}+l)}{m}-\frac{(\sum^{t}_{tot.in}+(d_{in}+l))(\sum^{t}_{tot.out}+(d_{out}+l))}{m^{2}}\bigg{]}-\bigg{[}\frac{\sum^{c}_{in}}{m}-\frac{\sum^{c}_{tot.in}\sum^{c}_{tot.out}}{m^{2}}+\frac{\sum^{t}_{in}}{m}-\frac{\sum^{t}_{tot.in}\sum^{t}_{tot.out}}{m^{2}}\bigg{]} * * [Notes]: * Louvain is a bit unclear on this but delta computation are not derived from * Q1 - Q2 but rather between Q when considered node is isolated in its own * community versus Q with this node in target community. This is in fact * an optimization because the subtract part is constant in the formulae and * does not affect delta comparisons. */ var typed = require('mnemonist/utils/typed-arrays'); var resolveDefaults = require('graphology-utils/defaults'); var createEdgeWeightGetter = require('graphology-utils/getters').createEdgeWeightGetter; var INSPECT = Symbol.for('nodejs.util.inspect.custom'); var DEFAULTS = { getEdgeWeight: 'weight', keepDendrogram: false, resolution: 1 }; function UndirectedLouvainIndex(graph, options) { // Solving options options = resolveDefaults(options, DEFAULTS); var resolution = options.resolution; // Weight getters var getEdgeWeight = createEdgeWeightGetter(options.getEdgeWeight).fromEntry; // Building the index var size = (graph.size - graph.selfLoopCount) * 2; var NeighborhoodPointerArray = typed.getPointerArray(size); var NodesPointerArray = typed.getPointerArray(graph.order + 1); // NOTE: this memory optimization can yield overflow deopt when computing deltas var WeightsArray = options.getEdgeWeight ? Float64Array : typed.getPointerArray(graph.size * 2); // Properties this.C = graph.order; this.M = 0; this.E = size; this.U = 0; this.resolution = resolution; this.level = 0; this.graph = graph; this.nodes = new Array(graph.order); this.keepDendrogram = options.keepDendrogram; // Edge-level this.neighborhood = new NodesPointerArray(size); this.weights = new WeightsArray(size); // Node-level this.loops = new WeightsArray(graph.order); this.starts = new NeighborhoodPointerArray(graph.order + 1); this.belongings = new NodesPointerArray(graph.order); this.dendrogram = []; this.mapping = null; // Community-level this.counts = new NodesPointerArray(graph.order); this.unused = new NodesPointerArray(graph.order); this.totalWeights = new WeightsArray(graph.order); var ids = {}; var weight; var i = 0, n = 0; var self = this; graph.forEachNode(function (node) { self.nodes[i] = node; // Node map to index ids[node] = i; // Initializing starts n += graph.undirectedDegreeWithoutSelfLoops(node); self.starts[i] = n; // Belongings self.belongings[i] = i; self.counts[i] = 1; i++; }); // Single sweep over the edges graph.forEachEdge(function (edge, attr, source, target, sa, ta, u) { weight = getEdgeWeight(edge, attr, source, target, sa, ta, u); source = ids[source]; target = ids[target]; self.M += weight; // Self loop? if (source === target) { self.totalWeights[source] += weight * 2; self.loops[source] = weight * 2; } else { self.totalWeights[source] += weight; self.totalWeights[target] += weight; var startSource = --self.starts[source], startTarget = --self.starts[target]; self.neighborhood[startSource] = target; self.neighborhood[startTarget] = source; self.weights[startSource] = weight; self.weights[startTarget] = weight; } }); this.starts[i] = this.E; if (this.keepDendrogram) this.dendrogram.push(this.belongings.slice()); else this.mapping = this.belongings.slice(); } UndirectedLouvainIndex.prototype.isolate = function (i, degree) { var currentCommunity = this.belongings[i]; // The node is already isolated if (this.counts[currentCommunity] === 1) return currentCommunity; var newCommunity = this.unused[--this.U]; var loops = this.loops[i]; this.totalWeights[currentCommunity] -= degree + loops; this.totalWeights[newCommunity] += degree + loops; this.belongings[i] = newCommunity; this.counts[currentCommunity]--; this.counts[newCommunity]++; return newCommunity; }; UndirectedLouvainIndex.prototype.move = function (i, degree, targetCommunity) { var currentCommunity = this.belongings[i], loops = this.loops[i]; this.totalWeights[currentCommunity] -= degree + loops; this.totalWeights[targetCommunity] += degree + loops; this.belongings[i] = targetCommunity; var nowEmpty = this.counts[currentCommunity]-- === 1; this.counts[targetCommunity]++; if (nowEmpty) this.unused[this.U++] = currentCommunity; }; UndirectedLouvainIndex.prototype.computeNodeDegree = function (i) { var o, l, weight; var degree = 0; for (o = this.starts[i], l = this.starts[i + 1]; o < l; o++) { weight = this.weights[o]; degree += weight; } return degree; }; UndirectedLouvainIndex.prototype.expensiveIsolate = function (i) { var degree = this.computeNodeDegree(i); return this.isolate(i, degree); }; UndirectedLouvainIndex.prototype.expensiveMove = function (i, ci) { var degree = this.computeNodeDegree(i); this.move(i, degree, ci); }; UndirectedLouvainIndex.prototype.zoomOut = function () { var inducedGraph = new Array(this.C - this.U), newLabels = {}; var N = this.nodes.length; var C = 0, E = 0; var i, j, l, m, n, ci, cj, data, adj; // Renumbering communities for (i = 0, l = this.C; i < l; i++) { ci = this.belongings[i]; if (!(ci in newLabels)) { newLabels[ci] = C; inducedGraph[C] = { adj: {}, totalWeights: this.totalWeights[ci], internalWeights: 0 }; C++; } // We do this to otpimize the number of lookups in next loop this.belongings[i] = newLabels[ci]; } // Actualizing dendrogram var currentLevel, nextLevel; if (this.keepDendrogram) { currentLevel = this.dendrogram[this.level]; nextLevel = new (typed.getPointerArray(C))(N); for (i = 0; i < N; i++) nextLevel[i] = this.belongings[currentLevel[i]]; this.dendrogram.push(nextLevel); } else { for (i = 0; i < N; i++) this.mapping[i] = this.belongings[this.mapping[i]]; } // Building induced graph matrix for (i = 0, l = this.C; i < l; i++) { ci = this.belongings[i]; data = inducedGraph[ci]; adj = data.adj; data.internalWeights += this.loops[i]; for (j = this.starts[i], m = this.starts[i + 1]; j < m; j++) { n = this.neighborhood[j]; cj = this.belongings[n]; if (ci === cj) { data.internalWeights += this.weights[j]; continue; } if (!(cj in adj)) adj[cj] = 0; adj[cj] += this.weights[j]; } } // Rewriting neighborhood this.C = C; n = 0; for (ci = 0; ci < C; ci++) { data = inducedGraph[ci]; adj = data.adj; ci = +ci; this.totalWeights[ci] = data.totalWeights; this.loops[ci] = data.internalWeights; this.counts[ci] = 1; this.starts[ci] = n; this.belongings[ci] = ci; for (cj in adj) { this.neighborhood[n] = +cj; this.weights[n] = adj[cj]; E++; n++; } } this.starts[C] = E; this.E = E; this.U = 0; this.level++; return newLabels; }; UndirectedLouvainIndex.prototype.modularity = function () { var ci, cj, i, j, m; var Q = 0; var M2 = this.M * 2; var internalWeights = new Float64Array(this.C); for (i = 0; i < this.C; i++) { ci = this.belongings[i]; internalWeights[ci] += this.loops[i]; for (j = this.starts[i], m = this.starts[i + 1]; j < m; j++) { cj = this.belongings[this.neighborhood[j]]; if (ci !== cj) continue; internalWeights[ci] += this.weights[j]; } } for (i = 0; i < this.C; i++) { Q += internalWeights[i] / M2 - Math.pow(this.totalWeights[i] / M2, 2) * this.resolution; } return Q; }; UndirectedLouvainIndex.prototype.delta = function ( i, degree, targetCommunityDegree, targetCommunity ) { var M = this.M; var targetCommunityTotalWeight = this.totalWeights[targetCommunity]; degree += this.loops[i]; return ( targetCommunityDegree / M - // NOTE: formula is a bit different here because targetCommunityDegree is passed without * 2 (targetCommunityTotalWeight * degree * this.resolution) / (2 * M * M) ); }; UndirectedLouvainIndex.prototype.deltaWithOwnCommunity = function ( i, degree, targetCommunityDegree, targetCommunity ) { var M = this.M; var targetCommunityTotalWeight = this.totalWeights[targetCommunity]; degree += this.loops[i]; return ( targetCommunityDegree / M - // NOTE: formula is a bit different here because targetCommunityDegree is passed without * 2 ((targetCommunityTotalWeight - degree) * degree * this.resolution) / (2 * M * M) ); }; // NOTE: this is just a faster but equivalent version of #.delta // It is just off by a constant factor and is just faster to compute UndirectedLouvainIndex.prototype.fastDelta = function ( i, degree, targetCommunityDegree, targetCommunity ) { var M = this.M; var targetCommunityTotalWeight = this.totalWeights[targetCommunity]; degree += this.loops[i]; return ( targetCommunityDegree - (degree * targetCommunityTotalWeight * this.resolution) / (2 * M) ); }; UndirectedLouvainIndex.prototype.fastDeltaWithOwnCommunity = function ( i, degree, targetCommunityDegree, targetCommunity ) { var M = this.M; var targetCommunityTotalWeight = this.totalWeights[targetCommunity]; degree += this.loops[i]; return ( targetCommunityDegree - (degree * (targetCommunityTotalWeight - degree) * this.resolution) / (2 * M) ); }; UndirectedLouvainIndex.prototype.bounds = function (i) { return [this.starts[i], this.starts[i + 1]]; }; UndirectedLouvainIndex.prototype.project = function () { var self = this; var projection = {}; self.nodes.slice(0, this.C).forEach(function (node, i) { projection[node] = Array.from( self.neighborhood.slice(self.starts[i], self.starts[i + 1]) ).map(function (j) { return self.nodes[j]; }); }); return projection; }; UndirectedLouvainIndex.prototype.collect = function (level) { if (arguments.length < 1) level = this.level; var o = {}; var mapping = this.keepDendrogram ? this.dendrogram[level] : this.mapping; var i, l; for (i = 0, l = mapping.length; i < l; i++) o[this.nodes[i]] = mapping[i]; return o; }; UndirectedLouvainIndex.prototype.assign = function (prop, level) { if (arguments.length < 2) level = this.level; var mapping = this.keepDendrogram ? this.dendrogram[level] : this.mapping; var i, l; for (i = 0, l = mapping.length; i < l; i++) this.graph.setNodeAttribute(this.nodes[i], prop, mapping[i]); }; UndirectedLouvainIndex.prototype[INSPECT] = function () { var proxy = {}; // Trick so that node displays the name of the constructor Object.defineProperty(proxy, 'constructor', { value: UndirectedLouvainIndex, enumerable: false }); proxy.C = this.C; proxy.M = this.M; proxy.E = this.E; proxy.U = this.U; proxy.resolution = this.resolution; proxy.level = this.level; proxy.nodes = this.nodes; proxy.starts = this.starts.slice(0, proxy.C + 1); var eTruncated = ['neighborhood', 'weights']; var cTruncated = ['counts', 'loops', 'belongings', 'totalWeights']; var self = this; eTruncated.forEach(function (key) { proxy[key] = self[key].slice(0, proxy.E); }); cTruncated.forEach(function (key) { proxy[key] = self[key].slice(0, proxy.C); }); proxy.unused = this.unused.slice(0, this.U); if (this.keepDendrogram) proxy.dendrogram = this.dendrogram; else proxy.mapping = this.mapping; return proxy; }; function DirectedLouvainIndex(graph, options) { // Solving options options = resolveDefaults(options, DEFAULTS); var resolution = options.resolution; // Weight getters var getEdgeWeight = createEdgeWeightGetter(options.getEdgeWeight).fromEntry; // Building the index var size = (graph.size - graph.selfLoopCount) * 2; var NeighborhoodPointerArray = typed.getPointerArray(size); var NodesPointerArray = typed.getPointerArray(graph.order + 1); // NOTE: this memory optimization can yield overflow deopt when computing deltas var WeightsArray = options.getEdgeWeight ? Float64Array : typed.getPointerArray(graph.size * 2); // Properties this.C = graph.order; this.M = 0; this.E = size; this.U = 0; this.resolution = resolution; this.level = 0; this.graph = graph; this.nodes = new Array(graph.order); this.keepDendrogram = options.keepDendrogram; // Edge-level // NOTE: edges are stored out then in, in this order this.neighborhood = new NodesPointerArray(size); this.weights = new WeightsArray(size); // Node-level this.loops = new WeightsArray(graph.order); this.starts = new NeighborhoodPointerArray(graph.order + 1); this.offsets = new NeighborhoodPointerArray(graph.order); this.belongings = new NodesPointerArray(graph.order); this.dendrogram = []; // Community-level this.counts = new NodesPointerArray(graph.order); this.unused = new NodesPointerArray(graph.order); this.totalInWeights = new WeightsArray(graph.order); this.totalOutWeights = new WeightsArray(graph.order); var ids = {}; var weight; var i = 0, n = 0; var self = this; graph.forEachNode(function (node) { self.nodes[i] = node; // Node map to index ids[node] = i; // Initializing starts & offsets n += graph.outDegreeWithoutSelfLoops(node); self.starts[i] = n; n += graph.inDegreeWithoutSelfLoops(node); self.offsets[i] = n; // Belongings self.belongings[i] = i; self.counts[i] = 1; i++; }); // Single sweep over the edges graph.forEachEdge(function (edge, attr, source, target, sa, ta, u) { weight = getEdgeWeight(edge, attr, source, target, sa, ta, u); source = ids[source]; target = ids[target]; self.M += weight; // Self loop? if (source === target) { self.loops[source] += weight; self.totalInWeights[source] += weight; self.totalOutWeights[source] += weight; } else { self.totalOutWeights[source] += weight; self.totalInWeights[target] += weight; var startSource = --self.starts[source], startTarget = --self.offsets[target]; self.neighborhood[startSource] = target; self.neighborhood[startTarget] = source; self.weights[startSource] = weight; self.weights[startTarget] = weight; } }); this.starts[i] = this.E; if (this.keepDendrogram) this.dendrogram.push(this.belongings.slice()); else this.mapping = this.belongings.slice(); } DirectedLouvainIndex.prototype.bounds = UndirectedLouvainIndex.prototype.bounds; DirectedLouvainIndex.prototype.inBounds = function (i) { return [this.offsets[i], this.starts[i + 1]]; }; DirectedLouvainIndex.prototype.outBounds = function (i) { return [this.starts[i], this.offsets[i]]; }; DirectedLouvainIndex.prototype.project = UndirectedLouvainIndex.prototype.project; DirectedLouvainIndex.prototype.projectIn = function () { var self = this; var projection = {}; self.nodes.slice(0, this.C).forEach(function (node, i) { projection[node] = Array.from( self.neighborhood.slice(self.offsets[i], self.starts[i + 1]) ).map(function (j) { return self.nodes[j]; }); }); return projection; }; DirectedLouvainIndex.prototype.projectOut = function () { var self = this; var projection = {}; self.nodes.slice(0, this.C).forEach(function (node, i) { projection[node] = Array.from( self.neighborhood.slice(self.starts[i], self.offsets[i]) ).map(function (j) { return self.nodes[j]; }); }); return projection; }; DirectedLouvainIndex.prototype.isolate = function (i, inDegree, outDegree) { var currentCommunity = this.belongings[i]; // The node is already isolated if (this.counts[currentCommunity] === 1) return currentCommunity; var newCommunity = this.unused[--this.U]; var loops = this.loops[i]; this.totalInWeights[currentCommunity] -= inDegree + loops; this.totalInWeights[newCommunity] += inDegree + loops; this.totalOutWeights[currentCommunity] -= outDegree + loops; this.totalOutWeights[newCommunity] += outDegree + loops; this.belongings[i] = newCommunity; this.counts[currentCommunity]--; this.counts[newCommunity]++; return newCommunity; }; DirectedLouvainIndex.prototype.move = function ( i, inDegree, outDegree, targetCommunity ) { var currentCommunity = this.belongings[i], loops = this.loops[i]; this.totalInWeights[currentCommunity] -= inDegree + loops; this.totalInWeights[targetCommunity] += inDegree + loops; this.totalOutWeights[currentCommunity] -= outDegree + loops; this.totalOutWeights[targetCommunity] += outDegree + loops; this.belongings[i] = targetCommunity; var nowEmpty = this.counts[currentCommunity]-- === 1; this.counts[targetCommunity]++; if (nowEmpty) this.unused[this.U++] = currentCommunity; }; DirectedLouvainIndex.prototype.computeNodeInDegree = function (i) { var o, l, weight; var inDegree = 0; for (o = this.offsets[i], l = this.starts[i + 1]; o < l; o++) { weight = this.weights[o]; inDegree += weight; } return inDegree; }; DirectedLouvainIndex.prototype.computeNodeOutDegree = function (i) { var o, l, weight; var outDegree = 0; for (o = this.starts[i], l = this.offsets[i]; o < l; o++) { weight = this.weights[o]; outDegree += weight; } return outDegree; }; DirectedLouvainIndex.prototype.expensiveMove = function (i, ci) { var inDegree = this.computeNodeInDegree(i), outDegree = this.computeNodeOutDegree(i); this.move(i, inDegree, outDegree, ci); }; DirectedLouvainIndex.prototype.zoomOut = function () { var inducedGraph = new Array(this.C - this.U), newLabels = {}; var N = this.nodes.length; var C = 0, E = 0; var i, j, l, m, n, ci, cj, data, offset, out, adj, inAdj, outAdj; // Renumbering communities for (i = 0, l = this.C; i < l; i++) { ci = this.belongings[i]; if (!(ci in newLabels)) { newLabels[ci] = C; inducedGraph[C] = { inAdj: {}, outAdj: {}, totalInWeights: this.totalInWeights[ci], totalOutWeights: this.totalOutWeights[ci], internalWeights: 0 }; C++; } // We do this to otpimize the number of lookups in next loop this.belongings[i] = newLabels[ci]; } // Actualizing dendrogram var currentLevel, nextLevel; if (this.keepDendrogram) { currentLevel = this.dendrogram[this.level]; nextLevel = new (typed.getPointerArray(C))(N); for (i = 0; i < N; i++) nextLevel[i] = this.belongings[currentLevel[i]]; this.dendrogram.push(nextLevel); } else { for (i = 0; i < N; i++) this.mapping[i] = this.belongings[this.mapping[i]]; } // Building induced graph matrix for (i = 0, l = this.C; i < l; i++) { ci = this.belongings[i]; offset = this.offsets[i]; data = inducedGraph[ci]; inAdj = data.inAdj; outAdj = data.outAdj; data.internalWeights += this.loops[i]; for (j = this.starts[i], m = this.starts[i + 1]; j < m; j++) { n = this.neighborhood[j]; cj = this.belongings[n]; out = j < offset; adj = out ? outAdj : inAdj; if (ci === cj) { if (out) data.internalWeights += this.weights[j]; continue; } if (!(cj in adj)) adj[cj] = 0; adj[cj] += this.weights[j]; } } // Rewriting neighborhood this.C = C; n = 0; for (ci = 0; ci < C; ci++) { data = inducedGraph[ci]; inAdj = data.inAdj; outAdj = data.outAdj; ci = +ci; this.totalInWeights[ci] = data.totalInWeights; this.totalOutWeights[ci] = data.totalOutWeights; this.loops[ci] = data.internalWeights; this.counts[ci] = 1; this.starts[ci] = n; this.belongings[ci] = ci; for (cj in outAdj) { this.neighborhood[n] = +cj; this.weights[n] = outAdj[cj]; E++; n++; } this.offsets[ci] = n; for (cj in inAdj) { this.neighborhood[n] = +cj; this.weights[n] = inAdj[cj]; E++; n++; } } this.starts[C] = E; this.E = E; this.U = 0; this.level++; return newLabels; }; DirectedLouvainIndex.prototype.modularity = function () { var ci, cj, i, j, m; var Q = 0; var M = this.M; var internalWeights = new Float64Array(this.C); for (i = 0; i < this.C; i++) { ci = this.belongings[i]; internalWeights[ci] += this.loops[i]; for (j = this.starts[i], m = this.offsets[i]; j < m; j++) { cj = this.belongings[this.neighborhood[j]]; if (ci !== cj) continue; internalWeights[ci] += this.weights[j]; } } for (i = 0; i < this.C; i++) Q += internalWeights[i] / M - ((this.totalInWeights[i] * this.totalOutWeights[i]) / Math.pow(M, 2)) * this.resolution; return Q; }; DirectedLouvainIndex.prototype.delta = function ( i, inDegree, outDegree, targetCommunityDegree, targetCommunity ) { var M = this.M; var targetCommunityTotalInWeight = this.totalInWeights[targetCommunity], targetCommunityTotalOutWeight = this.totalOutWeights[targetCommunity]; var loops = this.loops[i]; inDegree += loops; outDegree += loops; return ( targetCommunityDegree / M - ((outDegree * targetCommunityTotalInWeight + inDegree * targetCommunityTotalOutWeight) * this.resolution) / (M * M) ); }; DirectedLouvainIndex.prototype.deltaWithOwnCommunity = function ( i, inDegree, outDegree, targetCommunityDegree, targetCommunity ) { var M = this.M; var targetCommunityTotalInWeight = this.totalInWeights[targetCommunity], targetCommunityTotalOutWeight = this.totalOutWeights[targetCommunity]; var loops = this.loops[i]; inDegree += loops; outDegree += loops; return ( targetCommunityDegree / M - ((outDegree * (targetCommunityTotalInWeight - inDegree) + inDegree * (targetCommunityTotalOutWeight - outDegree)) * this.resolution) / (M * M) ); }; DirectedLouvainIndex.prototype.collect = UndirectedLouvainIndex.prototype.collect; DirectedLouvainIndex.prototype.assign = UndirectedLouvainIndex.prototype.assign; DirectedLouvainIndex.prototype[INSPECT] = function () { var proxy = {}; // Trick so that node displays the name of the constructor Object.defineProperty(proxy, 'constructor', { value: DirectedLouvainIndex, enumerable: false }); proxy.C = this.C; proxy.M = this.M; proxy.E = this.E; proxy.U = this.U; proxy.resolution = this.resolution; proxy.level = this.level; proxy.nodes = this.nodes; proxy.starts = this.starts.slice(0, proxy.C + 1); var eTruncated = ['neighborhood', 'weights']; var cTruncated = [ 'counts', 'offsets', 'loops', 'belongings', 'totalInWeights', 'totalOutWeights' ]; var self = this; eTruncated.forEach(function (key) { proxy[key] = self[key].slice(0, proxy.E); }); cTruncated.forEach(function (key) { proxy[key] = self[key].slice(0, proxy.C); }); proxy.unused = this.unused.slice(0, this.U); if (this.keepDendrogram) proxy.dendrogram = this.dendrogram; else proxy.mapping = this.mapping; return proxy; }; exports.UndirectedLouvainIndex = UndirectedLouvainIndex; exports.DirectedLouvainIndex = DirectedLouvainIndex;
export function isCommented(cm, nLine, match) { let token = cm.getTokenAt({ line: nLine, ch: match.index }); if (token && token.type) { return token.type === 'comment'; } return false; } export function isLineAfterMain(cm, nLine) { let totalLines = cm.getDoc().size; let voidRE = new RegExp('void main\\s*\\(\\s*[void]*\\)', 'i'); for (let i = 0; i < nLine && i < totalLines; i++) { // Do not start until being inside the main function let voidMatch = voidRE.exec(cm.getLine(i)); if (voidMatch) { return true; } } return false; } export function getVariableType(cm, sVariable) { let nLines = cm.getDoc().size; // Show line where the value of the variable is been asigned let uniformRE = new RegExp('\\s*uniform\\s+(float|vec2|vec3|vec4)\\s+' + sVariable + '\\s*;'); let voidRE = new RegExp('void main\\s*\\(\\s*[void]*\\)', 'i'); let voidIN = false; let constructRE = new RegExp('(float|vec\\d)\\s+(' + sVariable + ')\\s*[;]?', 'i'); for (let i = 0; i < nLines; i++) { if (!voidIN) { // Do not start until being inside the main function let voidMatch = voidRE.exec(cm.getLine(i)); if (voidMatch) { voidIN = true; } else { let uniformMatch = uniformRE.exec(cm.getLine(i)); if (uniformMatch && !isCommented(cm, i, uniformMatch)) { return uniformMatch[1]; } } } else { let constructMatch = constructRE.exec(cm.getLine(i)); if (constructMatch && constructMatch[1] && !isCommented(cm, i, constructMatch)) { return constructMatch[1]; } } } return 'none'; } export function getShaderForTypeVarInLine(cm, sType, sVariable, nLine) { let frag = ''; let offset = 1; for (let i = 0; i < nLine + 1 && i < cm.getDoc().size; i++) { if (cm.getLine(i)) { frag += cm.getLine(i) + '\n'; } } frag += '\tgl_FragColor = '; if (sType === 'float') { frag += 'vec4(vec3(' + sVariable + '),1.)'; } else if (sType === 'vec2') { frag += 'vec4(vec3(' + sVariable + ',0.),1.)'; } else if (sType === 'vec3') { frag += 'vec4(' + sVariable + ',1.)'; } else if (sType === 'vec4') { frag += sVariable; } frag += ';\n}\n'; return frag; } export function getResultRange(test_results) { let min_ms = '10000000.0'; let min_line = 0; let max_ms = '0.0'; let max_line = 0; for (let i in test_results) { if (test_results[i].ms < min_ms) { min_ms = test_results[i].ms; min_line = test_results[i].line; } if (test_results[i].ms > max_ms) { max_ms = test_results[i].ms; max_line = test_results[i].line; } } return { min:{line: min_line, ms: min_ms}, max:{line: max_line, ms: max_ms} }; } export function getMedian(values) { values.sort( function(a,b) {return a - b;} ); var half = Math.floor(values.length/2); if(values.length % 2) return values[half]; else return (values[half-1] + values[half]) / 2.0; } export function getDeltaSum(test_results) { let total = 0.0; for (let i in test_results) { if (test_results[i].delta > 0) { total += test_results[i].delta; } } return total; } export function getHits(test_results) { let total = 0; for (let i in test_results) { if (test_results[i].delta > 0) { total++; } } return total; }
import React, {PureComponent} from "react"; import {FillView} from "../shared/fill-view"; import {CodeView} from "../shared/code-view"; const sourceCode = ` export const DynamicRectangles = ({color, width, height}) => { const divProps = { style: { backgroundColor: color, width: width + "vw", height: height + "vh" } }; return ( <div {...divProps}> {width} x {height} </div> ); }; export const DynamicRectanglesComposed = compose( dynamicTestPatternHoc({ colors: [ 'tomato', 'darkkhaki', 'slateblue', 'mediumseagreen', 'aqua', ] }) )(DynamicRectangles); `; export class RectanglesHocUsageSlide extends PureComponent { render() { return ( <FillView> <CodeView sourceCode={sourceCode} language="javascript" /> </FillView> ) } }
/* jshint browser: true */ 'use strict'; (() => { const resultList = document.getElementById("result-list"); const observer = fastnav.observer; const actions = fastnav.actions; const SELECT_NONE = 0; const SELECT_DOWN = 1; const SELECT_UP = 2; var listManager = (() => { var currentList = []; var _actionSelected; var _selectedIndex = -1; observer.subscribe('selectionChanged', param => { let {oldSelectedIndex, selectedIndex, scrollNeeded} = param; if(oldSelectedIndex >= 0) { let oldAction = currentList[oldSelectedIndex]; oldAction.selected = false; oldAction.refreshDOM(); } if(selectedIndex >= 0) { _actionSelected = currentList[selectedIndex]; _actionSelected.selected = true; let dom = _actionSelected.refreshDOM(); if(scrollNeeded) { dom.scrollIntoView(false); } } _selectedIndex = selectedIndex; }); return { get selectedIndex() { return _selectedIndex; }, get actionSelected() { return _actionSelected; }, set actionSelected(actionSelected) { _actionSelected = actionSelected; }, getAction(index) { return currentList[index]; }, actionFiltered(action) { action.listIndex = currentList.length; currentList.push(action); resultList.appendChild(action.refreshDOM()); }, update(search) { this.moveSelection(SELECT_NONE); currentList = []; resultList.innerHTML = ''; let filterActions = (search, collection) => { for(let action of collection) { let title = action.title.toLowerCase(); let url = action.url; if(search === '*all*' || title.indexOf(search) >= 0 || (url && url.toLowerCase().indexOf(search) >= 0)) { this.actionFiltered(action); } } }; if(search) { let action = actions.get('default'); action.description = `Open ${search}`; this.actionFiltered(action); filterActions(search, actions.get('cache')); } filterActions(search, actions.get('tabs')); if(search && search !== ' *all*') { self.port.emit('get-data', search); } }, remove(dom) { //todo }, moveSelection(where) { let newSelectionIndex = _selectedIndex; if(where === SELECT_DOWN) { if((_selectedIndex + 1 < resultList.childNodes.length)) { newSelectionIndex++; } } else if (where === SELECT_UP && (_selectedIndex > 0)) { newSelectionIndex--; } else { newSelectionIndex = -1; } observer.fire('selectionChanged', { oldSelectedIndex: _selectedIndex, selectedIndex: newSelectionIndex, scrollNeeded: true }); } }; })(); fastnav.resultList = resultList; fastnav.list_manager = listManager; fastnav.SELECT_NONE = SELECT_NONE; fastnav.SELECT_DOWN = SELECT_DOWN; fastnav.SELECT_UP = SELECT_UP; })();
(function(){ if (typeof(KekuleMoodle) === 'undefined') KekuleMoodle = {}; if (!KekuleMoodle.Widget) KekuleMoodle.Widget = {}; KekuleMoodle.Widget.ChemObjSelectorPanel = Class.create(Kekule.Widget.Panel, { CLASS_NAME: 'KekuleMoodle.Widget.ChemObjSelectorPanel', initialize: function(/*$super, */parentOrElementOrDocument, renderType, viewerConfigs) { //this.setPropStoreFieldValue('renderType', renderType); //this.setPropStoreFieldValue('viewerConfigs', viewerConfigs); this.tryApplySuper('initialize', [parentOrElementOrDocument]); this._renderConfigs = this._generateDefaultRenderConfigs(); var viewerGrid = new Kekule.ChemWidget.ViewerGrid(this, renderType, viewerConfigs); viewerGrid.setEnableAdd(false).setEnableRemove(false); this.setPropStoreFieldValue('viewerGrid', viewerGrid); this.on('click', this.reactCellClick.bind(this)); }, initProperties: function() { this.defineProp('objects', {'dataType': DataType.ARRAY, 'serializable': false, 'setter': function(value) { this.setPropStoreFieldValue('objects', value || []); this.objectsChanged(); } }); //this.defineProp('renderType', {'dataType': DataType.INT, 'serializable': false, 'setter': null}); //this.defineProp('viewerConfigs', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null}); // private this.defineProp('viewerGrid', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null}); }, doFinalize: function() { this.getViewerGrid().finalize(); this.tryApplySuper('doFinalize'); }, /** @ignore */ doGetWidgetClassName: function(/*$super*/) { return this.tryApplySuper('doGetWidgetClassName') + ' ' + 'KM-ChemObjSelectorPanel'; }, _generateDefaultRenderConfigs: function() { var result = new Kekule.Render.Render2DConfigs(); result.getLengthConfigs().setAutofitContextPadding(10); //result.getLengthConfigs().setBondLineWidth(4); return result; }, objectsChanged: function() // update viewers to reflect to objects change { var objs = this.getObjects(); var grid = this.getViewerGrid(); grid.clearWidgets(); for (var i = 0, l = objs.length; i < l; ++i) { grid.addChemObj(objs[i]); } var viewers = grid.getChildWidgets(); for (var i = 0, l = viewers.length; i < l; ++i) { viewers[i].beginUpdate(); viewers[i].setAutoShrink(true); viewers[i].setRenderConfigs(this._renderConfigs); viewers[i].setPadding(this._renderConfigs.getLengthConfigs().getAutofitContextPadding()); viewers[i].endUpdate(); //viewers[i].repaint(); } }, _getTargetViewer: function(srcWidget) { if (srcWidget instanceof Kekule.ChemWidget.Viewer && srcWidget.getParent() === this.getViewerGrid()) { return srcWidget; } else { var parent = srcWidget.getParent(); return parent? this._getTargetViewer(parent): null; } }, reactCellClick: function(e) { var viewer = this._getTargetViewer(e.target); if (viewer) // click on viewer { this.invokeEvent('select', {'viewer': viewer, 'chemObj': viewer.getChemObj()}); } } }); })();
class stsserver_enumstsaltinfo { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = stsserver_enumstsaltinfo;
function Calendar(element, options, eventSources, resourceSources) { var t = this; // exports t.options = options; t.render = render; t.destroy = destroy; t.refetchEvents = refetchEvents; t.reportEvents = reportEvents; t.refetchResources = refetchResources; t.reportEventChange = reportEventChange; t.updateEventsNoRerender = updateEventsNoRerender; t.rerenderEvents = rerenderEvents; t.changeView = changeView; t.select = select; t.unselect = unselect; t.prev = prev; t.next = next; t.prevYear = prevYear; t.nextYear = nextYear; t.today = today; t.gotoDate = gotoDate; t.incrementDate = incrementDate; t.formatDate = function(format, date) { return formatDate(format, date, options) }; t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) }; t.getDate = getDate; t.getView = getView; t.option = option; t.trigger = trigger; t.renderEventsSimplified = renderEventsSimplified; // imports EventManager.call(t, options, eventSources); var isFetchNeeded = t.isFetchNeeded; var fetchEvents = t.fetchEvents; // fetch resources ResourceManager.call(t, options); var fetchResources = t.fetchResources; // locals var _element = element[0]; var header; var headerElement; var content; var tm; // for making theme classes var currentView; var viewInstances = {}; var elementOuterWidth; var suggestedViewHeight; var absoluteViewElement; var resizeUID = 0; var ignoreWindowResize = 0; var date = new Date(); var events = []; var _dragElement; /* Main Rendering -----------------------------------------------------------------------------*/ setYMD(date, options.year, options.month, options.date); function render(inc) { if (!content) { initialRender(); }else{ calcSize(); markSizesDirty(); markEventsDirty(); renderView(inc); } } function initialRender() { tm = options.theme ? 'ui' : 'fc'; element.addClass('fc'); if (options.isRTL) { element.addClass('fc-rtl'); } if (options.theme) { element.addClass('ui-widget'); } content = $("<div class='fc-content' style='position:relative'/>") .prependTo(element); header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } changeView(options.defaultView); $(window).resize(windowResize); // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize if (!bodyVisible()) { lateRender(); } } // called when we know the calendar couldn't be rendered when it was initialized, // but we think it's ready now function lateRender() { setTimeout(function() { // IE7 needs this so dimensions are calculated correctly if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once renderView(); } },0); } function destroy() { $(window).unbind('resize', windowResize); header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } function elementVisible() { return _element.offsetWidth !== 0; } function bodyVisible() { return $('body')[0].offsetWidth !== 0; } /* View Rendering -----------------------------------------------------------------------------*/ // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached unselect(); var oldView = currentView; var newViewElement; if (oldView) { (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) setMinHeight(content, content.height()); oldView.element.hide(); }else{ setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated } content.css('overflow', 'hidden'); currentView = viewInstances[newViewName]; if (currentView) { currentView.element.show(); }else{ currentView = viewInstances[newViewName] = new fcViews[newViewName]( newViewElement = absoluteViewElement = $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>") .appendTo(content), t // the calendar object ); } if (oldView) { header.deactivateButton(oldView.name); } header.activateButton(newViewName); renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null content.css('overflow', ''); if (oldView) { setMinHeight(content, 1); } if (!newViewElement) { (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) } ignoreWindowResize--; } } function renderView(inc) { if (elementVisible()) { ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached unselect(); if (suggestedViewHeight === undefined) { calcSize(); } var forceEventRender = false; if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { // view must render an entire new date range (and refetch/render events) currentView.render(date, inc || 0); // responsible for clearing events setSize(true); forceEventRender = true; } else if (currentView.sizeDirty) { // view must resize (and rerender events) currentView.clearEvents(); setSize(); forceEventRender = true; } else if (currentView.eventsDirty) { currentView.clearEvents(); forceEventRender = true; } currentView.sizeDirty = false; currentView.eventsDirty = false; updateEvents(forceEventRender); elementOuterWidth = element.outerWidth(); header.updateTitle(currentView.title); var today = new Date(); if (today >= currentView.start && today < currentView.end) { header.disableButton('today'); }else{ header.enableButton('today'); } ignoreWindowResize--; currentView.trigger('viewDisplay', _element); } } /* Resizing -----------------------------------------------------------------------------*/ function updateSize() { markSizesDirty(); if (elementVisible()) { calcSize(); setSize(); unselect(); currentView.clearEvents(); currentView.trigger('viewRender', currentView); currentView.renderEvents(events); currentView.sizeDirty = false; } } function markSizesDirty() { $.each(viewInstances, function(i, inst) { inst.sizeDirty = true; }); } function calcSize() { if (options.contentHeight) { suggestedViewHeight = options.contentHeight; } else if (options.height) { suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); } else { suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); } } function setSize(dateChanged) { // todo: dateChanged? ignoreWindowResize++; currentView.setHeight(suggestedViewHeight, dateChanged); if (absoluteViewElement) { absoluteViewElement.css('position', 'relative'); absoluteViewElement = null; } currentView.setWidth(content.width(), dateChanged); ignoreWindowResize--; } function windowResize() { if (!ignoreWindowResize) { if (currentView.start) { // view has already been rendered var uid = ++resizeUID; setTimeout(function() { // add a delay if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { ignoreWindowResize++; // in case the windowResize callback changes the height updateSize(); currentView.trigger('windowResize', _element); ignoreWindowResize--; } } }, 200); }else{ // calendar must have been initialized in a 0x0 iframe that has just been resized lateRender(); } } } /* Event Fetching/Rendering -----------------------------------------------------------------------------*/ // fetches events if necessary, rerenders events if necessary (or if forced) function updateEvents(forceRender) { if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { refetchEvents(); if (options['refetchResources']) refetchResources(); // refetch resources every time new events are loaded } else if (forceRender) { rerenderEvents(); } } function refetchEvents(source) { fetchEvents(currentView.visStart, currentView.visEnd, source); // will call reportEvents } function refetchResources() { fetchResources(false, currentView); // we have to destroy all view instances and recreate current one viewInstances = []; // remove current view from display currentView.element.remove(); // create current view again currentView = viewInstances[currentView.name] = new fcViews[currentView.name]( absoluteViewElement = $("<div class='fc-view fc-view-" + currentView.name + "' style='position:absolute'/>") .appendTo(content), t // the calendar object ); // let's render the new view renderView(); } // called when event data arrives function reportEvents(_events) { events = _events; rerenderEvents(); } // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } function updateEventsNoRerender(list) { if (currentView.updateEventNoRerender) { for (var i = 0; i < list.length; i++) { var _events = this.clientEvents(list[i]); if (_events.length > 0) { currentView.updateEventNoRerender(_events[0]); } } } else { // console.info('To Optimize add updateEventsNoRerender to view:', currentView.name); rerenderEvents(); } } // attempts to rerenderEvents function rerenderEvents(modifiedEventID) { markEventsDirty(); if (elementVisible()) { currentView.clearEvents(); currentView.trigger('viewRender', currentView); currentView.renderEvents(events, modifiedEventID); currentView.eventsDirty = false; } } function markEventsDirty() { $.each(viewInstances, function(i, inst) { inst.eventsDirty = true; }); } function renderEventsSimplified(events, classNames) { // Not all views have this function just yet if (currentView.renderEventsSimplified) { currentView.renderEventsSimplified(events, classNames); } } /* Selection -----------------------------------------------------------------------------*/ function select(start, end, allDay) { currentView.select(start, end, allDay===undefined ? true : allDay); } function unselect() { // safe to be called before renderView if (currentView) { currentView.unselect(); } } /* Date -----------------------------------------------------------------------------*/ function prev() { renderView(-1); } function next() { renderView(1); } function prevYear() { addYears(date, -1); renderView(); } function nextYear() { addYears(date, 1); renderView(); } function today() { date = new Date(); renderView(); } function gotoDate(year, month, dateOfMonth) { if (year instanceof Date) { date = cloneDate(year); // provided 1 argument, a Date }else{ setYMD(date, year, month, dateOfMonth); } renderView(); } function incrementDate(years, months, days) { if (years !== undefined) { addYears(date, years); } if (months !== undefined) { addMonths(date, months); } if (days !== undefined) { addDays(date, days); } renderView(); } function getDate() { return cloneDate(date); } /* Misc -----------------------------------------------------------------------------*/ function getView() { return currentView; } function option(name, value) { if (value === undefined) { return options[name]; } if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { options[name] = value; updateSize(); } else if (name.indexOf('list') == 0 || name == 'tableCols') { options[name] = value; currentView.start = null; // force re-render } else if (name == 'maxHeight' || name == 'selectable' || name == 'editable') { options[name] = value; } } function trigger(name, thisObj) { if (options[name]) { return options[name].apply( thisObj || _element, Array.prototype.slice.call(arguments, 2) ); } } /* External Dragging ------------------------------------------------------------------------*/ if (options.droppable) { $(document) .bind('dragstart', function(ev, ui) { var _e = ev.target; var e = $(_e); if (!e.parents('.fc').length) { // not already inside a calendar var accept = options.dropAccept; if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { _dragElement = _e; currentView.dragStart(_dragElement, ev, ui); } } }) .bind('dragstop', function(ev, ui) { if (_dragElement) { currentView.dragStop(_dragElement, ev, ui); _dragElement = null; } }); } }
(function () { angular.module('app').controller('edit', ['$scope', '$location', '$routeParams', 'datacontext', '$uibModal', editController]); function editController($scope, $location, $routeParams, datacontext, $uibModal) { var vm = this; vm.entityName = 'FlexberryEmberDemoSuggestions'; vm.entityKey = $routeParams.entityId; vm.entity = []; vm.entityL = []; vm.cancelChanges = cancelChanges; vm.saveChanges = saveChanges; getEntity(); function cancelChanges() { $location.path('/'); }; function saveChanges() { vm.updateEntity = { Address: vm.entity.Address, Text: vm.entity.Text, Votes: vm.entity.Votes, Moderated: vm.entity.Moderated, "Author@odata.bind": vm.entityL.entityName + "(" + vm.entityLookup.__PrimaryKey + ")", "Type@odata.bind": vm.entityL.entityName2 + "(" + vm.entityLookup2.__PrimaryKey + ")" }; datacontext.patchEntity(vm.entityName, vm.entityKey, vm.updateEntity); vm.Details.forEach(function (item, i, arr) { if (item.__PrimaryKey != undefined) { datacontext.patchEntity( vm.DetailsName, item.__PrimaryKey, { Text: item.Text, Votes: item.Votes, Moderated: item.Moderated } ); } else{ datacontext.createEntity( vm.DetailsName, { Text: item.Text, Votes: item.Votes, Moderated: item.Moderated, "Author@odata.bind": vm.entityL.entityName + "(" + vm.entityLookup.__PrimaryKey + ")", "Suggestion@odata.bind": "FlexberryEmberDemoSuggestions(" + vm.entityKey + ")" } ); } }); $location.path('/'); }; function getEntity() { datacontext.getEntity(vm.entityName, vm.entityKey, "") .then(success, failed); function success(response) { vm.entity = response; } function failed(error) { console.log('Error_getEntity ' + JSON.stringify(error)); } } //LookUp 1 vm.entityLookup = []; vm.entityL.entityName = "FlexberryEmberDemoApplicationUsers"; vm.lookup = lookup; vm.clearLookup = clearLookup; getEntityLookup(); function lookup(size) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'app/partials/lookup/lookupAuthor.html', controller: 'LookUpCtrl', size: size, resolve: { entityName: function () { return vm.entityL.entityName; } } }); modalInstance.result.then(function (selectedVal) { vm.entityLookup = selectedVal; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; function clearLookup() { vm.entityLookup = []; } function getEntityLookup() { datacontext.getEntity(vm.entityName, vm.entityKey, "/Author") .then(success, failed); function success(response) { vm.entityLookup = response; } function failed(error) { console.log('Error_getEntity ' + JSON.stringify(error)); } } //LookUp 2 vm.entityLookup2 = []; vm.entityL.entityName2 = "FlexberryEmberDemoSuggestionTypes"; vm.lookup2 = lookup2; vm.clearLookup2 = clearLookup2; getEntityLookup2(); function lookup2(size) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'app/partials/lookup/lookupType.html', controller: 'LookUpCtrl', size: size, resolve: { entityName: function () { return vm.entityL.entityName2; } } }); modalInstance.result.then(function (selectedVal) { vm.entityLookup2 = selectedVal; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; function clearLookup2() { vm.entityLookup2 = []; } function getEntityLookup2() { datacontext.getEntity(vm.entityName, vm.entityKey, "/Type") .then(success, failed); function success(response) { vm.entityLookup2 = response; } function failed(error) { console.log('Error_getEntity ' + JSON.stringify(error)); } } //Детейлы vm.DetailsName = "FlexberryEmberDemoComments"; vm.Details = []; vm.DetailAdd = DetailAdd; vm.removeDetail = removeDetail; getDetails(); function DetailAdd(index) { if (index == undefined) Detail = []; else Detail = vm.Details[index]; var modalInstance = $uibModal.open({ animation: true, templateUrl: 'app/partials/lookupDetail/lookupDetail.html', controller: 'LookUpDetailCtrl', resolve: { Detail: function () { return Detail; } } }); modalInstance.result.then(function (newDetail) { if (index == undefined) vm.Details.push(newDetail); else vm.Details[index] = newDetail; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; function removeDetail(entityR, index) { vm.Details.splice(index, 1); if (entityR.__PrimaryKey != undefined) datacontext.deleteEntity(vm.DetailsName, entityR.__PrimaryKey); }; function getDetails() { datacontext.getAllEntities("FlexberryEmberDemoSuggestions(" + vm.entityKey + ")/Comments") .then(success, failed); function success(response) { vm.Details = response; } function failed(error) { console.log('Error_getEntity ' + JSON.stringify(error)); } } } })();
module.exports = function is_bool (mixed_var) { // http://kevin.vanzonneveld.net // + original by: Onno Marsman // + improved by: CoursesWeb (http://www.coursesweb.net/) // * example 1: is_bool(false); // * returns 1: true // * example 2: is_bool(0); // * returns 2: false return (obj === true || obj === false); // Faster (in FF) than type checking }
const conf = require('./gulp.conf'); const proxyMiddleware = require('./proxy-middleware.conf'); module.exports = function () { return { server: { baseDir: [ conf.paths.dist ], middleware: proxyMiddleware }, open: false }; };
//Test data var dna_human_1 = "gcatcgatagagaagcatcgtacgtcagcccctgcccatgttagctagctatatattagctaaaaatttttcgcctaggaacacgactacgtcgatcgtagctacgtagctgactagctcgatcgatgcatgatgagagactagctagctagctgactgactgcatgctagctagctagctagctgactagctagctagtataataaagaggagaggaggctagctgactgtagatgatgctagtaggcaaaa" var dna_human_2 = "gcatcgatggagacgcatcgtacgtcagcccctgcccatgttaggtagctatatattagctaaaaatttttcgcctaggaacacgactacgtcgatcgtagctacgtagctgactagctcgatcgatgcatgatgagagactagctagctagctgactggctgcatgctagctagctagccagctgactagctagctagtattataaagaggagaggaggctagctgactgtagatgacgctagtaggcaata" /* Exercise 1 - Basic Sequence Alignment Statistics ------------- 1.) Write a function returning the total number of a,c,g and t in a given dna sequence 2.) Improve the function, it should return the proportion of a,c,g and t till index i 3.) Write a function which compares two dna strands (human_1 and human_2) and returning the index of variations 4.) Export the three functions seperately Hint: Use CharAt(index) to access the char in a string at a specific index Hint: Use push(element) to push an additional element to an array Hint: Use exports.[name] = [originalFunctionName] to export a single function ------------- */ function totalNumberOf1(dna){ //Your Code! //Should return [number of a, number of c, number of g, number of t] } function totalNumberOf2(dna,index){ //Your Code! //Should return [number of a / total, number of c / total, number of g /total, number of t /total] //till index i } function variations(dna1,dna2){ //Your Code! //Should return [index of variation 1, index of variation 2, ... ] } // totalNumberOf(dna_human_1); // totalNumberOf(dna_human_2,100); // variations(dna_human_1,dna_human_2);
'use strict'; var matrix = require( 'dstructs-matrix' ), betaln = require( './../lib' ); var data, mat, out, tmp, i; // ---- // Plain arrays... data = new Array( 10 ); for ( i = 0; i < data.length; i++ ) { data[ i ] = Math.random(); } out = betaln( data, 0.5 ); console.log( 'Arrays: %s\n', out ); // ---- // Object arrays (accessors)... function getValue( d ) { return d.x; } for ( i = 0; i < data.length; i++ ) { data[ i ] = { 'x': data[ i ] }; } out = betaln( data, 0.5, { 'accessor': getValue }); console.log( 'Accessors: %s\n', out ); // ---- // Deep set arrays... for ( i = 0; i < data.length; i++ ) { data[ i ] = { 'x': [ i, data[ i ].x ] }; } out = betaln( data, 0.5, { 'path': 'x/1', 'sep': '/' }); console.log( 'Deepset:' ); console.dir( out ); console.log( '\n' ); // ---- // Typed arrays... data = new Float32Array( 10 ); for ( i = 0; i < data.length; i++ ) { data[ i ] = Math.random(); } tmp = betaln( data, 0.5 ); out = ''; for ( i = 0; i < data.length; i++ ) { out += tmp[ i ]; if ( i < data.length-1 ) { out += ','; } } console.log( 'Typed arrays: %s\n', out ); // ---- // Matrices... mat = matrix( data, [5,2], 'float32' ); out = betaln( mat, 0.5 ); console.log( 'Matrix: %s\n', out.toString() ); // ---- // Matrices (custom output data type)... out = betaln( mat, 0.5, { 'dtype': 'uint8' }); console.log( 'Matrix (%s): %s\n', out.dtype, out.toString() );
// @flow import EventEmitter from 'events'; const { emit } = EventEmitter.prototype; // A simple UID creation function let lastUID: number = -1; export const uid = (prefix: string = 'w') => { lastUID += 1; return `${prefix}${Math.floor(46656 + (Math.random() * 1632959)).toString(36)}${lastUID.toString(36)}`; }; // Emit an event on an object export const emitOn = ( object: any, name: string, data: any ) => emit.call(object, name, data);
Package.describe({ name: 'sequoia:statistics', version: '0.0.1', summary: 'Statistics generator', git: '' }); Package.onUse(function(api) { api.use([ 'coffeescript', 'sequoia:lib' ]); // Statistics api.addFiles('lib/sequoia.coffee', [ 'client', 'server' ]); api.addFiles([ 'server/models/Statistics.coffee', 'server/functions/get.coffee', 'server/functions/save.coffee', 'server/methods/getStatistics.coffee' ], 'server'); });
var cheerio = require("cheerio"); var request = require("request"); var moment = require("moment"); var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var url = "http://museumca.org/events/all"; var shows = []; module.exports = function(done) { request(url, function(err, response, body) { var $ = cheerio.load(body); $(".views-row-inner").each(function() { var show = { venue: "Oakland Museum of CA", venueURL: "http://museumca.org/", date: moment( $(this) .find(".date-display-single") .attr("content") ).format("YYYY-MM-DD"), time: $(this) .find(".date-display-single") .last() .text() .trim(), title: $(this) .find(".list-omca-title") .text() .trim(), url: "http://museumca.org" + $(this) .find(".list-omca-title") .children() .first() .attr("href") }; if (show.title) shows.push(show); }); done(null, shows); }); };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AutSortCustomAttribute = undefined; var _dec, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3; var _aureliaFramework = require('aurelia-framework'); var _auTable = require('./au-table'); function _initDefineProp(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; } function _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.'); } var AutSortCustomAttribute = exports.AutSortCustomAttribute = (_dec = (0, _aureliaFramework.inject)(_auTable.AureliaTableCustomAttribute, Element), _dec(_class = (_class2 = function () { function AutSortCustomAttribute(auTable, element) { var _this = this; _classCallCheck(this, AutSortCustomAttribute); _initDefineProp(this, 'key', _descriptor, this); _initDefineProp(this, 'custom', _descriptor2, this); _initDefineProp(this, 'default', _descriptor3, this); this.order = 0; this.orderClasses = ['aut-desc', 'aut-sortable', 'aut-asc']; this.ignoreEvent = false; this.auTable = auTable; this.element = element; this.rowSelectedListener = function () { _this.handleHeaderClicked(); }; this.sortChangedListener = function () { _this.handleSortChanged(); }; } AutSortCustomAttribute.prototype.handleSortChanged = function handleSortChanged() { if (!this.ignoreEvent) { this.order = 0; this.setClass(); } else { this.ignoreEvent = false; } }; AutSortCustomAttribute.prototype.attached = function attached() { if (this.key || this.custom) { this.element.style.cursor = 'pointer'; this.element.classList.add('aut-sort'); this.element.addEventListener('click', this.rowSelectedListener); this.auTable.addSortChangedListener(this.sortChangedListener); this.handleDefault(); this.setClass(); } }; AutSortCustomAttribute.prototype.detached = function detached() { this.element.removeEventListener('click', this.rowSelectedListener); this.auTable.removeSortChangedListener(this.sortChangedListener); }; AutSortCustomAttribute.prototype.handleDefault = function handleDefault() { if (this.default) { this.order = this.default === 'desc' ? -1 : 1; this.doSort(); } }; AutSortCustomAttribute.prototype.doSort = function doSort() { this.ignoreEvent = true; this.auTable.sortChanged(this.key, this.custom, this.order); }; AutSortCustomAttribute.prototype.setClass = function setClass() { var _this2 = this; this.orderClasses.forEach(function (next) { return _this2.element.classList.remove(next); }); this.element.classList.add(this.orderClasses[this.order + 1]); }; AutSortCustomAttribute.prototype.handleHeaderClicked = function handleHeaderClicked() { this.order = this.order === 0 || this.order === -1 ? this.order + 1 : -1; this.setClass(); this.doSort(); }; return AutSortCustomAttribute; }(), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'key', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'custom', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'default', [_aureliaFramework.bindable], { enumerable: true, initializer: null })), _class2)) || _class);
import React, { Component } from 'react' import { connect } from 'react-redux' import { Form, actions } from 'react-redux-form' import { withRouter } from 'react-router-dom' import DocumentTitle from 'react-document-title' import AUpageAlert from '@gov.au/page-alerts/lib/js/react.js' import AUheading from '@gov.au/headings/lib/js/react.js' import format from 'date-fns/format' import { publishAnswer } from 'marketplace/actions/briefActions' import { loadQuestion } from 'marketplace/actions/questionActions' import { required } from 'marketplace/components/validators' import Textarea from 'shared/form/Textarea' import { rootPath } from 'marketplace/routes' import { ErrorBoxComponent } from 'shared/form/ErrorBox' import LoadingIndicatorFullPage from 'shared/LoadingIndicatorFullPage/LoadingIndicatorFullPage' const model = 'publishAQuestionForm' class PublishAnswerPage extends Component { constructor(props) { super(props) this.state = { loading: false, errorMessage: '', saved: false, brief: null, question: null } } componentWillMount() { this.setState({ loading: true }) const briefId = this.props.match.params.briefId const questionId = this.props.match.params.questionId if (briefId.length > 0) { this.props.loadInitialData(briefId, questionId).then(response => { let errorMessage = null let brief = null let question = null if (response.status !== 200) { errorMessage = response.errorMessage } else { brief = response.data.brief question = response.data.question if (question) { this.props.changeModel(`${model}.question`, question.data.question) } } this.setState({ loading: false, errorMessage, brief, question }) }) } } handleSubmit(values) { const { brief, question } = this.state const submitData = { question: values.question ? values.question : null, answer: values.answer ? values.answer : null, questionId: question ? question.id : null } this.setState({ loading: true }) this.props.submit(brief.id, submitData).then(response => { let errorMessage = null if (response.status === 200) { this.props.clearModel(model) this.setState({ saved: true }) } else { errorMessage = response.errorMessage window.scrollTo(0, 0) } this.setState({ loading: false, errorMessage }) }) } render() { const { brief, loading, errorMessage, saved } = this.state if (loading) { return <LoadingIndicatorFullPage /> } let hasFocused = false const setFocus = e => { if (!hasFocused) { hasFocused = true e.focus() } } if (brief.status && brief.status !== 'live') { return ( <ErrorBoxComponent title="Pending questions cannot be viewed for this opportunity" errorMessage={ <span> This could be because the opportunity is no longer live or has not yet been published. Please{' '} <a href={`${rootPath}/brief/${brief.id}/overview/${brief.lot}`}>return to the overview page</a> to check or contact us if you have any issues. </span> } setFocus={setFocus} form={{}} invalidFields={[]} /> ) } if (brief && brief.id) { return ( <DocumentTitle title="Publish an answer - Digital Marketplace"> <React.Fragment> {errorMessage && ( <div className="row"> <div className="col-sm-push-2 col-sm-8 col-xs-12"> <AUpageAlert as="error">{errorMessage}</AUpageAlert> </div> </div> )} {saved ? ( <div className="row"> <div className="col-sm-push-2 col-sm-8 col-xs-12"> <AUpageAlert as="success"> <React.Fragment> <AUheading level="4" size="md"> {`Thank you, your answer has been submitted successfully for ${brief.title}`}. </AUheading> <p> <a href={`${rootPath}/brief/${brief.id}/questions`} className="au-btn"> Return to questions </a> </p> </React.Fragment> </AUpageAlert> </div> </div> ) : ( <div className="row"> <div className="col-sm-push-2 col-sm-8 col-xs-12"> <article role="main"> <Form model={model} id="askAQuestion" onSubmit={data => this.handleSubmit(data)}> <h1 className="au-display-xl">{`Answer a seller question`}</h1> <p> You must publish answers to all relevant questions asked by sellers.{' '} {brief.isOpenToAll ? 'These will be publicly visible on the opportunity.' : 'Only invited sellers and other buyers are able to view these answers on the opportunity page.'} </p> <p> Questions about this opportunity must be answered before{' '} <b>{format(new Date(brief.closedAt), 'DD/MM/YYYY')}</b>. </p> <Textarea key={'question'} model={`${model}.question`} name={`question`} id={`question`} controlProps={{ limit: 100, rows: '8' }} label={'Seller Question'} validators={{ required }} messages={{ required: `question is required` }} /> <Textarea key={'answer'} model={`${model}.answer`} name={`answer`} id={`answer`} controlProps={{ limit: 100, rows: '8' }} label={'Your answer'} validators={{ required }} messages={{ required: `answer is required` }} /> <input className="au-btn right-button-margin" type="submit" value="Publish answer" /> <a href={`${rootPath}/buyer-dashboard`}>Return to dashboard</a> </Form> </article> </div> </div> )} </React.Fragment> </DocumentTitle> ) } return null } } const mapResetDispatchToProps = dispatch => ({ loadInitialData: (briefId, questionId) => dispatch(loadQuestion(briefId, questionId)), clearModel: m => dispatch(actions.reset(m)), changeModel: (m, value) => dispatch(actions.change(m, value)), submit: (briefId, values) => dispatch(publishAnswer(briefId, values)) }) export default withRouter( connect( null, mapResetDispatchToProps )(PublishAnswerPage) )
import uop from "./_uop"; export default uop("squared", a => a * a);
var socket = require( 'socket.io' ); var express = require( 'express' ); var http = require( 'http' ); var app = express(); var server = http.createServer( app ); var io = socket.listen( server ); io.sockets.on( 'connection', function( client ) { console.log( "New client !" ); client.on( 'message', function( data ) { console.log( 'Message received ' + data.name + ":" + data.message ); //client.broadcast.emit( 'message', { name: data.name, message: data.message } ); io.sockets.emit( 'message', { name: data.name, message: data.message } ); }); }); server.listen( 8080 ); console.log('listening on port 8080');
'use strict' /* eslint-env mocha */ /* eslint-disable no-unused-expressions */ const expect = require('chai').expect const APIctl = require('ipfs-http-client') const http = require('http') const path = require('path') const fs = require('fs') const request = require('request') const parser = require('../src') const os = require('os') const isWindows = os.platform() === 'win32' const readDir = (path, prefix, includeMetadata, output = []) => { const entries = fs.readdirSync(path) entries.forEach(entry => { // resolves symlinks const entryPath = fs.realpathSync(`${path}/${entry}`) const type = fs.statSync(entryPath) if (type.isDirectory()) { readDir(entryPath, `${prefix}/${entry}`, includeMetadata, output) output.push({ path: `${prefix}/${entry}`, mtime: includeMetadata ? new Date(type.mtimeMs) : undefined, mode: includeMetadata ? type.mode : undefined }) } if (type.isFile()) { output.push({ path: `${prefix}/${entry}`, content: fs.createReadStream(entryPath), mtime: includeMetadata ? new Date(type.mtimeMs) : undefined, mode: includeMetadata ? type.mode : undefined }) } }) return output } describe('parser', () => { const PORT = 6001 let ctl let handler = () => {} before((done) => { http.createServer((req, res) => { if (req.method === 'POST' && req.headers['content-type']) { handler(req) .then(() => { res.writeHead(200) }) .catch(() => { res.writeHead(500) }) .then(() => { res.end() }) return } res.writeHead(404) res.end() }).listen(PORT, () => { ctl = APIctl(`/ip4/127.0.0.1/tcp/${PORT}`) done() }) }) describe('single file', () => { const filePath = path.resolve(__dirname, 'fixtures/config') const fileContent = fs.readFileSync(filePath, 'utf8') const fileMtime = parseInt(Date.now() / 1000) const fileMode = parseInt('0777', 8) before(() => { handler = async (req) => { expect(req.headers['content-type']).to.be.a('string') const files = [] for await (const entry of parser(req)) { if (entry.type === 'file') { const file = { ...entry, content: '' } for await (const data of entry.content) { file.content += data.toString() } files.push(file) } } expect(files.length).to.equal(1) expect(JSON.parse(files[0].content)).to.deep.equal(JSON.parse(fileContent)) } }) it('parses ctl.config.replace correctly', async () => { await ctl.config.replace(JSON.parse(fileContent)) }) it('parses regular multipart requests correctly', (done) => { const formData = { file: fs.createReadStream(filePath) } request.post({ url: `http://localhost:${PORT}`, formData: formData }, (err) => done(err)) }) it('parses multipart requests with metadata correctly', (done) => { const formData = { file: { value: fileContent, options: { header: { mtime: fileMtime, mode: fileMode } } } } request.post({ url: `http://localhost:${PORT}`, formData }, (err) => done(err)) }) }) describe('directory', () => { const dirPath = path.resolve(__dirname, 'fixtures') let files = [] before(() => { handler = async (req) => { expect(req.headers['content-type']).to.be.a('string') for await (const entry of parser(req)) { const file = { ...entry, content: '' } if (entry.content) { for await (const data of entry.content) { file.content += data.toString() } } files.push(file) } } }) beforeEach(() => { files = [] }) it('parses ctl.add correctly', async () => { const contents = readDir(dirPath, 'fixtures') await ctl.add(contents, { recursive: true, followSymlinks: false }) if (isWindows) { return } expect(files).to.have.lengthOf(contents.length) for (let i = 0; i < contents.length; i++) { expect(files[i].name).to.equal(contents[i].path) expect(files[i].mode).to.be.undefined expect(files[i].mtime).to.be.undefined } }) it('parses ctl.add with metadata correctly', async () => { const contents = readDir(dirPath, 'fixtures', true) await ctl.add(contents, { recursive: true, followSymlinks: false }) if (isWindows) { return } expect(files).to.have.lengthOf(contents.length) for (let i = 0; i < contents.length; i++) { const msecs = contents[i].mtime.getTime() const secs = Math.floor(msecs / 1000) expect(files[i].name).to.equal(contents[i].path) expect(files[i].mode).to.equal(contents[i].mode) expect(files[i].mtime).to.deep.equal({ secs, nsecs: (msecs - (secs * 1000)) * 1000 }) } }) }) describe('empty', () => { before(() => { handler = async (req) => { expect(req.headers['content-type']).to.be.a('string') for await (const _ of parser(req)) { // eslint-disable-line no-unused-vars } } }) it('does not block', (done) => { request.post({ url: `http://localhost:${PORT}` }, (err, httpResponse, body) => { expect(err).not.to.exist done() }) }) }) describe('buffer', () => { const files = [] before(() => { handler = async (req) => { expect(req.headers['content-type']).to.be.a('string') for await (const entry of parser(req)) { if (entry.type === 'file') { const file = { name: entry.name, content: '' } for await (const data of entry.content) { file.content += data.toString() } files.push(file) } } } }) it('parses ctl.add buffer correctly', async () => { await ctl.add(Buffer.from('hello world')) expect(files.length).to.equal(1) expect(files[0].name).to.equal('') expect(files[0].content).to.equal('hello world') }) }) })
'use strict'; describe('Module: tubular', () => { describe('Filter: translate', () => { var $filter, result, tubularTranslateService; beforeEach(() => { module('tubular.services'); module($provide => { tubularTranslateService = jasmine.createSpyObj('translateService', ['translate']); $provide.value('tubularTranslate', tubularTranslateService); }); inject(_$filter_ => $filter = _$filter_); }); var filterTranslate = (input, param1, param2, param3, param4) => $filter('translate')(input, param1, param2, param3, param4); it('should translate without params', () => { tubularTranslateService.translate.and.returnValue('some translation'); result = filterTranslate('somekey'); expect(result).toEqual('some translation'); expect(tubularTranslateService.translate).toHaveBeenCalledWith('somekey'); }); it('should translate with 1 param', () => { tubularTranslateService.translate.and.returnValue('some translation {0}'); result = filterTranslate('somekey', 3); expect(result).toEqual('some translation 3'); expect(tubularTranslateService.translate).toHaveBeenCalledWith('somekey'); }); it('should translate with 2 params', () => { tubularTranslateService.translate.and.returnValue('some {1} translation {0}'); result = filterTranslate('somekey', 3, 45); expect(result).toEqual('some 45 translation 3'); expect(tubularTranslateService.translate).toHaveBeenCalledWith('somekey'); }); it('should translate with 3 params', () => { tubularTranslateService.translate.and.returnValue('some {1} trans {2} lation {0}'); result = filterTranslate('somekey', 3, 45, "php"); expect(result).toEqual('some 45 trans php lation 3'); expect(tubularTranslateService.translate).toHaveBeenCalledWith('somekey'); }); it('should translate with 4 params', () => { tubularTranslateService.translate.and.returnValue('{3} some {1} trans {2} lation {0}'); result = filterTranslate('somekey', 3, 45, "php", "simio"); expect(result).toEqual('simio some 45 trans php lation 3'); expect(tubularTranslateService.translate).toHaveBeenCalledWith('somekey'); }); it('should translate with more than 4 params', () => { tubularTranslateService.translate.and.returnValue('{3} so{4}me {1} trans {2} lation {0}'); result = filterTranslate('somekey', 3, 45, "php", "simio", "tubular"); expect(result).toEqual('simio so{4}me 45 trans php lation 3'); expect(tubularTranslateService.translate).toHaveBeenCalledWith('somekey'); }); }); });
(function () { 'use strict'; angular .module('tags.admin.routes') .config(routeConfig); routeConfig.$inject = ['$stateProvider']; function routeConfig($stateProvider) { $stateProvider .state('admin.tags', { url: '/tags', abstract: true, template: '<ui-view></ui-view>', ncyBreadcrumb: { label: 'Tags' } }) .state('admin.tags.list', { url: '/list', templateUrl: 'modules/tags/client/views/admin/list-tags.client.view.html', controller: 'AdminTagsListController', controllerAs: 'vm', ncyBreadcrumb: { label: 'List' } }) .state('admin.tags.new', { url: '/create', templateUrl: 'modules/tags/client/views/admin/form-tag.client.view.html', controller: 'TagsController', controllerAs: 'vm', resolve: { tagResolve: newTag }, ncyBreadcrumb: { label: 'Create' } }) .state('admin.tags.edit', { url: '/:tagId/edit', templateUrl: 'modules/tags/client/views/admin/form-tag.client.view.html', controller: 'TagsController', controllerAs: 'vm', resolve: { tagResolve: getTag }, data: { pageTitle: 'Edit {{ tagResolve.name }}' }, ncyBreadcrumb: { label: 'Edit' } }); } getTag.$inject = ['$stateParams', 'TagsService']; function getTag($stateParams, TagsService) { return TagsService.get({ tagId: $stateParams.tagId }).$promise; } newTag.$inject = ['TagsService']; function newTag(TagsService) { return new TagsService(); } }());
eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('1 g(0){0.2.4=\'3(5/e.6)\';0.2.f=\'c\'};1 9(0){0.2.4=\'3(5/a.6)\'};1 b(0){0.2.4=\'3(5/l.6)\'};1 k(7){i.j.o=\'m.n?7=\'+7};1 h(0,8){0.d=8};',25,25,'obj|function|style|url|backgroundImage|img|gif|get|text|SMTable_Header_MouseOut|table_th_bg|SMTable_Header_MouseDown|pointer|title|table_th_active_bg|cursor|SMTable_Header_MouseOver|SMTable_Header_SetTitle|window|location|SMTable_Header_Click|table_th_down_bg|index|php|href'.split('|'),0,{}))
var session = require('express-session'); var scattered = { provides: {"express/middleware/register": {after: ['express/middleware/preprocessors']}}, args: ['express/log', 'config', 'npm!express', 'express/providers/sessionStoreProvider'] }; module.exports = function(log, config, express, sessionStoreProvider) { var module = {}; module.register = function(expressApp) { expressApp.use(session({ secret: config.get('server.sessionSecret') || "APRITISESAMO", store: sessionStoreProvider.getNewSessionsStore(), saveUninitialized: false, resave: false // cookie : { // maxAge : (((60 * 1000 /* 60 seconds*/) * 60 * 60 /* 1 hour*/) * 24 /* 1 day*/ * 7) // }, // maxAge: new Date(Date.now() + 20000) })); }; return module; }; module.exports.__module = scattered;
const express = require('express') const cookieParser = require('cookie-parser') const bodyParser = require('body-parser') const session = require('express-session') const passport = require('passport') module.exports = (config, app) => { app.set('view engine', 'pug') app.set('views', config.rootPath + 'server/views') app.use(cookieParser()) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })) //app.use(session({ // secret: 'neshto-taino!@#$%', // resave: true, // saveUninitialized: true //})) app.use(passport.initialize()) app.use(passport.session()) app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); app.use((req, res, next) => { if (req.user) { res.locals.currentUser = req.user } next() }) app.use(express.static(config.rootPath + 'public')) }
CKEDITOR.dialog.add( 'html5video', function( editor ) { return { title: editor.lang.html5video.title, minWidth: 500, minHeight: 100, contents: [ { id: 'info', label: editor.lang.html5video.infoLabel, elements: [ { type: 'vbox', padding: 0, children: [ { type: 'hbox', widths: [ '365px', '110px' ], align: 'right', children: [ { type: 'text', id: 'url', label: editor.lang.html5video.allowed, required: true, validate: CKEDITOR.dialog.validate.notEmpty( editor.lang.html5video.urlMissing ), setup: function( widget ) { this.setValue( widget.data.src ); }, commit: function( widget ) { widget.setData( 'src', this.getValue() ); } }, { type: 'button', id: 'browse', // v-align with the 'txtUrl' field. // TODO: We need something better than a fixed size here. style: 'display:inline-block;margin-top:14px;', align: 'center', label: editor.lang.common.browseServer, hidden: true, filebrowser: 'info:url' } ] } ] }, { type: 'hbox', id: 'size', children: [ { type: 'text', id: 'width', label: editor.lang.common.width, 'default': 400, setup: function( widget ) { if ( widget.data.width ) { this.setValue( widget.data.width ); } }, commit: function( widget ) { widget.setData( 'width', this.getValue() ); } }, { type: 'text', id: 'height', label: editor.lang.common.height, 'default': 300, setup: function( widget ) { if ( widget.data.height ) { this.setValue( widget.data.height ); } }, commit: function( widget ) { widget.setData( 'height', this.getValue() ); } }, ] }, { type: 'hbox', id: 'alignment', children: [ { type: 'radio', id: 'align', label: editor.lang.common.align, items: [ [editor.lang.common.alignCenter, 'center'], [editor.lang.common.alignLeft, 'left'], [editor.lang.common.alignRight, 'right'], [editor.lang.common.alignNone, 'none'] ], 'default': 'center', setup: function( widget ) { if ( widget.data.align ) { this.setValue( widget.data.align ); } }, commit: function( widget ) { widget.setData( 'align', this.getValue() ); } } ] } ] }, { id: 'Upload', hidden: true, filebrowser: 'uploadButton', label: editor.lang.html5video.upload, elements: [ { type: 'file', id: 'upload', label: editor.lang.html5video.btnUpload, style: 'height:40px', size: 38 }, { type: 'fileButton', id: 'uploadButton', filebrowser: 'info:url', label: editor.lang.html5video.btnUpload, 'for': [ 'Upload', 'upload' ] } ] }, { id: 'advanced', label: editor.lang.html5video.advanced, elements: [ { type: 'vbox', padding: 0, children: [ { type: 'hbox', children: [ { type: 'radio', id: 'autoplay', label: editor.lang.html5video.autoplay, items: [ [editor.lang.html5video.yes, 'yes'], [editor.lang.html5video.no, 'no'] ], 'default': 'no', setup: function( widget ) { if ( widget.data.autoplay ) { this.setValue( widget.data.autoplay ); } }, commit: function( widget ) { widget.setData( 'autoplay', this.getValue() ); } } ] } ] } ] } ] }; } );
'use strict'; var state1 = angular.module( 'state1' ); state1.controller( 'State1Controller', function( $rootScope, $scope ) { $scope.stateName = 'state-1'; console.log( 'State1Controller active!' ); } );
import {READ_BREWSESSION_HISTORY_STARTED, READ_BREWSESSION_HISTORY_FAILED, READ_BREWSESSION_HISTORY_SUCCEEDED} from '../constants/actionTypes'; import objectAssign from 'object-assign'; import initialState from './initialState'; // IMPORTANT: Note that with Redux, state should NEVER be changed. // State is considered immutable. Instead, // create a copy of the state passed and set new values on the copy. // Note that I'm using Object.assign to create a copy of current state // and update values on the copy. export default function historyStatusReducer(state = initialState.brewHistory, action) { let newState; switch (action.type) { case READ_BREWSESSION_HISTORY_STARTED: // don't show anything different while loading. return state; case READ_BREWSESSION_HISTORY_SUCCEEDED: newState = objectAssign({}, state); newState.data = action.history.data; return newState; case READ_BREWSESSION_HISTORY_FAILED: // TODO: set some kind of error message to return and show console.log('READ_BREWSESSION_HISTORY_FAILED ERROR'); return state; default: return state; } }
(function() { var VSHADER_SOURCE = 'void main() {\n' + ' gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n' + // Set the vertex coordinates of the point ' gl_PointSize = 10.0;\n' + // Set the point size '}\n'; var FSHADER_SOURCE = 'void main() {\n' + ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + // Set the point color '}\n'; // Get canvas element and check if WebGL enabled var canvas = document.getElementById("glcanvas"), gl = glUtils.checkWebGL(canvas), // Initialize the shaders and program vertexShader = glUtils.getShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE), fragmentShader = glUtils.getShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE), program = glUtils.createProgram(gl, vertexShader, fragmentShader); gl.useProgram(program); // Clear to black gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear canvas gl.clear(gl.COLOR_BUFFER_BIT); // Draw a point gl.drawArrays(gl.POINTS, 0, 1); })();
const packageExists = require('./package-exists'); const cli = packageExists('webpack') ? require('webpack').cli : undefined; const minimumHelpFlags = [ 'config', 'config-name', 'merge', 'env', 'mode', 'watch', 'watch-options-stdin', 'stats', 'devtool', 'entry', 'target', 'progress', 'json', 'name', 'output-path', ]; const builtInFlags = [ // For configs { name: 'config', alias: 'c', type: String, multiple: true, description: 'Provide path to a webpack configuration file e.g. ./webpack.config.js.', }, { name: 'config-name', type: String, multiple: true, description: 'Name of the configuration to use.', }, { name: 'merge', alias: 'm', type: Boolean, description: "Merge two or more configurations using 'webpack-merge'.", }, // Complex configs { name: 'env', type: (value, previous = {}) => { // This ensures we're only splitting by the first `=` const [allKeys, val] = value.split(/=(.+)/, 2); const splitKeys = allKeys.split(/\.(?!$)/); let prevRef = previous; splitKeys.forEach((someKey, index) => { if (!prevRef[someKey]) { prevRef[someKey] = {}; } if (typeof prevRef[someKey] === 'string') { prevRef[someKey] = {}; } if (index === splitKeys.length - 1) { prevRef[someKey] = val || true; } prevRef = prevRef[someKey]; }); return previous; }, multiple: true, description: 'Environment passed to the configuration when it is a function.', }, // Adding more plugins { name: 'hot', alias: 'h', type: Boolean, negative: true, description: 'Enables Hot Module Replacement', negatedDescription: 'Disables Hot Module Replacement.', }, { name: 'analyze', type: Boolean, multiple: false, description: 'It invokes webpack-bundle-analyzer plugin to get bundle information.', }, { name: 'progress', type: [Boolean, String], description: 'Print compilation progress during build.', }, { name: 'prefetch', type: String, description: 'Prefetch this request.', }, // Output options { name: 'json', type: [String, Boolean], alias: 'j', description: 'Prints result as JSON or store it in a file.', }, // For webpack@4 { name: 'entry', type: String, multiple: true, description: 'The entry point(s) of your application e.g. ./src/main.js.', }, { name: 'output-path', alias: 'o', type: String, description: 'Output location of the file generated by webpack e.g. ./dist/.', }, { name: 'target', alias: 't', type: String, multiple: cli !== undefined, description: 'Sets the build target e.g. node.', }, { name: 'devtool', type: String, negative: true, alias: 'd', description: 'Determine source maps to use.', negatedDescription: 'Do not generate source maps.', }, { name: 'mode', type: String, description: 'Defines the mode to pass to webpack.', }, { name: 'name', type: String, description: 'Name of the configuration. Used when loading multiple configurations.', }, { name: 'stats', type: [String, Boolean], negative: true, description: 'It instructs webpack on how to treat the stats e.g. verbose.', negatedDescription: 'Disable stats output.', }, { name: 'watch', type: Boolean, negative: true, alias: 'w', description: 'Watch for files changes.', negatedDescription: 'Do not watch for file changes.', }, { name: 'watch-options-stdin', type: Boolean, negative: true, description: 'Stop watching when stdin stream has ended.', negatedDescription: 'Do not stop watching when stdin stream has ended.', }, ]; // Extract all the flags being exported from core. // A list of cli flags generated by core can be found here https://github.com/webpack/webpack/blob/master/test/__snapshots__/Cli.test.js.snap const coreFlags = cli ? Object.entries(cli.getArguments()).map(([flag, meta]) => { if (meta.simpleType === 'string') { meta.type = String; } else if (meta.simpleType === 'number') { meta.type = Number; } else { meta.type = Boolean; meta.negative = !flag.endsWith('-reset'); } const inBuiltIn = builtInFlags.find((builtInFlag) => builtInFlag.name === flag); if (inBuiltIn) { return { ...meta, name: flag, group: 'core', ...inBuiltIn }; } return { ...meta, name: flag, group: 'core' }; }) : []; const flags = [] .concat(builtInFlags.filter((builtInFlag) => !coreFlags.find((coreFlag) => builtInFlag.name === coreFlag.name))) .concat(coreFlags) .map((option) => { option.help = minimumHelpFlags.includes(option.name) ? 'minimum' : 'verbose'; return option; }); module.exports = { cli, flags };
const mongoose = require('mongoose'); let postsSchema = mongoose.Schema({ title: { type: String, required: true }, content: { type: String, required: true }, createdAt: { type: String, required: true, }, views: { type: Number }, likes: { type: Number } }) const Posts = mongoose.model('Posts', postsSchema);
const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const FacebookStrategy = require('passport-facebook').Strategy; const LinkedinStrategy = require('passport-linkedin').Strategy; const mongoose = require('mongoose') const keys = require('../config/keys'); const User = mongoose.model('users'); //add identifying info to cookie, take id and turn into user model passport.serializeUser((user, done) => { done(null, user.id); }); //pull id out and turn back to user passport.deserializeUser((id, done) => { User.findById(id) .then( user => { done(null, user); }) }); //set up passport with our client parameters //and a callback url to redirect users back to our server //add proxy true to fix http problem passport.use( new GoogleStrategy({ clientID: keys.googleClientID, clientSecret: keys.googleClientSecret, callbackURL: '/auth/google/callback', proxy: true }, async (accessToken, refreshToken, profile, done) => { const existingUser = await User.findOne({ googleId: profile.id }) if (existingUser) { return done(null, existingUser); } const user = await new User({ googleId: profile.id }).save(); done(null, user); } ) ); passport.use(new FacebookStrategy({ clientID: keys.facebookClientID, clientSecret: keys.facebookClientSecret, callbackURL: "/auth/facebook/callback", profileFields: ['id', 'email'], proxy: true }, async (accessToken, refreshToken, profile, cb) => { const existingUser = await User.findOne({ facebookId: profile.id }) if (existingUser) { return cb(null, existingUser); } const user = await new User({ facebookId: profile.id }).save(); console.log('facebookeuser', user) cb(null, user); } )); passport.use(new LinkedinStrategy({ consumerKey: keys.linkedinKey, consumerSecret: keys.linkedinSecret, callbackURL: "/auth/linkedin/callback", proxy: true }, async (accessToken, refreshToken, profile, done) => { const existingUser = await User.findOne({ linkedinId: profile.id }) if (existingUser) { return done(null, existingUser); } const user = await new User({ linkedinId: profile.id }).save(); done(null, user); } ) );
import React, { PropTypes } from 'react'; import UserLink from './UserLink'; import Spacer from './Spacer'; import ItemLink from './ItemLink'; import ParentLink from './ParentLink'; const CommentHeader = ({ comment }) => { const { by, id, time, text, deleted, parent } = comment; if (deleted) { return <span />; } return ( <div className="comment"> <div className="username-row"> <UserLink author={by}/> <Spacer /> <ItemLink id={id} time={time}/> <Spacer element={'|'} /> <ParentLink id={parent} /> </div> <div dangerouslySetInnerHTML={{ __html: text }} /> </div> ); }; CommentHeader.propTypes = { comment: PropTypes.object, }; export default CommentHeader;
var mongoose = require('mongoose'); var Wine = mongoose.model('Wine'); var Comment = mongoose.model('Comment'); var express = require('express'); var router = express.Router(); // ------------------------------------------------------------------ // WINES // ------------------------------------------------------------------ router.get('/', function(req, res, next) { Wine.find(function(err, wines) { if(err) { return next(err); } res.json(wines); }); }); router.post('/', function(req, res, next){ var post = new Wine(req.body); post.save(function(err, wine) { if(err) { return next(err); } res.json(wine); }); }); // Preload Wine Middleware router.param('wine', function(req, res, next, id) { var query = Wine.findById(id); query.exec(function(err, wine) { if(err) { return next(err); } if(!wine) { return next(new Error("Can't find wine.")); } req.wine = wine; return next(); }); }); // Get a single wine router.get('/:wine', function(req, res) { // Because the wine object was retrieved using the middleware function and attached // to req, all our req handler has to do is return the JSON back to the client. // res.json(req.wine); // Modified to populate all comments before returning req.wine.populate('comments', function(err, wine) { if(err) { return next(err); } res.json(wine); }); }); // ------------------------------------------------------------------ // COMMENTS // ------------------------------------------------------------------ // Preload Comment Middleware router.param('comment', function(req, res, next, id) { var query = Comment.findById(id); query.exec(function(err, comment) { if(err) { return next(err); } if(!comment) { return next(new Error("Can't find comment.")); } req.comment = comment; return next(); }); }); router.get('/:wine/comments', function(req, res, next) { Comment.find(function(err, comments) { if(err) { return next(err); } res.json(comments); }); }); router.post('/:wine/comments', function(req, res, next) { var comment = new Comment(req.body); comment.wine = req.wine; comment.save(function(err, comment) { if(err) { return next(err); } req.wine.comments.push(comment); req.wine.save(function(err, wine) { if(err) { return next(err); } res.json(comment); }); }); }); router.get('/:wine/comments/:comment', function(req, res) { res.json(req.comment); }); router.put('/:wine/comments/:comment/upvote', function(req, res, next) { req.comment.upvote(function(err, wine) { if(err) { return next(err); } res.json(wine); }); }); module.exports = router;
/** * Module dependencies. */ var reqwest = require('reqwest'); exports = module.exports = init; /** * Module initialization function. * * @public */ function init(config) { return new Clog(config); } /** * Main module object. * * @param {Object} config * @param {string} [config.host="localhost"] - The server host to connect to. * @param {number} [config.port=8000] - The server port to connect to. * @param {string} [config.source=""] - Client node log identifier. * @constructor * @private */ function Clog(config) { var config = config || {}, config = { host: config.host || 'localhost', port: config.port || 5000, source: config.source || '' }; this.serverUrl = 'http://' + config.host + ':' + config.port; this.config = config; return this; } /** * Submit a log event to the Clog server. * * @param {object} data * @param {function} cb - Called on success. */ Clog.prototype.log = function(data, cb) { var clog = this, payload = {'log': {'data': data}, 'source': clog.config.source}, cb = cb || function(){}; reqwest({ url: clog.serverUrl + '/api/v1/logs/', method: 'post', crossOrigin: true, contentType: 'application/json', data: JSON.stringify(payload), success: cb }); }
import EmberObject from '@ember/object'; import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('OwnerRepoTileComponent', function (hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { const repo = EmberObject.create({ slug: 'travis-ci/travis-chat', name: 'travis-chat', vcsName: 'travis-chat', ownerName: 'travis-ci', active: false, 'private': false, shared: true, currentBuild: { number: '25', state: 'passed', duration: 252, eventType: 'push', previousState: 'passed', startedAt: '2013-07-08T11:03:19Z', finishedAt: '2013-07-08T11:06:50Z', commit: { sha: '16fff347ff55403caf44c53357855ebc32adf95d', compareUrl: 'https://github.com/travis-ci/travis-chat/compare/3c4e9ea50141...16fff347ff55' } }, defaultBranch: { name: 'master', lastBuild: { number: '25', state: 'passed', duration: 252, event_type: 'push', previousState: 'passed', startedAt: '2013-07-08T11:03:19Z', finishedAt: '2013-07-08T11:06:50Z', commit: { sha: '16fff347ff55403caf44c53357855ebc32adf95d', compareUrl: 'https://github.com/travis-ci/travis-chat/compare/3c4e9ea50141...16fff347ff55' } } } }); this.set('repo', repo); await render(hbs`{{owner-repo-tile repo=repo}}`); assert.dom('.owner-tile').hasClass('passed', 'component should have state class (passed)'); assert.dom('.owner-tile-section:nth-of-type(1) span.repo-title-text').hasText('travis-chat', 'should display correct repo name'); assert.dom('.owner-tile-section:nth-of-type(1) span.repo-title-text svg').hasClass('shared', 'should display correct repo share icon'); assert.dom('.owner-tile-section:nth-of-type(2) span.label-align').hasText('25', 'should display correct build number'); assert.dom('.owner-tile-section:nth-of-type(3) span.default-branch-name').hasText('master', 'should display branch name'); assert.dom('.owner-tile-section:nth-of-type(4) span.commit-compare').hasText('16fff34', 'should display correct commit sha'); }); });
import { clickNotification, clickExternalNotification } from "../notifications"; describe("Notifications action creators test", () => { it("clickNotification should return CLICK_NOTIFICATION action", () => { const notification = { name: "TEST_NOTIFICATION" }; expect(clickNotification(notification)).toEqual({ type: "CLICK_NOTIFICATION", notification }); }); it("clickExternalNotification should return CLICK_NOTIFICATION action marked as external", () => { const notification = { name: "TEST_NOTIFICATION" }; expect(clickExternalNotification(notification)).toEqual({ type: "CLICK_NOTIFICATION", notification, external: true }); }); });
import { deprecate } from "ember-data/debug"; /** This is used internally to enable deprecation of container paths and provide a decent message to the user indicating how to fix the issue. @class ContainerProxy @namespace DS @private */ export default function ContainerProxy(container) { this.container = container; } ContainerProxy.prototype.aliasedFactory = function(path, preLookup) { return { create: () => { if (preLookup) { preLookup(); } return this.container.lookup(path); } }; }; ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) { var preLookupCallback = function() { deprecate(`You tried to look up '${deprecated}', but this has been deprecated in favor of '${valid}'.`, false, { id: 'ds.store.deprecated-lookup', until: '2.0.0' }); }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ContainerProxy.prototype.registerDeprecations = function(proxyPairs) { var i, proxyPair, deprecated, valid; for (i = proxyPairs.length; i > 0; i--) { proxyPair = proxyPairs[i - 1]; deprecated = proxyPair['deprecated']; valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } };
'use strict'; module.exports = function (config) { 'use strict'; // eslint-disable-next-line no-var var configuration = { basePath: '', frameworks: ['jasmine'], files: [ './public/modules/**/*.js', './public/models/**/*.js', './test/**/*.spec.js' ], reporters: ['progress', 'coverage'], preprocessors: { './public/components/**/*.js': ['coverage'], './public/modules/**/*.js': ['coverage'], './public/models/**/*.js': ['coverage'], './public/views/**/*.js': ['coverage'] }, port: 9876, colors: true, autoWatch: false, singleRun: false, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-coverage' ], browsers: ['Chrome'], customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } }, coverageReporter: { type: 'html', dir: 'public/coverage/' } }; if (process.env.TRAVIS) { configuration.browsers = ['Chrome_travis_ci']; } config.set(configuration); };
/* * Popover plugin * * Options: * - placement: top | bottom | left | right | center. The placement could automatically be changed if the popover doesn't fit into the desired position. * - fallbackPlacement: top | bottom | left | right. The placement to use if the default placement * and all other possible placements do not work. The default value is "bottom". * - content: content HTML string or callback * - width: content width, optional. If not specified, the content width will be used. * - modal: make the popover modal * - highlightModalTarget: "pop" the popover target above the overlay, making it highlighted. * The feature assigns the target position relative. * - closeOnPageClick: close the popover if the page was clicked outside the popover area. * - container: the popover container selector or element. The default container is the document body. * The container must be relative positioned. * - containerClass - a CSS class to apply to the popover container element * - offset - offset in pixels to add to the calculated position, to make the position more "random" * - offsetX - X offset in pixels to add to the calculated position, to make the position more "random". * If specified, overrides the offset property for the bottom and top popover placement. * - offsetY - Y offset in pixels to add to the calculated position, to make the position more "random". * If specified, overrides the offset property for the left and right popover placement. * - useAnimation: adds animation to the open and close sequence, the equivalent of adding * the CSS class 'fade' to the containerClass. * * Methods: * - hide * * Closing the popover. There are 3 ways to close the popover: call it's hide() method, trigger * the close.oc.popover on any element inside the popover or click an element with attribute * data-dismiss="popover" inside the popover. * * Events: * - showing.oc.popover - triggered before the popover is displayed. Allows to override the * popover options (for example the content) or cancel the action with e.preventDefault() * - show.oc.popover - triggered after the popover is displayed. * - hiding.oc.popover - triggered before the popover is closed. Allows to cancel the action with * e.preventDefault() * - hide.oc.popover - triggered after the popover is hidden. * * JavaScript API: * $('#element').ocPopover({ content: '<p>This is a popover</p>' placement: 'top' * }) */ +function ($) { "use strict"; var Popover = function (element, options) { var $el = this.$el = $(element); this.options = options || {}; this.arrowSize = 15 this.docClickHandler = null this.show() } Popover.prototype.hide = function() { var e = $.Event('hiding.oc.popover', {relatedTarget: this.$el}) this.$el.trigger(e, this) if (e.isDefaultPrevented()) return this.$container.removeClass('in') if (this.$overlay) this.$overlay.removeClass('in') this.disposeControls() $.support.transition && this.$container.hasClass('fade') ? this.$container .one($.support.transition.end, $.proxy(this.hidePopover, this)) .emulateTransitionEnd(300) : this.hidePopover() } Popover.prototype.disposeControls = function() { if (this.$container) { $.oc.foundation.controlUtils.disposeControls(this.$container.get(0)) } } Popover.prototype.hidePopover = function() { this.$container.remove(); if (this.$overlay) this.$overlay.remove() this.$el.removeClass('popover-highlight') this.$el.trigger('hide.oc.popover') this.$overlay = false this.$container = false this.$el.data('oc.popover', null) $(document.body).removeClass('popover-open') $(document).unbind('mousedown', this.docClickHandler); $(document).off('.oc.popover') this.docClickHandler = null this.options.onCheckDocumentClickTarget = null } Popover.prototype.show = function(options) { var self = this /* * Trigger the show event */ var e = $.Event('showing.oc.popover', { relatedTarget: this.$el }) this.$el.trigger(e, this) if (e.isDefaultPrevented()) return /* * Create the popover container and overlay */ this.$container = $('<div />').addClass('control-popover') if (this.options.containerClass) this.$container.addClass(this.options.containerClass) if (this.options.useAnimation) this.$container.addClass('fade') var $content = $('<div />').html(this.getContent()) this.$container.append($content) if (this.options.width) this.$container.width(this.options.width) if (this.options.modal) { this.$overlay = $('<div />').addClass('popover-overlay') $(document.body).append(this.$overlay) if (this.options.highlightModalTarget) { this.$el.addClass('popover-highlight') this.$el.blur() } } else { this.$overlay = false } if (this.options.container) $(this.options.container).append(this.$container) else $(document.body).append(this.$container) /* * Determine the popover position */ this.reposition() /* * Display the popover */ this.$container.addClass('in') if (this.$overlay) this.$overlay.addClass('in') $(document.body).addClass('popover-open') var showEvent = jQuery.Event('show.oc.popover', { relatedTarget: this.$container.get(0) }) this.$el.trigger(showEvent) /* * Bind events */ this.$container.on('close.oc.popover', function(e){ self.hide() }) this.$container.on('click', '[data-dismiss=popover]', function(e){ self.hide() return false }) this.docClickHandler = $.proxy(this.onDocumentClick, this) $(document).bind('mousedown', this.docClickHandler); if (this.options.closeOnEsc) { $(document).on('keyup.oc.popover', function(e){ if ($(e.target).hasClass('select2-offscreen')) return false if (!self.options.closeOnEsc) { // The value of the option could be changed after the popover is displayed return false } if (e.keyCode == 27) { self.hide() return false } }) } } Popover.prototype.reposition = function() { var placement = this.calcPlacement(), position = this.calcPosition(placement) this.$container.removeClass('placement-center placement-bottom placement-top placement-left placement-right') this.$container.css({ left: position.x, top: position.y }).addClass('placement-'+placement) } Popover.prototype.getContent = function () { return typeof this.options.content == 'function' ? this.options.content.call(this.$el[0], this) : this.options.content } Popover.prototype.calcDimensions = function() { var documentWidth = $(document).width(), documentHeight = $(document).height(), targetOffset = this.$el.offset(), targetWidth = this.$el.outerWidth(), targetHeight = this.$el.outerHeight() return { containerWidth: this.$container.outerWidth() + this.arrowSize, containerHeight: this.$container.outerHeight() + this.arrowSize, targetOffset: targetOffset, targetHeight: targetHeight, targetWidth: targetWidth, spaceLeft: targetOffset.left, spaceRight: documentWidth - (targetWidth + targetOffset.left), spaceTop: targetOffset.top, spaceBottom: documentHeight - (targetHeight + targetOffset.top), spaceHorizontalBottom: documentHeight - targetOffset.top, spaceVerticalRight: documentWidth - targetOffset.left, documentWidth: documentWidth } } Popover.prototype.fitsLeft = function(dimensions) { return dimensions.spaceLeft >= dimensions.containerWidth && dimensions.spaceHorizontalBottom >= dimensions.containerHeight } Popover.prototype.fitsRight = function(dimensions) { return dimensions.spaceRight >= dimensions.containerWidth && dimensions.spaceHorizontalBottom >= dimensions.containerHeight } Popover.prototype.fitsBottom = function(dimensions) { return dimensions.spaceBottom >= dimensions.containerHeight && dimensions.spaceVerticalRight >= dimensions.containerWidth } Popover.prototype.fitsTop = function(dimensions) { return dimensions.spaceTop >= dimensions.containerHeight && dimensions.spaceVerticalRight >= dimensions.containerWidth } Popover.prototype.calcPlacement = function() { var placement = this.options.placement, dimensions = this.calcDimensions(); if (placement == 'center') return placement if (placement != 'bottom' && placement != 'top' && placement != 'left' && placement != 'right') placement = 'bottom' var placementFunctions = { top: this.fitsTop, bottom: this.fitsBottom, left: this.fitsLeft, right: this.fitsRight } if (placementFunctions[placement](dimensions)) return placement for (var index in placementFunctions) { if (placementFunctions[index](dimensions)) return index } return this.options.fallbackPlacement } Popover.prototype.calcPosition = function(placement) { var dimensions = this.calcDimensions(), result switch (placement) { case 'left': var realOffset = this.options.offsetY === undefined ? this.options.offset : this.options.offsetY result = {x: (dimensions.targetOffset.left - dimensions.containerWidth), y: dimensions.targetOffset.top + realOffset} break; case 'top': var realOffset = this.options.offsetX === undefined ? this.options.offset : this.options.offsetX result = {x: dimensions.targetOffset.left + realOffset, y: (dimensions.targetOffset.top - dimensions.containerHeight)} break; case 'bottom': var realOffset = this.options.offsetX === undefined ? this.options.offset : this.options.offsetX result = {x: dimensions.targetOffset.left + realOffset, y: (dimensions.targetOffset.top + dimensions.targetHeight + this.arrowSize)} break; case 'right': var realOffset = this.options.offsetY === undefined ? this.options.offset : this.options.offsetY result = {x: (dimensions.targetOffset.left + dimensions.targetWidth + this.arrowSize), y: dimensions.targetOffset.top + realOffset} break; case 'center' : var windowHeight = $(window).height() result = {x: (dimensions.documentWidth/2 - dimensions.containerWidth/2), y: (windowHeight/2 - dimensions.containerHeight/2)} if (result.y < 40) result.y = 40 break; } if (!this.options.container) return result var $container = $(this.options.container), containerOffset = $container.offset() result.x -= containerOffset.left result.y -= containerOffset.top return result } Popover.prototype.onDocumentClick = function(e) { if (!this.options.closeOnPageClick) return if (this.options.onCheckDocumentClickTarget && this.options.onCheckDocumentClickTarget(e.target)) { return } if ($.contains(this.$container.get(0), e.target)) return this.hide(); } Popover.DEFAULTS = { placement: 'bottom', fallbackPlacement: 'bottom', content: '<p>Popover content<p>', width: false, modal: false, highlightModalTarget: false, closeOnPageClick: true, closeOnEsc: true, container: false, containerClass: null, offset: 15, useAnimation: false, onCheckDocumentClickTarget: null } // POPOVER PLUGIN DEFINITION // ============================ var old = $.fn.ocPopover $.fn.ocPopover = function (option) { var args = arguments; return this.each(function () { var $this = $(this) var data = $this.data('oc.popover') var options = $.extend({}, Popover.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) { if (typeof option == 'string') return; $this.data('oc.popover', (data = new Popover(this, options))) } else { if (typeof option != 'string') return; var methodArgs = []; for (var i=1; i<args.length; i++) methodArgs.push(args[i]) data[option].apply(data, methodArgs) } }) } $.fn.ocPopover.Constructor = Popover // POPOVER NO CONFLICT // ================= $.fn.ocPopover.noConflict = function () { $.fn.ocPopover = old return this } // POPOVER DATA-API // =============== $(document).on('click', '[data-control=popover]', function(e){ $(this).ocPopover() return false; }) }(window.jQuery);
// Pseudocode // input: an array of integers // output: three separate integer or string values: 1. the sum of the integers, 2. the mean of the integers, and 3. the median of the integers // steps: // create a function called sum that takes the array as an argument // add all of the integers together // save the total as a variable total // return the total // create a function called mean that takes the array as an argument // invoke the sum function // create a variable count that is equal to the length of the array // divide the total from the sum function by count // save the result as a variable result // return result // create a function called median that takes the array as an argument // iterate over the array // sort the integers from lowest to highest // save the new array in variable called sorted // create a variable count is equal to the length of the array // create a variable middle that is equal to sorted divided by 2 // return middle
var config = {}; config.address = "irc.chat.twitch.tv"; // Twitch's IRC address config.tmiPort = 6667; // Twitch's IRC port config.relayPort = 6667; // Port the relay listens to config.sendChannelModeNotices = true; // Send a human-readable notice with slow/sub-modes config.apiClientId = ""; // Because Twitch API likes Client-ID header to be included with API requests config.viewerListUpdateInterval = 60; // Update the viewer list every 30 seconds by default config.viwerListUpdateEnabled = true; // Might want to disable entirely in some cases config.stripTags = true; // Strip tags from the message sent to the client /** * +o is always set, do not include it below * Admins have a, subscribers h, turbo v */ config.staffMode = "q"; // Twitch staff's additional modes config.broadcasterMode = ""; // Broadcaster's additional modes module.exports = config;
var app = angular.module('callcenterApplication', ['ngMessages', 'glue.directives']); app.filter('time', function() { return function(value) { var minutes = Math.floor(value / 60); var seconds = value - (minutes * 60); if (minutes < 10){ minutes = '0' + minutes; } if (seconds < 10){ seconds = '0' + seconds; } return minutes + ':' + seconds; }; }); app.controller('WorkflowController', function ($scope, $rootScope, $http, $interval, $log) { /* misc configuration data, for instance callerId for outbound calls */ $scope.configuration; /* contains task data pushed by the TaskRouter JavaScript SDK */ $scope.reservation; $scope.tasks; /* contains worker record received by the Twilio API or the TaskRouter JavaScript SDK */ $scope.worker; /* TaskRouter Worker */ $scope.workerJS; /* request configuration data and tokens from the backend */ $scope.init = function () { $http.get('/api/agents/session') .then(function onSuccess(response) { /* keep a local copy of the configuration and the worker */ $scope.configuration = response.data.configuration; /* initialize Twilio worker js with token received from the backend */ $scope.initWorker(response.data.tokens.worker); /* initialize Twilio client with token received from the backend */ $scope.$broadcast('InitializePhone', { token: response.data.tokens.phone}); /* initialize Twilio IP Messaging client with token received from the backend */ $scope.$broadcast('InitializeChat', { token: response.data.tokens.chat, identity: response.data.worker.friendlyName}); }, function onError(response) { /* session is not valid anymore */ if(response.status == 403){ window.location.replace('/callcenter/'); } else { alert(JSON.stringify(response)); } }); }; $scope.initWorker = function(token) { /* create TaskRouter Worker */ $scope.workerJS = new Twilio.TaskRouter.Worker(token, true, $scope.configuration.twilio.workerIdleActivitySid, $scope.configuration.twilio.workerOfflineActivitySid); $scope.workerJS.on('ready', function(worker) { $log.log('TaskRouter Worker: ready'); $scope.worker = worker; }); $scope.workerJS.on('reservation.created', function(reservation) { $log.log('TaskRouter Worker: reservation.created'); $log.log(reservation); $scope.reservation = reservation; $scope.$apply(); $scope.startReservationCounter(); }); $scope.workerJS.on('reservation.accepted', function(reservation) { $log.log('TaskRouter Worker: reservation.accepted'); $log.log(reservation); $scope.task = reservation.task; $scope.task.completed = false; $scope.reservation = null; $scope.stopReservationCounter(); $scope.$apply(); }); $scope.workerJS.on('reservation.timeout', function(reservation) { $log.log('TaskRouter Worker: reservation.timeout'); $log.log(reservation); /* reset all data */ $scope.reservation = null; $scope.task = null; $scope.$apply(); }); $scope.workerJS.on('reservation.rescinded', function(reservation) { $log.log('TaskRouter Worker: reservation.rescinded'); $log.log(reservation); /* reset all data */ $scope.reservation = null; $scope.task = null; $scope.$apply(); }); $scope.workerJS.on('reservation.canceled', function(reservation) { $log.log('TaskRouter Worker: reservation.cancelled'); $log.log(reservation); $scope.reservation = null; $scope.task = null; $scope.$apply(); }); $scope.workerJS.on('activity.update', function(worker) { $log.log('TaskRouter Worker: activity.update'); $log.log(worker); $scope.worker = worker; $scope.$apply(); }); $scope.workerJS.on('token.expired', function() { $log.log('TaskRouter Worker: token.expired'); $scope.reservation = null; $scope.task = null; $scope.$apply(); /* the worker token expired, the agent shoud log in again, token is generated upon log in */ window.location.replace('/callcenter/'); }); }; $scope.acceptReservation = function (reservation) { $log.log('accept reservation with TaskRouter Worker JavaScript SDK'); /* depending on the typ of taks that was created we handle the reservation differently */ if(reservation.task.attributes.channel == 'chat'){ reservation.accept( function(err, reservation) { if(err) { $log.error(err); return; } $scope.$broadcast('ActivateChat', { channelSid: reservation.task.attributes.channelSid }); }); } if(reservation.task.attributes.channel == 'phone' && reservation.task.attributes.type == 'Inbound call'){ $log.log('dequeue reservation with callerId: ' + $scope.configuration.twilio.callerId); reservation.dequeue($scope.configuration.twilio.callerId); } /* we accept the reservation and initiate a call to the customer's phone number */ if(reservation.task.attributes.channel == 'phone' && reservation.task.attributes.type == 'Callback request'){ reservation.accept( function(err, reservation) { if(err) { $log.error(err); return; } $scope.$broadcast('CallPhoneNumber', { phoneNumber: reservation.task.attributes.phone }); }); } }; $scope.complete = function (reservation) { if($scope.task.attributes.channel == 'chat'){ $scope.$broadcast('DestroyChat'); } $scope.workerJS.update('ActivitySid', $scope.configuration.twilio.workerIdleActivitySid, function(err, worker) { if(err) { $log.error(err); return; } $scope.reservation = null; $scope.task = null; $scope.$apply(); }); }; $scope.logout = function () { $http.post('/api/agents/logout') .then(function onSuccess(response) { window.location.replace('/callcenter/index.html'); }, function onError(response) { $log.error(response); }); }; $scope.startReservationCounter = function() { $log.log('start reservation counter'); $scope.reservationCounter = $scope.reservation.task.age; $scope.reservationInterval = $interval(function() { $scope.reservationCounter++; }, 1000); }; $scope.stopReservationCounter = function() { if (angular.isDefined($scope.reservationInterval)) { $interval.cancel($scope.reservationInterval); $scope.reservationInterval = undefined; } }; });
import React from 'react'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; // Import Routes import routes from './routes'; // Base stylesheet require('./main.scss'); export default function App(props) { return ( <Provider store={props.store}> <Router history={browserHistory} onUpdate={() => window.scrollTo(0, 0)}> {routes} </Router> </Provider> ); } /* eslint react/forbid-prop-types: 0 */ App.propTypes = { store: React.PropTypes.object.isRequired, };
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*\n' + '<%= pkg.name %> | v<%= pkg.version %> | Build date: <%= grunt.template.today("yyyy-mm-dd") %>\n' + 'Copyright (C) 2013 - <%= grunt.template.today("yyyy") %> n-fuse GmbH - All Rights Reserved\n' + 'Licensed under the <%= pkg.licenses[0].type %> license\n' + '*/\n', sourceMap: 'dist/<%= pkg.name %>-source-map.js', sourceMapRoot: 'dist/' }, build: { src: 'src/<%= pkg.name %>.js', dest: 'dist/<%= pkg.name %>.min.js' } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('default', ['uglify']); };
var _ = require('lodash'); var when = require('when'); var validator = require('./validator'); var schema = require('../schema').tables; var errors = require('../../errors'); var validateSchema = null; var validate = null; /** * 模型属性值验证 * @param {String} tableName 数据表名称 * @param {String} model 模型JSON数据 * @return {Promise} */ validateSchema = function(tableName, model) { var columns = _.keys(schema[tableName]); var validationErrors = []; var on = model.hasOwnProperty('id') ? 'update' : 'add'; // 数据表字段名 _.each(columns, function (columnKey) { var field = schema[tableName][columnKey]; var message = ''; // 检查字段是否可以为空 if (model.hasOwnProperty(columnKey) && field.hasOwnProperty('nullable') && field.nullable !== true) { if (validator.isNull(model[columnKey]) || validator.isEmpty(model[columnKey])) { message = 'Value in [' + tableName + '.' + columnKey + '] cannot be blank.'; validationErrors.push(new errors.ValidationError(message, tableName + '.' + columnKey)); } } // 对非空属性值的检验 if (model[columnKey] !== null && model[columnKey] !== undefined) { // 检查长度是否合法 if (field.hasOwnProperty('maxlength')) { if (!validator.isLength(model[columnKey], 0, field.maxlength)) { message = 'Value in [' + tableName + '.' + columnKey + '] exceeds maximum length of ' + field.maxlength + ' characters.'; validationErrors.push(new errors.ValidationError(message, tableName + '.' + columnKey)); } } // 检查validatations对象 if (field.hasOwnProperty('validations')) { validationErrors = validationErrors.concat(validate(model[columnKey], columnKey, field.validations, on)); } // 检查是否为整数 if (field.hasOwnProperty('type')) { if (field.type === 'integer' && !validator.isInt(model[columnKey])) { message = 'Value in [' + tableName + '.' + columnKey + '] is not an integer.'; validationErrors.push(new errors.ValidationError(message, tableName + '.' + columnKey)); } } } }); if (validationErrors.length !== 0) { return when.reject(validationErrors); } return when.resolve(); }; /** * 字段验证器 * @param {String} value 需要被验证属性的value * @param {String} key 需要被验证属性的key * @param {String} on 属性被验证的时机 * @param {String} validations 验证器名称 * @return {Array} ValidationError的数组 */ validate = function (value, key, validations, on) { var validationErrors = []; _.each(validations, function (opts, validationName) { // 是否在合适的验证时机 if (!opts.hasOwnProperty('validateOn') || (opts.hasOwnProperty('validateOn') && opts.validateOn.toLowerCase() === on)) { var args = []; var expect = true; var errorInfo = opts.errorInfo || 'Validation (' + validationName + ') failed for ' + key; if (_.isBoolean(opts.condition)) { expect = opts.condition; } else { args.push(opts.condition); } args.unshift(value); // 调用validator.xxxx进行验证 if (validator[validationName].apply(validator, args) !== expect) { validationErrors.push(new errors.ValidationError(errorInfo, key)); } } }, this); return validationErrors; }; module.exports = { validateSchema: validateSchema };
module.exports = { components : { overshadow : { function : require('../components/camera'), properties : { z: -10 } }, mouse : { construct : require('../components/mouse'), properties : { speed: 5 } }, winMessage : "You've won." } }
var PubNub = require('pubnub') // Configure Twitter subscribe key var pubnubTwitter = new PubNub({ subscribeKey: "sub-c-78806dd4-42a6-11e4-aed8-02ee2ddab7fe", }) // Listener on the Twitter channel pubnubTwitter.addListener({ message: function(m) { var msg = m.message; // We are filtering tweets based on Trump, trump, or any capitilization of POTUS if (msg.text.match(/([T|t]rump|[P|p][O|o][T|t][U|u][S|s])/g)) { console.log(msg.text); } } }) // Configure PubNub subscriptions pubnubTwitter.subscribe({ channels: ['pubnub-twitter'], })
const passport = require('passport') module.exports = function (req, res, next) { passport.authenticate('jwt', function (err, user) { if (err || !user) { res.status(403).send({ error: 'Invalid Authorisation' }) } else { req.user = user next() } })(req, res, next) }
/* jQuery Content Panel Switcher JS */ var jcps = {}; jcps.fader = function(speed, target, panel) { jcps.show(target, panel); if (panel == null) {panel = ''}; $('.switcher' + panel).click(function() { var _contentId = '#' + $(this).attr('id') + '-content'; var _content = $(_contentId).html(); if (speed == 0) { $(target).html(_content); } else { $(target).fadeToggle(speed, function(){$(this).html(_content);}).fadeToggle(speed); } }); }; jcps.slider = function(speed, target, panel) { jcps.show(target, panel); if (panel == null) {panel = ''}; $('.switcher' + panel).click(function() { var _contentId = '#' + $(this).attr('id') + '-content'; var _content = $(_contentId).html(); if (speed == 0) { $(target).html(_content); } else { $(target).slideToggle(speed, function(){$(this).html(_content);}).slideToggle(speed); } }); }; jcps.show = function (target, panel) { $('.show').each(function() { if (panel == null) { $(target).append($(this).html() + '<br/>'); } else { var trimPanel = panel.replace('.', ''); if ($(this).hasClass(trimPanel) == true){$(target).append($(this).html() + '<br/>');} } }); }
/* global describe, it */ import {assert} from 'chai' import {Meteor} from 'meteor/meteor' import { createTestDID, createTestHDWallet, testRecoveryAddress } from 'bitcoin/testUtils' import {sendRawTransaction} from 'bitcoin/bitcoinRpc' import signWithOwnerKey256 from 'bitcoin/sign' import verifyWithOwnerKey256 from 'bitcoin/verify' global.Buffer = global.Buffer || require('buffer').Buffer if (Meteor.isClient) { describe('verify', function () { it('it verifies a message signature', async function () { this.timeout(150000) const walletRoot = createTestHDWallet() const recoveryAddress = testRecoveryAddress const {tx1, tx2} = await createTestDID({walletRoot, recoveryAddress}) await sendRawTransaction(tx1.toHex()) await sendRawTransaction(tx2.toHex()) const msg = 'Hello World!' const sig = signWithOwnerKey256({walletRoot, msg, rotationIx: 0}) const res = await verifyWithOwnerKey256({msg, DID: tx1.getId(), sig}) assert.isTrue(res) }) }) }
import React from "react" import { shallow } from "enzyme" import { Idea } from "../../web/static/js/components/idea" import IdeaEditForm from "../../web/static/js/components/idea_edit_form" import IdeaLiveEditContent from "../../web/static/js/components/idea_live_edit_content" import IdeaReadOnlyContent from "../../web/static/js/components/idea_read_only_content" import STAGES from "../../web/static/js/configs/stages" const { IDEA_GENERATION } = STAGES describe("Idea component", () => { const idea = { category: "sad", body: "redundant tests", user_id: 1, } const mockRetroChannel = { on: () => {}, push: () => {} } const mockUser = {} const mockUsers = [{}] context("when the idea is being edited", () => { const ideaInEditState = { ...idea, editing: true, editorToken: "aljk" } context("and the idea's `editorToken` matches the current user's token", () => { const currentUser = { token: "aljk" } const wrapper = shallow( <Idea idea={ideaInEditState} currentUser={currentUser} retroChannel={mockRetroChannel} stage={IDEA_GENERATION} users={mockUsers} /> ) it("renders an <IdeaEditForm/> as a child", () => { expect(wrapper.find(IdeaEditForm).length).to.equal(1) }) }) context("and the idea's `editorToken` does *not* match the current user's token", () => { const currentUser = { token: "merp" } const wrapper = shallow( <Idea idea={ideaInEditState} currentUser={currentUser} retroChannel={mockRetroChannel} stage={IDEA_GENERATION} users={mockUsers} /> ) it("does not render an <IdeaEditForm/> as a child", () => { expect(wrapper.find(IdeaEditForm).length).to.equal(0) }) context("when the idea has a `liveEditText` value", () => { const wrapper = shallow( <Idea idea={{ ...ideaInEditState, liveEditText: "editing bigtime" }} currentUser={currentUser} retroChannel={mockRetroChannel} stage={IDEA_GENERATION} users={mockUsers} /> ) it("renders the <IdeaLiveEditContent /> as a child", () => { expect(wrapper.find(IdeaLiveEditContent).length).to.equal(1) }) }) }) }) context("when the idea is not in an edit state", () => { const ideaInDefaultState = { ...idea, editing: false } const wrapper = shallow( <Idea idea={ideaInDefaultState} currentUser={mockUser} retroChannel={mockRetroChannel} stage={IDEA_GENERATION} users={mockUsers} /> ) it("renders <IdeaReadOnlyContent /> as a child", () => { expect(wrapper.find(IdeaReadOnlyContent).length).to.equal(1) }) it("does not render <IdeaEditForm/> as a child", () => { expect(wrapper.find(IdeaEditForm).length).to.equal(0) }) it("does not render <IdeaLiveEditContent/> as a child", () => { expect(wrapper.find(IdeaLiveEditContent).length).to.equal(0) }) }) })
/* eslint-disable react/prop-types */ import { connect } from 'react-redux' import { injectIntl } from 'react-intl' import React from 'react' import * as apiActions from '../../actions/api' import * as locationActions from '../../actions/location' import { getActiveSearch, getShowUserSettings } from '../../util/state' import { getUserLocations } from '../../util/user' import Icon from '../util/icon' /** * Custom icon component that renders based on the user location icon prop. */ const UserLocationIcon = ({ userLocation }) => { const { icon = 'marker' } = userLocation // Places from localStorage that are assigned the 'work' icon // should be rendered as 'briefcase'. const finalIcon = icon === 'work' ? 'briefcase' : icon return <Icon name={finalIcon} /> } /** * This higher-order component connects the target (styled) LocationField to the * redux store. * @param StyledLocationField The input LocationField component to connect. * @param options Optional object with the following optional props (see defaults in code): * - actions: a list of actions to include in mapDispatchToProps * - excludeSavedLocations: whether to not render user-saved locations * - includeLocation: whether to derive the location prop from * the active query * @returns The connected component. */ export default function connectLocationField( StyledLocationField, options = {} ) { // By default, set actions to empty list and do not include location. const { actions = {}, excludeSavedLocations = false, includeLocation = false } = options const mapStateToProps = (state, ownProps) => { const { config, currentQuery, location, transitIndex } = state.otp const { currentPosition, nearbyStops, sessionSearches } = location const activeSearch = getActiveSearch(state) const query = activeSearch ? activeSearch.query : currentQuery // Display saved locations and recent places according to the configured persistence strategy, // unless displaying user locations is disabled via prop (e.g. in the saved-place editor // when the loggedInUser defines their saved locations). let userSavedLocations = [] let recentPlaces = [] if (!excludeSavedLocations) { const userLocations = getUserLocations(state) userSavedLocations = userLocations.saved recentPlaces = userLocations.recent } const geocoderConfig = config.geocoder if (currentPosition?.coords) { const { latitude: lat, longitude: lon } = currentPosition.coords geocoderConfig.focusPoint = { lat, lon } } const stateToProps = { currentPosition, geocoderConfig, layerColorMap: config.geocoder?.resultsColors || {}, nearbyStops, sessionSearches, showUserSettings: getShowUserSettings(state), stopsIndex: transitIndex.stops, UserLocationIconComponent: UserLocationIcon, userLocationsAndRecentPlaces: [...userSavedLocations, ...recentPlaces] } // Set the location prop only if includeLocation is specified, else leave unset. // Otherwise, the StyledLocationField component will use the fixed undefined/null value as location // and will not respond to user input. if (includeLocation) { stateToProps.location = query[ownProps.locationType] } return stateToProps } const mapDispatchToProps = { addLocationSearch: locationActions.addLocationSearch, findNearbyStops: apiActions.findNearbyStops, getCurrentPosition: locationActions.getCurrentPosition, ...actions } return connect( mapStateToProps, mapDispatchToProps )(injectIntl(StyledLocationField)) }
var testModule = require('./testfile');
angular.module('game') .factory('Particles', ['Calc', function (Calc) { var nextName = 1; function create(image, center, particles) { var p = { image: image, size: Calc.nextGaussian(20, 4), center: {x: center.x, y: center.y}, direction: Calc.nextCircleVector(), speed: Calc.nextGaussian(50, 25), // pixels per second rotation: 0, lifetime: Calc.nextGaussian(2.5, 1), // How long the particle should live, in seconds alive: 0 // How long the particle has been alive, in seconds }; // // Ensure we have a valid size - gaussian numbers can be negative p.size = Math.max(1, p.size); // // Same thing with lifetime p.lifetime = Math.max(0.01, p.lifetime); // // Assign a unique name to each particle particles[nextName++] = p; } function update(particles, elapsedTime) { var removeMe = [], value, particle; for (value in particles) { if (particles.hasOwnProperty(value)) { particle = particles[value]; // // Update how long it has been alive particle.alive += elapsedTime; // // Update its position particle.center.x += (elapsedTime * particle.speed * particle.direction.x); particle.center.y += (elapsedTime * particle.speed * particle.direction.y); // // Rotate proportional to its speed particle.rotation += particle.speed / 500; // // If the lifetime has expired, identify it for removal if (particle.alive > particle.lifetime) { removeMe.push(value); } } } // // Remove all of the expired particles for (particle = 0; particle < removeMe.length; particle++) { delete particles[removeMe[particle]]; } removeMe.length = 0; } function render(particles, context, draw) { var value, particle; for (value in particles) { if (particles.hasOwnProperty(value)) { particle = particles[value]; draw(context, particle); } } } return { create : create, update : update, render : render } }]);
'use strict'; const proxyquire = require('proxyquire'); const chai = require('chai'); const sinon = require('sinon'); const assert = chai.assert; const expect = chai.expect; const testHelper = require('../../util/testHelper'); const secrets = require('../../lib/secrets'); const constants = require('../../lib/constants'); describe('clientIdAuthorizer', function() { beforeEach(function() { this.clientIdAuthorizer = proxyquire('./clientIdAuthorizer', { '../../lib/log': testHelper.mockLog }); }); it(`should fail when authorizationToken is not defined`, function(done) { let event = testHelper.lambdaEvent(); this.clientIdAuthorizer(event, {}, (err, data) => { testHelper.check(done, () => { expect(err).to.equal('Fail'); expect(data.name).to.equal('client_id_error'); expect(data.message).to.equal(`${constants.CLIENT_ID_HEADER} key missing in request header`); }); }); }); });
exports.names = ['songinfo']; exports.hidden = false; exports.enabled = true; exports.matchStart = true; exports.cd_all = 30; exports.cd_user = 30; exports.cd_manager = 5; exports.min_role = PERMISSIONS.NONE; function do_history(data, format, cid, songs_ago) { if (!cid || !format) { sendMessage('/me :tfw: MFW no song'); return; } Song.findAll({ where: { format: format, cid: cid, }, order: 'updated_at DESC' }).on('success', function (rows) { console.info(rows); if (rows && rows.length > 0) { var song_ids = []; _.each(rows, function (row) { song_ids.push(row.id); }); console.info(song_ids); Play.findAll({ where: { song_id: song_ids }, order: 'updated_at DESC' }).on('success', function (rows) { console.info(rows); if (format == 1) { var prefix = 'This song'; if (songs_ago >= 0) { prefix = 'The song that played ' + (songs_ago+1) + ' songs ago (https://youtu.be/' + cid + ')'; } if (rows && rows.length > 0) { modMessage(data, prefix + ' has been played '+(rows.length)+' times in my lifetime, last time being ' + moment.utc(rows[0]['updated_at']).calendar() + ' (' + moment.utc(rows[0]['updated_at']).fromNow() + ')'); } else { modMessage(data, prefix + ' has not been played here in my lifetime.'); } } else { soundcloud_get_track(cid, function (json_data) { var song_url = json_data.permalink_url; var prefix = 'This song'; if (songs_ago >= 0) { prefix = 'The song that played ' + (songs_ago+1) + ' songs ago (' + song_url + ')'; } if (rows && rows.length > 0) { modMessage(data, prefix + ' has been played '+(rows.length)+' times in my lifetime, last time being ' + moment.utc(rows[0]['updated_at']).calendar() + ' (' + moment.utc(rows[0]['updated_at']).fromNow() + ')'); } else { modMessage(data, prefix + ' has not been played here in my lifetime.'); } }); } }); } else { modMessage(data, 'This song has not been played here in my lifetime.'); } }); } exports.handler = function (data) { var input = data.message.split(' '); var command = _.first(input); var params = _.rest(input); var offset = false; var cid = false; var format = false; if (params.length >= 1) { var tmp_offset = parseInt(params); if (!isNaN(tmp_offset) && tmp_offset >= 1) { offset = tmp_offset-1; } } var media = bot.getMedia(); if (media == null) { offset = 0; } else { cid = media.cid; format = media.format; } if (offset !== false) { console.info('offset: ' + offset); sequelize.query('SELECT `plays`.`id`, `songs`.`format`, `songs`.`cid`, `songs`.`author`, `songs`.`title` FROM `plays` INNER JOIN `songs` ON `songs`.`id`=`plays`.`song_id` ORDER BY `plays`.`id` DESC LIMIT '+offset+',1', { type: Sequelize.QueryTypes.SELECT }) .then(function(rows) { console.info(rows); if (rows != null && rows.length == 1) { var row = rows[0]; console.info(row); cid = row['cid']; format = row['format']; } }).then(function() { do_history(data, format, cid, offset); }); } else { do_history(data, format, cid, -1); } };
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format */ // flowlint ambiguous-object-type:error 'use strict'; const RelayConcreteNode = require('../util/RelayConcreteNode'); const RelayModernRecord = require('./RelayModernRecord'); const RelayStoreUtils = require('./RelayStoreUtils'); const cloneRelayHandleSourceField = require('./cloneRelayHandleSourceField'); const invariant = require('invariant'); import type { NormalizationLinkedField, NormalizationModuleImport, NormalizationNode, NormalizationSelection, } from '../util/NormalizationNode'; import type {DataID, Variables} from '../util/RelayRuntimeTypes'; import type { NormalizationSelector, OperationLoader, Record, RecordSource, } from './RelayStoreTypes'; const { CONDITION, CLIENT_EXTENSION, DEFER, FRAGMENT_SPREAD, INLINE_FRAGMENT, LINKED_FIELD, MODULE_IMPORT, LINKED_HANDLE, SCALAR_FIELD, SCALAR_HANDLE, STREAM, } = RelayConcreteNode; const {getStorageKey, getModuleOperationKey} = RelayStoreUtils; function mark( recordSource: RecordSource, selector: NormalizationSelector, references: Set<DataID>, operationLoader: ?OperationLoader, ): void { const {dataID, node, variables} = selector; const marker = new RelayReferenceMarker( recordSource, variables, references, operationLoader, ); marker.mark(node, dataID); } /** * @private */ class RelayReferenceMarker { _operationLoader: OperationLoader | null; _recordSource: RecordSource; _references: Set<DataID>; _variables: Variables; constructor( recordSource: RecordSource, variables: Variables, references: Set<DataID>, operationLoader: ?OperationLoader, ) { this._operationLoader = operationLoader ?? null; this._recordSource = recordSource; this._references = references; this._variables = variables; } mark(node: NormalizationNode, dataID: DataID): void { this._traverse(node, dataID); } _traverse(node: NormalizationNode, dataID: DataID): void { this._references.add(dataID); const record = this._recordSource.get(dataID); if (record == null) { return; } this._traverseSelections(node.selections, record); } _getVariableValue(name: string): mixed { invariant( this._variables.hasOwnProperty(name), 'RelayReferenceMarker(): Undefined variable `%s`.', name, ); return this._variables[name]; } _traverseSelections( selections: $ReadOnlyArray<NormalizationSelection>, record: Record, ): void { selections.forEach(selection => { /* eslint-disable no-fallthrough */ switch (selection.kind) { case LINKED_FIELD: if (selection.plural) { this._traversePluralLink(selection, record); } else { this._traverseLink(selection, record); } break; case CONDITION: const conditionValue = this._getVariableValue(selection.condition); if (conditionValue === selection.passingValue) { this._traverseSelections(selection.selections, record); } break; case INLINE_FRAGMENT: if (selection.abstractKey == null) { const typeName = RelayModernRecord.getType(record); if (typeName != null && typeName === selection.type) { this._traverseSelections(selection.selections, record); } } else { this._traverseSelections(selection.selections, record); } break; case FRAGMENT_SPREAD: invariant( false, 'RelayReferenceMarker(): Unexpected fragment spread `...%s`, ' + 'expected all fragments to be inlined.', selection.name, ); case LINKED_HANDLE: // The selections for a "handle" field are the same as those of the // original linked field where the handle was applied. Reference marking // therefore requires traversing the original field selections against // the synthesized client field. // // TODO: Instead of finding the source field in `selections`, change // the concrete structure to allow shared subtrees, and have the linked // handle directly refer to the same selections as the LinkedField that // it was split from. const handleField = cloneRelayHandleSourceField( selection, selections, this._variables, ); if (handleField.plural) { this._traversePluralLink(handleField, record); } else { this._traverseLink(handleField, record); } break; case DEFER: case STREAM: this._traverseSelections(selection.selections, record); break; case SCALAR_FIELD: case SCALAR_HANDLE: break; case MODULE_IMPORT: this._traverseModuleImport(selection, record); break; case CLIENT_EXTENSION: this._traverseSelections(selection.selections, record); break; default: (selection: empty); invariant( false, 'RelayReferenceMarker: Unknown AST node `%s`.', selection, ); } }); } _traverseModuleImport( moduleImport: NormalizationModuleImport, record: Record, ): void { const operationLoader = this._operationLoader; invariant( operationLoader !== null, 'RelayReferenceMarker: Expected an operationLoader to be configured when using `@module`.', ); const operationKey = getModuleOperationKey(moduleImport.documentName); const operationReference = RelayModernRecord.getValue(record, operationKey); if (operationReference == null) { return; } const operation = operationLoader.get(operationReference); if (operation != null) { this._traverseSelections(operation.selections, record); } // Otherwise, if the operation is not available, we assume that the data // cannot have been processed yet and therefore isn't in the store to // begin with. } _traverseLink(field: NormalizationLinkedField, record: Record): void { const storageKey = getStorageKey(field, this._variables); const linkedID = RelayModernRecord.getLinkedRecordID(record, storageKey); if (linkedID == null) { return; } this._traverse(field, linkedID); } _traversePluralLink(field: NormalizationLinkedField, record: Record): void { const storageKey = getStorageKey(field, this._variables); const linkedIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey); if (linkedIDs == null) { return; } linkedIDs.forEach(linkedID => { if (linkedID != null) { this._traverse(field, linkedID); } }); } } module.exports = {mark};
'use strict'; import React from 'react'; require('styles/hadrien/Demo.styl'); let DemoComponent = (props) => ( <div className="demo-component"> { props.children } </div> ); DemoComponent.displayName = 'HadrienDemoComponent'; // Uncomment properties you need // EditorComponent.propTypes = {}; // EditorComponent.defaultProps = {}; export default DemoComponent;
/* global test expect */ const add = require('./.'); test('should add a string to a list only once', () => { const arr = ['test']; const newArr = add('test', arr); expect(newArr[0]).toBe('test'); expect(newArr[1]).toBeFalsy(); }); test('should add a string to an empty list', () => { const arr = []; const newArr = add('test', arr); expect(newArr[0]).toBe('test'); }); test('should add a string to a non empty list', () => { const arr = ['test 1']; const newArr = add('test 2', arr); expect(newArr[0]).toBe('test 1'); expect(newArr[1]).toBe('test 2'); });
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var createClass = require('create-react-class'); var DeviceBattery90 = createClass({ displayName: 'DeviceBattery90', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { 'fillOpacity': '.3', d: 'M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z' }), React.createElement('path', { d: 'M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z' }) ); } }); module.exports = DeviceBattery90;
/** * GearBonus.js * KC3改 The definitions of Ship's stats visible bonuses from equipment (Gears). * Visible bonus only, hidden bonuses, improvement bonuses, anti-specified-target bonuses are excluded for now. */ (function(){ "use strict"; // All methods are static, do not instantiate this. window.KC3GearBonus = function() { }; /** * Explicit stats visible bonuses from equipment on specific ship are added to API result by server-side, * to correct the 'naked stats' for these cases, have to simulate them all. * These definitions might be moved to an independent JSON, but kept to be a module so that we can add comments. * @return a bonus definition table with new counters bound to relevant equipment IDs. * @see https://wikiwiki.jp/kancolle/%E8%A3%85%E5%82%99#bonus - about naming of this bonus type * @see https://kancolle.fandom.com/wiki/Equipment_Bonuses - summary tables and named: visible bonuses * @see `main.js#SlotItemEffectUtil` - since 2020-03-03, devs implemented client-side bonuses display, which hard-coded these logics and wrapped results with `SlotItemEffectModel` * @see URLs some other summary tables: * * [20210916 ALL] https://docs.google.com/spreadsheets/d/1bInH11S_xKdaKP754bB7SYh-di9gGzcXkiQPvGuzCpg/htmlview * * [20210301 ALL] https://www.npmjs.com/package/equipment-bonus * * [20190208 ALL] https://docs.google.com/spreadsheets/d/1_peG-B4ijt7HOvDtkd8dPZ8vA7ZMLx-YuwsuGoEm6wY/htmlview * * [20180904 ALL] https://github.com/andanteyk/ElectronicObserver/blob/develop/ElectronicObserver/Other/Information/kcmemo.md#%E7%89%B9%E6%AE%8A%E8%A3%85%E5%82%99%E3%81%AB%E3%82%88%E3%82%8B%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E8%A3%9C%E6%AD%A3 * * [20180816 ALL] http://furukore.com/archives/13793 * * [20180726 DD] https://zekamashi.net/kancolle-kouryaku/kutiku-fit/ * * [20180808 DD] https://kitongame.com/%E3%80%90%E8%89%A6%E3%81%93%E3%82%8C%E3%80%91%E9%A7%86%E9%80%90%E8%89%A6%E3%81%AE%E4%B8%BB%E7%A0%B2%E3%83%95%E3%82%A3%E3%83%83%E3%83%88%E8%A3%9C%E6%AD%A3%E3%81%A8%E8%89%A6%E7%A8%AE%E5%88%A5%E3%81%8A/#i * * [20180429 DD] https://twitter.com/Lambda39/status/990268289866579968 */ KC3GearBonus.explicitStatsBonusGears = function(){ return { "synergyGears": { surfaceRadar: 0, surfaceRadarIds: [28, 29, 31, 32, 88, 89, 124, 141, 142, 240, 278, 279, 307, 315, 410, 411], airRadar: 0, airRadarIds: [27, 30, 32, 89, 106, 124, 142, 278, 279, 307, 315, 410, 411], aaMachineGun: 0, aaMachineGunIds: [37, 38, 39, 40, 49, 51, 84, 85, 92, 131, 173, 191, 274, 301], domesticSonar: 0, domesticSonarIds: [46, 47, 132, 149, 438], enhancedBoiler: 0, enhancedBoilerIds: [34], newModelBoiler: 0, newModelBoilerIds: [87], tripleTorpedo: 0, tripleTorpedoIds: [13, 125, 285], tripleTorpedoLateModel: 0, tripleTorpedoLateModelIds: [285], tripleTorpedoOxygenLateModel: 0, tripleTorpedoOxygenLateModelIds: [125, 285], quadrupleTorpedoOxygenLateModel: 0, quadrupleTorpedoOxygenLateModelIds: [15, 286], submarineTorpedoLateModel: 0, submarineTorpedoLateModelIds: [213, 214, 383], kamikazeTwinTorpedo: 0, kamikazeTwinTorpedoIds: [174], tripleLargeGunMountK2: 0, tripleLargeGunMountK2Nonexist: 1, tripleLargeGunMountK2Ids: [290], triple305mm46LargeGunMount: 0, triple305mm46LargeGunMountIds: [427], triple320mm44LargeGunMount: 0, triple320mm44LargeGunMountIds: [429], twin203MediumGunMountNo2: 0, twin203MediumGunMountNo2Nonexist: 1, twin203MediumGunMountNo2Ids: [90], rotorcraft: 0, rotorcraftIds: [69, 324, 325, 326, 327], helicopter: 0, helicopterIds: [326, 327], twin127SmallGunMountModelDK2: 0, twin127SmallGunMountModelDK2Nonexist: 1, twin127SmallGunMountModelDK2Ids: [267], ru130mmB13SmallGunMount: 0, ru130mmB13SmallGunMountIds: [282], skilledLookouts: 0, skilledLookoutsIds: [129, 412], searchlightSmall: 0, searchlightSmallIds: [74], type21AirRadar: 0, type21AirRadarIds: [30, 410], type21AirRadarK2: 0, type21AirRadarK2Ids: [410], }, // Ryuusei "18": { count: 0, byClass: { // Kaga Class Kai+ "3": { remodel: 1, multiple: { "houg": 1 }, }, // Akagi Class Kai+ "14": "3", // Taihou Class Kai "43": "3", }, byShip: [ { // extra +1 ev for Akagi Kai Ni, Kaga K2, K2Go ids: [594, 646, 698], multiple: { "houk": 1 }, }, { // extra +1 fp, +1 ev for Akagi Kai Ni E, Kaga K2E ids: [599, 610], multiple: { "houg": 1, "houk": 1 }, }, ], }, // Ryuusei Kai "52": { count: 0, byClass: { // Kaga Class Kai+ "3": { remodel: 1, multiple: { "houg": 1 }, }, // Akagi Class Kai+ "14": "3", // Taihou Class Kai "43": "3", }, byShip: [ { // extra +1 ev for Akagi Kai Ni, Kaga K2, K2Go ids: [594, 646, 698], multiple: { "houk": 1 }, }, { // extra +1 fp, +1 ev for Akagi Kai Ni E, Kaga K2E ids: [599, 610], multiple: { "houg": 1, "houk": 1 }, }, ], }, // Ryuusei Kai (CarDiv 1) "342": { count: 0, byClass: { // Kaga Class Kai+ "3": { remodel: 1, multiple: { "houg": 1 }, }, // Akagi Class Kai+ "14": "3", // Shoukaku Class Kai Ni+ "33": { remodel: 2, multiple: { "houg": 1 }, }, }, byShip: [ { // extra +1 fp, +1 aa, +1 ev for Akagi Kai Ni, Kaga K2, K2Go ids: [594, 646, 698], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // extra +2 fp, +2 aa, +2 ev for Akagi Kai Ni E, Kaga K2E ids: [599, 610], multiple: { "houg": 2, "tyku": 2, "houk": 2 }, }, ], }, // Ryuusei Kai (CarDiv 1 / Skilled) "343": { count: 0, byClass: { // Kaga Class Kai+ "3": { remodel: 1, multiple: { "houg": 2 }, }, // Akagi Class Kai+ "14": "3", // Shoukaku Class Kai Ni+ "33": { remodel: 2, multiple: { "houg": 1 }, }, }, byShip: [ { // extra +1 fp, +2 aa, +1 ev for Akagi Kai Ni, Kaga K2, K2Go ids: [594, 646, 698], multiple: { "houg": 1, "tyku": 2, "houk": 1 }, }, { // extra +3 fp, +3 aa, +3 ev for Akagi Kai Ni E, Kaga K2E ids: [599, 610], multiple: { "houg": 3, "tyku": 3, "houk": 3 }, }, ], }, // Type 97 Torpedo Bomber (931 Air Group) "82": { count: 0, byClass: { // Taiyou Class // Kasugamaru ctype is 75, but she is Taiyou remodel group 0 "76": { multiple: { "tais": 1, "houk": 1 }, }, }, }, // Type 97 Torpedo Bomber (931 Air Group / Skilled) "302": { count: 0, byClass: { // Taiyou Class "76": { multiple: { "tais": 1, "houk": 1 }, }, }, }, // Type 97 Torpedo Bomber (Tomonaga Squadron) "93": { count: 0, byClass: { // Souryuu "17": { single: { "houg": 1 }, }, // Hiryuu "25": { single: { "houg": 3 }, }, }, }, // Tenzan Model 12 (Tomonaga Squadron) "94": { count: 0, byClass: { // Souryuu Kai Ni "17": { remodel: 2, single: { "houg": 3 }, }, // Hiryuu Kai Ni "25": { remodel: 2, single: { "houg": 7 }, }, }, }, // Type 97 Torpedo Bomber (Murata Squadron) "143": { count: 0, byClass: { // Kaga Class "3": { single: { "houg": 2 }, }, // Akagi Class "14": { single: { "houg": 3 }, }, // Ryuujou Class "32": { single: { "houg": 1 }, }, // Shoukaku Class "33": { single: { "houg": 1 }, }, }, byShip: [ // extra +1 fp for Shoukaku all remodels { origins: [110], single: { "houg": 1 }, }, ], }, // Tenzan Model 12 (Murata Squadron) "144": { count: 0, byClass: { // Kaga Class "3": { single: { "houg": 2 }, }, // Akagi Class "14": { single: { "houg": 3 }, }, // Ryuujou Class "32": { single: { "houg": 1 }, }, // Shoukaku Class "33": [ // Base and Kai { single: { "houg": 1 }, }, // Kai Ni+ { remodel: 2, single: { "houg": 1 }, }, ], }, byShip: [ // extra +1 fp for Shoukaku base and Kai { ids: [110, 288], single: { "houg": 1 }, }, // extra +2 fp for Shoukaku K2 and K2A { ids: [461, 466], single: { "houg": 2 }, }, ], }, // Prototype Type 97 Torpedo Bomber Kai Type 3 Model E (w/ Type 6 Airborne Radar Kai) "344": { count: 0, byShip: [ { // Ryuuhou Kai ids: [318], multiple: { "houg": 4, "tais": 1 }, }, { // Ryuuhou K2 ids: [888], multiple: { "houg": 4, "tais": 2 }, }, { // Ryuuhou K2E ids: [883], multiple: { "houg": 5, "tais": 2 }, }, { // Zuihou Kai Ni+ ids: [555, 560], multiple: { "houg": 2, "tais": 2 }, }, { // Shouhou Kai ids: [282], multiple: { "houg": 2, "tais": 1 }, }, { // Akagi Kai Ni E, Kaga Kai Ni E ids: [599, 610], multiple: { "houg": 3 }, }, ], }, // Prototype Type 97 Torpedo Bomber Kai (Skilled) Type 3 Model E (w/ Type 6 Airborne Radar Kai) "345": { count: 0, byShip: [ { // Ryuuhou Kai ids: [318], multiple: { "houg": 5, "tais": 1, "houk": 2 }, }, { // Ryuuhou K2 ids: [888], multiple: { "houg": 4, "tais": 2, "houk": 2 }, }, { // Ryuuhou K2E ids: [883], multiple: { "houg": 5, "tais": 2, "houk": 3 }, }, { // Zuihou Kai Ni+ ids: [555, 560], multiple: { "houg": 3, "tais": 2, "houk": 2 }, }, { // Shouhou Kai ids: [282], multiple: { "houg": 3, "tais": 1, "houk": 1 }, }, { // Akagi Kai Ni E, Kaga Kai Ni E ids: [599, 610], multiple: { "houg": 3, "houk": 1 }, }, ], }, // TBM-3W+3S "389": { count: 0, byClass: { // Lexington Class "69": { multiple: { "houg": 2, "tais": 3, "houk": 1 }, }, // Casablanca Class "83": "69", // Essex Class "84": "69", // Yorktown Class "105": "69", }, byShip: [ { // Akagi Kai Ni, K2E ids: [594, 599], multiple: { "houg": 2, "houk": 2 }, }, { // Kaga Kai Ni, K2E ids: [698, 610], multiple: { "houg": 3, "houk": 2 }, }, { // Kaga Kai Ni Go ids: [646], multiple: { "houg": 4, "tais": 4, "houk": 3 }, synergy: [ { flags: [ "rotorcraft" ], single: { "houg": 3, "tais": 6 }, }, { flags: [ "helicopter" ], single: { "houg": 5, "tais": 4 }, }, ], }, ], }, // Tenzan Model 12A Kai (with Type 6 Airborne Radar) "373": { count: 0, byClass: { // Shouhou Class "11": [ // Base { multiple: { "tais": 1 }, }, // Kai { remodel: 1, multiple: { "houg": 1 }, }, { remodel: 1, single: { "raig": 1 }, }, // Kai Ni { remodel: 2, multiple: { "tais": 1 }, }, { remodel: 2, single: { "houk": 1 }, }, ], // Ryuuhou Class "51": [ // Ryuuhou Base (Taigei ctype 50, remodel index 0) { remodel: 1, multiple: { "houg": 1, "tais": 1 }, }, { remodel: 1, single: { "raig": 1 }, }, // Ryuuhou Kai { remodel: 2, multiple: { "tais": 1 }, }, { remodel: 2, single: { "houk": 1 }, }, ], // Chitose Class "15": [ // CVL base { remodel: 3, multiple: { "houg": 1 }, }, // CVL Kai { remodel: 4, single: { "raig": 1 }, }, // CVL Kai Ni { remodel: 5, single: { "houk": 1 }, }, ], // Hiyou Class "24": [ { multiple: { "houg": 1 }, }, { single: { "raig": 1, "houk": 1 }, }, ], // Shoukaku Class "33": [ { multiple: { "houg": 1 }, }, { single: { "raig": 2, "houk": 2 }, }, ], // Taihou Class "43": [ { multiple: { "houg": 1 }, }, { single: { "raig": 2, "houk": 2 }, }, ], }, byShip: [ { // Shoukaku, extra +1 fp origins: [110], multiple: { "houg": 1 }, }, { // Zuikaku, extra +1 ev origins: [111], single: { "houk": 1 }, }, { // Suzuya/Kumano CVL ids: [508, 509], multiple: { "houg": 1 }, }, { // Suzuya/Kumano CVL ids: [508, 509], single: { "raig": 2, "houk": 2 }, }, { // Ryuuhou K2 ids: [888], multiple: { "houg": 1 }, }, { // Ryuuhou K2 ids: [888], single: { "raig": 1, "houk": 1 }, }, { // Ryuuhou K2E ids: [883], single: { "raig": 2, "houk": 3 }, }, ], }, // Tenzan Model 12A Kai (Skilled / with Type 6 Airborne Radar) "374": { count: 0, byClass: { // Shouhou Class "11": [ // Base { multiple: { "houg": 1, "tais": 1 }, }, // Kai { remodel: 1, multiple: { "tais": 1 }, }, { remodel: 1, single: { "raig": 1, "houk": 1 }, }, // Kai Ni { remodel: 2, multiple: { "tais": 1 }, }, { remodel: 2, single: { "houk": 1 }, }, ], // Ryuuhou Class "51": [ // Ryuuhou Base { remodel: 1, multiple: { "houg": 1, "tais": 2 }, }, { remodel: 1, single: { "raig": 1, "houk": 1 }, }, // Ryuuhou Kai { remodel: 2, multiple: { "tais": 1 }, }, { remodel: 2, single: { "houk": 1 }, }, ], // Chitose Class "15": [ // CVL base { remodel: 3, multiple: { "houg": 1 }, }, { remodel: 3, single: { "raig": 1 }, }, // CVL Kai { remodel: 4, multiple: { "tais": 1 }, }, // CVL Kai Ni { remodel: 5, single: { "houk": 1 }, }, ], // Hiyou Class "24": [ { multiple: { "houg": 1 }, }, { single: { "raig": 2, "houk": 2 }, }, ], // Shoukaku Class "33": [ { multiple: { "houg": 2 }, }, { single: { "raig": 3, "houk": 3 }, }, ], // Taihou Class "43": [ { multiple: { "houg": 2 }, }, { single: { "raig": 3, "houk": 2 }, }, ], }, byShip: [ { // Shoukaku, extra +1 fp origins: [110], multiple: { "houg": 1 }, }, { // Zuikaku, extra +1 ev origins: [111], single: { "houk": 1 }, }, { // Suzuya/Kumano CVL ids: [508, 509], multiple: { "houg": 1, "tais": 2 }, }, { // Suzuya/Kumano CVL ids: [508, 509], single: { "raig": 2, "houk": 3 }, }, { // Ryuuhou K2 ids: [888], multiple: { "houg": 2 }, }, { // Ryuuhou K2 ids: [888], single: { "raig": 1, "houk": 1 }, }, { // Ryuuhou K2E ids: [883], multiple: { "houg": 1 }, }, { // Ryuuhou K2E ids: [883], single: { "raig": 2, "houk": 3 }, }, ], }, // Tenzan Model 12A "372": { count: 0, byClass: { // Shouhou Class "11": [ // Base { multiple: { "tais": 1 }, }, // Kai Ni { remodel: 2, single: { "raig": 1 }, }, ], // Chitose Class "15": [ // CVL { remodel: 3, multiple: { "houg": 1 }, }, ], // Hiyou Class "24": { multiple: { "houg": 1 }, }, // Shoukaku Class "33": [ { multiple: { "houg": 1 }, }, { single: { "raig": 1 }, }, ], // Taihou Class "43": "33", // Ryuuhou Class "51": [ // Ryuuhou Base { remodel: 1, multiple: { "tais": 1 }, }, // Ryuuhou Kai { remodel: 2, single: { "raig": 1 }, }, // Ryuuhou K2+ { remodel: 3, multiple: { "houg": 2 }, }, // Ryuuhou K2+ { remodel: 3, single: { "raig": 1 }, }, ], }, byShip: [ { // Suzuya/Kumano CVL ids: [508, 509], multiple: { "houg": 1 }, }, ], }, // Swordfish "242": { count: 0, byClass: { // Ark Royal Class "78": { multiple: { "houg": 2, "houk": 1 }, }, // Houshou Class "27": { multiple: { "houg": 1 }, }, }, }, // Swordfish Mk.II (Skilled) "243": { count: 0, byClass: { // Ark Royal Class "78": { multiple: { "houg": 3, "houk": 1 }, }, // Houshou Class "27": { multiple: { "houg": 2 }, }, }, }, // Swordfish Mk.III (Skilled) "244": { count: 0, byClass: { // Ark Royal Class "78": { multiple: { "houg": 4, "houk": 2 }, }, // Houshou Class "27": { multiple: { "houg": 3 }, }, }, }, // Ju 87C Kai Ni (w/ KMX) "305": { count: 0, byClass: { // Graf Zeppelin Class "63": { multiple: { "houg": 1, "houk": 1 }, }, // Aquila Class "68": "63", // Taiyou Class "76": { multiple: { "tais": 1, "houk": 1 }, }, }, byShip: [ // extra +2 asw, +1 ev for Shinyou { ids: [534, 381, 536], multiple: { "tais": 2, "houk": 1 }, }, ], }, // Ju 87C Kai Ni (w/ KMX / Skilled) "306": { count: 0, byClass: { // Graf Zeppelin Class "63": { multiple: { "houg": 1, "houk": 1 }, }, // Aquila Class "68": "63", // Taiyou Class "76": { multiple: { "tais": 1, "houk": 1 }, }, }, byShip: [ // extra +2 asw, +1 ev for Shinyou { ids: [534, 381, 536], multiple: { "tais": 2, "houk": 1 }, }, ], }, // Suisei "24": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 2 }, }, }, }, // Suisei Model 12A "57": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 2 }, }, }, }, // Suisei (601 Air Group) "111": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 2 }, }, }, }, // Type 99 Dive Bomber (Egusa Squadron) "99": { count: 0, byClass: { // Souryuu "17": { single: { "houg": 4 }, }, // Hiryuu "25": { single: { "houg": 1 }, }, }, }, // Suisei (Egusa Squadron) "100": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 4 }, }, // Souryuu Kai Ni "17": { remodel: 2, single: { "houg": 6 }, }, // Hiryuu Kai Ni "25": { remodel: 2, single: { "houg": 3 }, }, }, }, // Suisei Model 22 (634 Air Group) "291": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 6, "houk": 1 }, }, }, }, // Suisei Model 22 (634 Air Group / Skilled) "292": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 8, "tyku": 1, "houk": 2 }, }, }, }, // Suisei Model 12 (634 Air Group w/Type 3 Cluster Bombs) "319": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 7, "tyku": 3, "houk": 2 }, }, }, }, // Suisei Model 12 (w/Type 31 Photoelectric Fuze Bombs) "320": { count: 0, byShip: [ { // Ise Kai Ni +2 fp ids: [553], multiple: { "houg": 2 }, }, { // Hiryuu/Souryuu K2 +3 fp ids: [196, 197], multiple: { "houg": 3 }, }, { // Suzuya/Kumano CVL, Hyuuga Kai Ni +4 fp ids: [508, 509, 554], multiple: { "houg": 4 }, }, ], }, // Type 99 Dive Bomber Model 22 "391": { count: 0, byShip: [ { // Hiyou, Junyou, Shoukaku, Zuikaku origins: [75, 92, 110, 111], multiple: { "houg": 1 }, }, { // Zuihou, Ryuuhou, Shouhou Kai ids: [116, 185, 282], multiple: { "houg": 1 }, }, { // Zuihou Kai, Ryuuhou Kai+ ids: [117, 318, 883, 888], multiple: { "houg": 1 }, }, { // Zuihou Kai, Ryuuhou Kai+ ids: [117, 318, 883, 888], single: { "houk": 1 }, }, { // Zuihou K2, Zuihou K2B ids: [555, 560], multiple: { "houg": 1, "houk": 1 }, }, ], }, // Type 99 Dive Bomber Model 22 (Skilled) "392": { count: 0, byShip: [ { // Hiyou, Junyou origins: [75, 92], multiple: { "houg": 1, "houk": 1 }, }, { // Shoukaku, Zuikaku origins: [110, 111], multiple: { "houg": 2, "houk": 1 }, }, { // Zuihou, Ryuuhou, Shouhou Kai ids: [116, 185, 282], multiple: { "houg": 2, "houk": 1 }, }, { // Zuihou Kai, Ryuuhou Kai+ ids: [117, 318, 883, 888], multiple: { "houg": 2, "houk": 2 }, }, { // Zuihou K2, Zuihou K2B ids: [555, 560], multiple: { "houg": 3, "houk": 2 }, }, ], }, // Type 0 Fighter Model 62 (Fighter-bomber) "60": { count: 0, byShip: [ { // Hiyou, Junyou, Chitose, Chiyoda, Zuihou origins: [75, 92, 102, 103, 116], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // Ryuuhou, Ryuuhou Kai, Shouhou Kai ids: [185, 318, 282], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // Ryuuhou K2E, K2 ids: [883, 888], multiple: { "houg": 2, "tyku": 1, "houk": 2 }, }, ], }, // Zero Fighter Model 62 (Fighter-bomber / Iwai Squadron) "154": { count: 0, byShip: [ { // Hiyou, Junyou, Chitose, Chiyoda, Zuihou origins: [75, 92, 102, 103, 116], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // Ryuuhou, Ryuuhou Kai, Shouhou Kai ids: [185, 318, 282], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // Ryuuhou K2E, K2 ids: [883, 888], multiple: { "houg": 2, "tyku": 1, "houk": 2 }, }, ], }, // Type 0 Fighter Model 63 (Fighter-bomber) "219": { count: 0, byShip: [ { // Hiyou, Junyou, Chitose, Chiyoda, Zuihou origins: [75, 92, 102, 103, 116], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // Ryuuhou, Ryuuhou Kai, Shouhou Kai ids: [185, 318, 282], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // Ryuuhou K2E, K2 ids: [883, 888], multiple: { "houg": 2, "tyku": 1, "houk": 2 }, }, ], }, // FM-2 "277": { count: 0, byClass: { // Following carriers: Lexington Class "69": { multiple: { "houg": 1, "houk": 1 }, }, // Essex Class "84": "69", // Yorktown Class "105": "69", // Ark Royal Class "78": "69", // Illustrious Class "112": "69", // Casablanca Class "83": { multiple: { "houg": 2, "tyku": 1, "houk": 2 }, }, }, }, // SBD "195": { count: 0, byClass: { // Following American carriers: Lexington Class "69": { multiple: { "houg": 1 }, }, // Casablanca Class "83": "69", // Essex Class "84": "69", // Yorktown Class "105": "69", }, }, // SBD-5 "419": { count: 0, starsDist: [], byClass: { // Following American carriers: Lexington Class "69": [ { multiple: { "houg": 2 }, }, { minStars: 2, multiple: { "houg": 1 }, }, { minStars: 7, multiple: { "houg": 1 }, }, ], // Casablanca Class "83": "69", // Essex Class "84": "69", // Yorktown Class "105": "69", }, }, // SB2C-3 "420": { count: 0, starsDist: [], byClass: { // Following American carriers: Lexington Class "69": [ { multiple: { "houg": 1 }, }, { minStars: 3, multiple: { "houg": 1 }, }, ], // Casablanca Class "83": "69", // Yorktown Class "105": "69", // Illustrious Class "112": "69", // Essex Class "84": [ { multiple: { "houg": 2 }, }, { minStars: 3, multiple: { "houg": 1 }, }, ], // Ark Royal Class "78": { minStars: 3, multiple: { "houg": 1 }, }, }, byShip: { // All CVL -2 fp, -1 ev, -2 ar stypes: [7], multiple: { "houg": -2, "houk": -1, "souk": -2 }, }, }, // SB2C-5 "421": { count: 0, starsDist: [], byClass: { // Following American carriers: Lexington Class "69": [ { multiple: { "houg": 2 }, }, { minStars: 5, multiple: { "houg": 1 }, }, ], // Casablanca Class "83": "69", // Yorktown Class "105": "69", // Illustrious Class "112": "69", // Essex Class "84": [ { multiple: { "houg": 3 }, }, { minStars: 5, multiple: { "houg": 1 }, }, ], // Ark Royal Class "78": [ { multiple: { "houg": 1 }, }, { minStars: 5, multiple: { "houg": 1 }, }, ], }, byShip: { // All CVL -2 fp, -1 ev, -2 ar stypes: [7], multiple: { "houg": -2, "houk": -1, "souk": -2 }, }, }, // Type 96 Fighter "19": { count: 0, byClass: { // Taiyou Class "76": { multiple: { "houg": 2, "tais": 3 }, }, // Kasugamaru Class "75": "76", // Houshou Class "27": { multiple: { "houg": 2, "tyku": 2, "tais": 2, "houk": 2 }, }, }, byShip: { // All CVL +1 aa, +1 ev stypes: [7], multiple: { "tyku": 1, "houk": 1 }, }, }, // Type 96 Fighter Kai "228": { count: 0, byClass: { // Taiyou Class "76": { multiple: { "houg": 2, "tyku": 1, "tais": 5, "houk": 1 }, }, // Kasugamaru Class "75": "76", // Houshou Class "27": { multiple: { "houg": 3, "tyku": 3, "tais": 4, "houk": 4 }, }, }, byShip: { // All CVL +1 aa, +1 ev, +2 asw stypes: [7], multiple: { "tyku": 1, "tais": 2, "houk": 1 }, }, }, // Shiden Kai 4 "271": { count: 0, starsDist: [], byShip: [ { // Suzuya/Kumano-Kou Kai Ni, Ryuuhou Kai Ni+ ids: [508, 509, 883, 888], minStars: 4, multiple: { "houg": 1 }, }, { // Suzuya/Kumano-Kou Kai Ni, Ryuuhou Kai Ni+ ids: [508, 509, 883, 888], minStars: 6, multiple: { "tyku": 2 }, }, { // Suzuya/Kumano-Kou Kai Ni, Ryuuhou Kai Ni+ ids: [508, 509, 883, 888], minStars: 8, multiple: { "houk": 2 }, }, { // Suzuya/Kumano-Kou Kai Ni, Ryuuhou Kai Ni+ ids: [508, 509, 883, 888], minStars: 10, multiple: { "houg": 1 }, }, ], }, // Reppuu Kai (Prototype Carrier-based Model) "335": { count: 0, byClass: { // Kaga Class Kai+ "3": [ { remodel: 1, multiple: { "tyku": 1, "houk": 1 }, }, { remodel: 2, multiple: { "tyku": 1 }, }, ], // Akagi Class Kai+ "14": "3", }, }, // Reppuu Kai Ni "336": { count: 0, byClass: { // Kaga Class Kai+ "3": [ { remodel: 1, multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { remodel: 2, multiple: { "tyku": 1 }, }, ], // Akagi Class Kai+ "14": "3", }, }, // Reppuu Kai Ni (CarDiv 1 / Skilled) "337": { count: 0, byClass: { // Kaga Class Kai+ "3": [ { remodel: 1, multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, { remodel: 2, multiple: { "houg": 1, "tyku": 1 }, }, ], // Akagi Class Kai+ "14": "3", }, }, // Reppuu Kai Ni Model E "338": { count: 0, byClass: { // Kaga Class Kai+ "3": [ { remodel: 1, multiple: { "houg": 1, "tyku": 1, "houk": 2 }, }, { remodel: 2, multiple: { "tyku": 1, "houk": 1 }, }, ], // Akagi Class Kai+ "14": "3", }, byShip: { // Akagi K2E, Kaga K2E +4 fp, +3 aa, +4 ev totally // Kaga Kai Ni Go's bonus the same with Kai Ni's ids: [599, 610], multiple: { "houg": 3, "tyku": 1, "houk": 1 }, }, }, // Reppuu Kai Ni Model E (CarDiv 1 / Skilled) "339": { count: 0, byClass: { // Kaga Class Kai+ "3": [ { remodel: 1, multiple: { "houg": 1, "tyku": 2, "houk": 2 }, }, { remodel: 2, multiple: { "tyku": 1, "houk": 2 }, }, ], // Akagi Class Kai+ "14": "3", }, byShip: { // Akagi K2E, Kaga K2E +6 fp, +4 aa, +5 ev totally // Kaga Kai Ni Go's bonus the same with Kai Ni's ids: [599, 610], multiple: { "houg": 5, "tyku": 1, "houk": 1 }, }, }, // Re.2001 OR Kai "184": { count: 0, byClass: { // Aquila Class "68": { multiple: { "houg": 1, "tyku": 2, "houk": 3 }, }, }, }, // Re.2005 Kai "189": { count: 0, byClass: { // Aquila Class "68": { multiple: { "tyku": 1, "houk": 2 }, }, // Graf "63": "68", }, }, // Re.2001 G Kai "188": { count: 0, byClass: { // Aquila Class "68": { multiple: { "houg": 3, "tyku": 1, "houk": 1 }, }, }, }, // Re.2001 CB Kai "316": { count: 0, byClass: { // Aquila Class "68": { multiple: { "houg": 4, "tyku": 1, "houk": 1 }, }, }, }, // XF5U "375": { count: 0, byClass: { // Lexington Class "69": { multiple: { "houg": 3, "tyku": 3, "tais": 3, "houk": 3 }, }, // Casablanca Class "83": "69", // Essex Class "84": "69", // Yorktown Class "105": "69", // Kaga Class "3": { multiple: { "houg": 1, "tyku": 1, "tais": 1, "houk": 1 }, }, }, }, // FR-1 Fireball "422": { count: 0, byClass: { // Following carriers: Lexington Class "69": { multiple: { "houg": 1, "houk": 1 }, }, // Yorktown Class "105": "69", // Ark Royal Class "78": "69", // Illustrious Class "112": "69", // Essex Class "84": { multiple: { "houg": 2, "tyku": 1, "houk": 2 }, }, // Casablanca Class "83": [ { multiple: { "houg": 1, "houk": 1 }, }, { // Gambier Bay Mk.II remodel: 2, multiple: { "houg": 2, "tyku": 2, "houk": 2 }, }, ], }, }, // Corsair Mk.II "434": { count: 0, byClass: { // Illustrious Class "112": { multiple: { "houg": 2, "tyku": 3, "houk": 5 }, }, // Ark Royal Class "78": { multiple: { "houg": 1, "tyku": 2, "houk": 3 }, }, // Lexington Class "69": { multiple: { "houg": 1, "tyku": 1, "houk": 2 }, }, // Casablanca Class "83": "69", // Essex Class "84": "69", // Yorktown Class "105": "69", }, }, // Corsair Mk.II (Ace) "435": { count: 0, byClass: { // Illustrious Class "112": { multiple: { "houg": 2, "tyku": 3, "houk": 5 }, }, // Ark Royal Class "78": { multiple: { "houg": 1, "tyku": 2, "houk": 3 }, }, // Lexington Class "69": { multiple: { "houg": 1, "tyku": 1, "houk": 2 }, }, // Casablanca Class "83": "69", // Essex Class "84": "69", // Yorktown Class "105": "69", }, }, // Prototype Jinpuu "437": { count: 0, byShip: [ { // Hiryuu/Souryuu Kai Ni ids: [196, 197], multiple: { "houg": 2, "tyku": 2, "houk": 3 }, }, { // Houshou Kai ids: [285], multiple: { "houg": 3, "tyku": 3, "houk": 4 }, }, { // Suzuya/Kumano-Kou Kai Ni, Kaga Kai Ni Go ids: [508, 509, 646], multiple: { "houg": 2, "tyku": 2, "houk": 2 }, }, { // Ise/Hyuuga Kai Ni, Ryuuhou Kai Ni+, ids: [553, 554, 883, 888], multiple: { "houg": 1, "tyku": 2, "houk": 2 }, }, ], }, // All carrier-based improved recon planes on all ships can equip, current implemented: // Saiun, Type 2 Reconnaissance Aircraft, Prototype Keiun (Carrier-based Reconnaissance Model) "t2_9": { count: 0, starsDist: [], byShip: [ { // stars+2, +1 los minStars: 2, single: { "houg": 0, "saku": 1 }, }, { // stars+4 extra +1 fp, accumulative +1 fp, +1 los minStars: 4, single: { "houg": 1 }, }, { // stars+6 extra +1 los, accumulative +1 fp, +2 los minStars: 6, single: { "saku": 1 }, }, { // stars+10 accumulative +2 fp, +3 los minStars: 10, single: { "houg": 1, "saku": 1 }, }, ], }, // Type 2 Reconnaissance Aircraft // https://wikiwiki.jp/kancolle/%E4%BA%8C%E5%BC%8F%E8%89%A6%E4%B8%8A%E5%81%B5%E5%AF%9F%E6%A9%9F "61": { count: 0, starsDist: [], byClass: { // Ise Class Kai Ni, range +1 too, can be extreme long "2": { remodel: 2, single: { "houg": 3, "souk": 1, "houk": 2, "houm": 5, "leng": 1 }, }, "17": [ { // Souryuu stars+1 minStars: 1, single: { "houg": 3, "saku": 3 }, }, { // Souryuu K2 stars+8 totally +5 fp, +6 los minStars: 8, remodel: 2, single: { "houg": 1, "saku": 1 }, }, { // Souryuu Kai Ni acc+5, range +1 remodel: 2, single: { "houm": 5, "leng": 1 }, }, ], "25": [ { // Hiryuu K2 stars+1 minStars: 1, single: { "houg": 2, "saku": 2 }, }, { // Hiryuu Kai Ni acc+5, range +1 remodel: 2, single: { "houm": 5, "leng": 1 }, }, ], }, byShip: [ { // Hyuuga Kai Ni, extra +2 ar, +1 ev ids: [554], single: { "souk": 2, "houk": 1 }, }, { // Suzuya/Kumano Kou K2, Zuihou K2B stars+1 ids: [508, 509, 560], minStars: 1, single: { "houg": 1, "saku": 1 }, }, ], }, // Fulmar (Reconnaissance Fighter / Skilled) "423": { count: 0, byClass: { // Ark Royal Class "78": { multiple: { "houg": 4, "tyku": 4, "houk": 4, "saku": 4 }, }, // Illustrious Class "112": "78", // Lexington Class "69": { multiple: { "houg": 1, "tyku": 1, "houk": 1, "saku": 1 }, }, // Casablanca Class "83": "69", // Essex Class "84": "69", // Yorktown Class "105": "69", }, }, // Barracuda Mk.II "424": { count: 0, starsDist: [], byClass: { // Ark Royal Class "78": [ { multiple: { "houg": 2, "raig": 3 }, }, { minStars: 2, multiple: { "houg": 1 }, }, { minStars: 6, multiple: { "houg": 1 }, }, ], // Illustrious Class "112": "78", }, }, // Barracuda Mk.III "425": { count: 0, starsDist: [], byClass: { // Ark Royal Class "78": [ { multiple: { "houg": 2, "tais": 2, "raig": 1, "saku": 1 }, }, { minStars: 2, multiple: { "tais": 1 }, }, { minStars: 4, multiple: { "houg": 1 }, }, { minStars: 6, multiple: { "tais": 1 }, }, { minStars: 8, multiple: { "raig": 1 }, }, { minStars: 10, multiple: { "tais": 1 }, }, ], // Illustrious Class "112": "78", }, }, // Zuiun "26": { count: 0, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "houg": 2, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], single: { "houg": 2 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "tyku": 1, "houk": 1 }, }, ], }, // Prototype Seiran "62": { count: 0, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "houg": 2, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], single: { "houg": 2 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "tyku": 1, "houk": 1 }, }, ], }, // Zuiun (634 Air Group) "79": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 3 }, }, // Fusou Class Kai Ni "26": { remodel: 2, multiple: { "houg": 2 }, }, }, byShip: [ { // Ise Class Kai ids: [82, 88], multiple: { "houg": 2 }, }, { // Noshiro Kai Ni ids: [662], single: { "houg": 2, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], single: { "houg": 2 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "tyku": 1, "houk": 1 }, }, ], }, // Zuiun Model 12 "80": { count: 0, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "houg": 2, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], single: { "houg": 2 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "tyku": 1, "houk": 1 }, }, ], }, // Zuiun Model 12 (634 Air Group) "81": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 3 }, }, // Fusou Class Kai Ni "26": { remodel: 2, multiple: { "houg": 2 }, }, }, byShip: [ { // Ise Class Kai ids: [82, 88], multiple: { "houg": 2 }, }, { // Noshiro Kai Ni ids: [662], single: { "houg": 2, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], single: { "houg": 2 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "tyku": 1, "houk": 1 }, }, ], }, // Zuiun (631 Air Group) "207": { count: 0, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "houg": 2, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], single: { "houg": 2 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "tyku": 1, "houk": 1 }, }, ], }, // Seiran (631 Air Group) "208": { count: 0, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "houg": 2, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], single: { "houg": 2 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "tyku": 1, "houk": 1 }, }, ], }, // Zuiun (634 Air Group / Skilled) "237": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 4, "houk": 2 }, }, // Fusou Class Kai Ni "26": { remodel: 2, multiple: { "houg": 2 }, }, }, byShip: [ { // Ise Class Kai ids: [82, 88], multiple: { "houg": 3, "houk": 1 }, }, { // Noshiro Kai Ni ids: [662], single: { "houg": 3, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "houg": 3, "tyku": 1, "houk": 2 }, }, ], }, // Zuiun Kai Ni (634 Air Group) "322": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 5, "tyku": 2, "tais": 1, "houk": 2 }, }, }, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "houg": 3, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "houg": 3, "tyku": 1, "houk": 2 }, }, ], }, // Zuiun Kai Ni (634 Air Group / Skilled) "323": { count: 0, byClass: { // Ise Class Kai Ni "2": { remodel: 2, multiple: { "houg": 6, "tyku": 3, "tais": 2, "houk": 3 }, }, }, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "houg": 3, "houk": 1 }, }, { // Yahagi Kai Ni+, Mogami Kai Ni+ ids: [663, 668, 501, 506], multiple: { "houg": 3, "tyku": 1, "houk": 2 }, }, ], }, // Laté 298B "194": { count: 0, byClass: { // Commandant Teste Class "70": { multiple: { "houg": 3, "houk": 2, "saku": 2 }, }, // Richelieu Kai "79": { remodel: 1, multiple: { "houg": 1, "houk": 2, "saku": 2 }, }, // Mizuho Class "62": { multiple: { "houk": 1, "saku": 2 }, }, // Kamoi Class "72": "62", }, }, // Swordfish (Seaplane Model) "367": { count: 0, byClass: { // Commandant Teste Class "70": { multiple: { "houg": 1, "tais": 1, "houk": 1, "saku": 1 }, }, // Gotland Class "89": { multiple: { "houg": 2, "tais": 1, "houk": 1, "saku": 1 }, }, // Mizuho Class "62": { multiple: { "houg": 1, "houk": 1, "saku": 1 }, }, // Kamoi Class "72": "62", /* Queen Elizabeth Class, Ark Royal Class, J Class and Nelson Class (but they can not equip) "67": { multiple: { "houg": 2, "houk": 2, "saku": 2 }, }, "78": "67", "82": "67", "88": "67", */ }, }, // Swordfish Mk.III Kai (Seaplane Model) "368": { count: 0, byClass: { // Commandant Teste Class "70": { multiple: { "houg": 2, "tais": 3, "houk": 1, "saku": 2 }, }, // Gotland Class "89": [ { multiple: { "houg": 4, "tais": 3, "houk": 2, "saku": 3 }, }, { // Gotland andra FP +2, TP +2, EV +1, LoS +1 remodel: 2, single: { "houg": 2, "raig": 2, "houk": 1, "saku": 1 }, }, ], // Mizuho Class "62": { multiple: { "houg": 1, "tais": 2, "houk": 1, "saku": 2 }, }, // Kamoi Class "72": "62", }, }, // Swordfish Mk.III Kai (Seaplane Model/Skilled) "369": { count: 0, byClass: { // Commandant Teste Class "70": { multiple: { "houg": 3, "tais": 3, "houk": 2, "saku": 3 }, }, // Gotland Class "89": [ { multiple: { "houg": 5, "tais": 4, "houk": 4, "saku": 3 }, }, { // Gotland andra FP +3, TP +3, EV +2, LoS +2 remodel: 2, single: { "houg": 3, "raig": 3, "houk": 2, "saku": 2 }, }, ], // Mizuho Class "62": { multiple: { "houg": 2, "tais": 2, "houk": 1, "saku": 2 }, }, // Kamoi Class "72": "62", }, }, // Type 0 Observation Seaplane "59": { count: 0, byShip: { // Mogami Kai Ni+ ids: [501, 506], single: { "tyku": 1, "houk": 1 }, }, }, // S9 Osprey "304": { count: 0, byClass: { // Kuma Class "4": { multiple: { "houg": 1, "tais": 1, "houk": 1 }, }, // Sendai Class "16": "4", // Nagara Class "20": "4", // Agano Class "41": "4", // Gotland Class "89": { multiple: { "houg": 1, "tais": 2, "houk": 2 }, }, }, }, // Swordfish Mk.II Kai (Recon Seaplane Model) "370": { count: 0, byClass: { // Gotland Class "89": [ { multiple: { "houg": 1, "tais": 3, "houk": 1, "saku": 2 }, }, ], // Commandant Teste Class "70": { multiple: { "houg": 1, "tais": 3, "houk": 1, "saku": 1 }, }, // Mizuho Class "62": { multiple: { "houg": 1, "tais": 2, "houk": 1, "saku": 1 }, }, // Kamoi Class "72": "62", // Queen Elizabeth Class "67": [ { multiple: { "houg": 2, "tais": 3, "houk": 2, "saku": 2 }, }, // Warspite only { single: { "houg": 4, "houk": 1, "saku": 1 }, }, ], // Nelson Class "88": { multiple: { "houg": 2, "tais": 3, "houk": 2, "saku": 2 }, }, // Town Class "108": "88", }, }, // Fairey Seafox Kai "371": { count: 0, byClass: { // Gotland Class "89": [ { multiple: { "houg": 4, "tais": 2, "houk": 3, "saku": 6 }, }, { // Gotland andra FP +2, EV +2, LoS +3 remodel: 2, single: { "houg": 2, "houk": 2, "saku": 3 }, }, ], // Commandant Teste Class "70": { multiple: { "houg": 2, "tais": 1, "houk": 2, "saku": 4 }, }, // Richelieu Class "79": { multiple: { "houg": 2, "houk": 1, "saku": 3 }, }, // Queen Elizabeth Class "67": { multiple: { "houg": 3, "tais": 1, "houk": 2, "saku": 3 }, }, // Town Class "108": "67", // Nelson Class "88": [ { multiple: { "houg": 3, "tais": 1, "houk": 2, "saku": 3 }, }, { single: { "houg": 3, "houk": 2, "saku": 2 }, }, ], }, }, // OS2U "171": { count: 0, starsDist: [], byClass: { // Iowa Class "65": [ { single: { "houg": 1, "saku": 1 }, }, { minStars: 3, single: { "saku": 1 }, }, { minStars: 5, single: { "houk": 1 }, }, { minStars: 8, single: { "saku": 1 }, }, { minStars: 10, single: { "houg": 1 }, }, ], // Colorado Class "93": "65", // South Dakota Class "102": "65", // North Carolina Class "107": "65", // Northampton Class "95": [ { minStars: 5, single: { "houk": 1 }, }, { minStars: 10, single: { "houg": 1 }, }, ], // Atlanta Class "99": "95", // St. Louis Class "106": "95", // Brooklyn Class "110": "95", }, }, // SOC Seagull "414": { count: 0, starsDist: [], byClass: { // Following Americans: // Iowa Class "65": [ { single: { "saku": 1 }, }, { minStars: 5, single: { "houk": 1 }, }, ], // Colorado Class "93": "65", // South Dakota Class "102": "65", // North Carolina Class "107": "65", // Northampton Class "95": [ { single: { "houg": 1, "saku": 2 }, }, { minStars: 3, single: { "saku": 1 }, }, { minStars: 5, single: { "houk": 1 }, }, { minStars: 8, single: { "houk": 1 }, }, { minStars: 10, single: { "houg": 1 }, }, ], // Atlanta Class "99": "95", // St. Louis Class "106": "95", // Brooklyn Class "110": "95", }, }, // SO3C Seamew Kai "415": { count: 0, starsDist: [], byClass: { // Following Americans: // Iowa Class "65": [ { single: { "saku": 1, "tais": 1 }, }, { minStars: 5, single: { "houk": 1 }, }, ], // Colorado Class "93": "65", // South Dakota Class "102": "65", // North Carolina Class "107": "65", // Northampton Class "95": [ { single: { "houg": 1, "saku": 1, "tais": 1 }, }, { minStars: 3, single: { "houk": 1 }, }, { minStars: 8, single: { "houg": 1 }, }, ], // Atlanta Class "99": "95", // St. Louis Class "106": "95", // Brooklyn Class "110": "95", }, }, // Ar196 Kai "115": { count: 0, starsDist: [], byClass: { // Bismarck Class "47": [ { multiple: { "houg": 2, "houk": 1, "saku": 2 }, }, { minStars: 10, multiple: { "houg": 1, "houk": 1 }, }, ], // Admiral Hipper Class "55": "47", }, }, // Shiun "118": { count: 0, starsDist: [], byClass: { // Ooyodo Class "52": [ { multiple: { "houg": 1, "houk": 2, "saku": 2 }, }, { minStars: 10, multiple: { "houg": 2, "saku": 1 }, }, ], }, }, // Type 2 Seaplane Fighter Kai "165": { count: 0, byShip: { // Mogami K2+ ids: [501, 506], single: { "tyku": 2, "houk": 2 }, }, }, // Type 2 Seaplane Fighter Kai (Skilled) "216": { count: 0, byShip: { // Mogami K2+ ids: [501, 506], single: { "tyku": 2, "houk": 2 }, }, }, // Type 0 Reconnaissance Seaplane Model 11B "238": { count: 0, byShip: { // Mogami K2+ ids: [501, 506], single: { "raig": 1, "houk": 1 }, }, }, // Type 0 Reconnaissance Seaplane Model 11B (Skilled) "239": { count: 0, byShip: { // Mogami K2+ ids: [501, 506], single: { "raig": 1, "houk": 1 }, }, }, // Kyoufuu Kai "217": { count: 0, byShip: { // Mogami K2+ ids: [501, 506], multiple: { "houg": 1, "tyku": 5, "houk": 3 }, }, }, // Ka Type Observation Autogyro "69": { count: 0, byShip: [ { // Ise Kai Ni ids: [553], multiple: { "houg": 1, "tais": 1 }, }, { // Hyuuga Kai Ni, Kaga Kai Ni Go ids: [554, 646], multiple: { "houg": 1, "tais": 2 }, }, ], }, // O Type Observation Autogyro Kai "324": { count: 0, byShip: [ { // Ise Kai Ni ids: [553], multiple: { "houg": 1, "tais": 2, "houk": 1 }, }, { // Hyuuga Kai Ni, Kaga Kai Ni Go ids: [554, 646], multiple: { "houg": 2, "tais": 3, "houk": 1 }, }, ], }, // O Type Observation Autogyro Kai Ni "325": { count: 0, byShip: [ { // Ise Kai Ni ids: [553], multiple: { "houg": 1, "tais": 2, "houk": 1 }, }, { // Hyuuga Kai Ni, Kaga Kai Ni Go ids: [554, 646], multiple: { "houg": 2, "tais": 3, "houk": 1 }, }, ], }, // S-51J "326": { count: 0, byShip: [ { // Ise Kai Ni ids: [553], multiple: { "houg": 1, "tais": 3, "houk": 1 }, }, { // Hyuuga Kai Ni ids: [554], multiple: { "houg": 3, "tais": 4, "houk": 2 }, }, { // Kaga Kai Ni Go ids: [646], multiple: { "houg": 3, "tais": 5, "houk": 3 }, }, ], }, // S-51J Kai "327": { count: 0, byShip: [ { // Ise Kai Ni ids: [553], multiple: { "houg": 2, "tais": 4, "houk": 1 }, }, { // Hyuuga Kai Ni ids: [554], multiple: { "houg": 4, "tais": 5, "houk": 2 }, }, { // Kaga Kai Ni Go ids: [646], multiple: { "houg": 5, "tais": 6, "houk": 4 }, }, ], }, // 35.6cm Twin Gun Mount (Dazzle Camouflage) "104": { count: 0, byShip: [ { // all Kongou Class Kai Ni ids: [149, 150, 151, 152], multiple: { "houg": 1 }, }, { // for Kongou K2 and Haruna K2 ids: [149, 151], multiple: { "houg": 1 }, }, { // extra +1 aa, +2 ev for Haruna K2 ids: [151], multiple: { "tyku": 1, "houk": 2 }, }, ], }, // 35.6cm Triple Gun Mount Kai (Dazzle Camouflage) "289": { count: 0, byShip: [ { // all Kongou Class Kai Ni ids: [149, 150, 151, 152], multiple: { "houg": 1 }, }, { // for Kongou K2 and Haruna K2 ids: [149, 151], multiple: { "houg": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 2 }, }, }, { // extra +1 aa for Kongou K2 ids: [149], multiple: { "tyku": 1 }, }, { // extra +2 aa, +2 ev for Haruna K2 ids: [151], multiple: { "tyku": 2, "houk": 2 }, }, ], }, // 35.6cm Twin Gun Mount Kai "328": { count: 0, byClass: { "6": [ // Kongou Class { multiple: { "houg": 1, "houk": 1 }, }, // extra +1 fp for Kongou Class Kai+ { remodel: 1, multiple: { "houg": 1 }, }, ], // Ise Class "2": { multiple: { "houg": 1 }, }, // Fusou Class "26": "2", }, byShip: [ // extra +1 fp, +1 tp for Kongou Kai Ni C { ids: [591], multiple: { "houg": 1, "raig": 1 }, }, // extra +1 fp, +1 aa for Hiei Kai Ni C { ids: [592], multiple: { "houg": 1, "tyku": 1 }, }, ], }, // 35.6cm Twin Gun Mount Kai Ni "329": { count: 0, byClass: { "6": [ // Kongou Class { multiple: { "houg": 1, "houk": 1 }, }, // extra +1 fp for Kongou Class Kai+ { remodel: 1, multiple: { "houg": 1 }, }, // extra +1 fp, +1 aa for Kongou Class Kai Ni+ { remodel: 2, multiple: { "houg": 1, "tyku": 1 }, }, // extra +1 fp, +2 tp for Kongou Class Kai Ni C { remodel: 3, multiple: { "houg": 1, "raig": 2 }, }, ], // Ise Class "2": { multiple: { "houg": 1 }, }, // Fusou Class "26": "2", }, }, // 41cm Triple Gun Mount Kai Ni // https://wikiwiki.jp/kancolle/41cm%E4%B8%89%E9%80%A3%E8%A3%85%E7%A0%B2%E6%94%B9%E4%BA%8C "290": { count: 0, byClass: { "2": [ // Ise Class Kai+ { remodel: 1, multiple: { "houg": 2, "tyku": 2, "houk": 1 }, synergy: { flags: [ "airRadar" ], single: { "tyku": 2, "houk": 3 }, }, }, // extra +1 fp, +3 acc for Ise Class Kai Ni { remodel: 2, multiple: { "houg": 1, "houm": 3 }, }, ], // Fusou Class Kai Ni "26": { remodel: 2, multiple: { "houg": 1 }, }, }, byShip: { // extra +1 ev for Hyuuga Kai Ni ids: [554], multiple: { "houk": 1 }, }, }, // 41cm Twin Gun Mount Kai Ni // https://wikiwiki.jp/kancolle/41cm%E9%80%A3%E8%A3%85%E7%A0%B2%E6%94%B9%E4%BA%8C "318": { count: 0, byClass: { // Ise Class Kai+ "2": { remodel: 1, multiple: { "houg": 2, "tyku": 2, "houk": 2 }, synergy: { // `distinct` means only 1 set takes effect at the same time, // not stackable with 41cm Triple K2's air radar synergy // see https://twitter.com/KennethWWKK/status/1098960971865894913 flags: [ "tripleLargeGunMountK2Nonexist", "airRadar" ], distinct: { "tyku": 2, "houk": 3, "houm": 1 }, }, }, // Nagato Class Kai Ni "19": { remodel: 2, multiple: { "houg": 3, "tyku": 2, "houk": 1, "houm": 2 }, synergy: { flags: [ "tripleLargeGunMountK2" ], single: { "houg": 2, "souk": 1, "houk": 2, "houm": 1 }, }, }, // Fusou Class Kai Ni "26": { remodel: 2, multiple: { "houg": 1 }, }, }, byShip: [ { // extra +3 acc for Ise Kai Ni ids: [553], multiple: { "houm": 3 }, // extra +1 ar, +2 ev when synergy with `41cm Triple Gun Mount Kai Ni` synergy: { flags: [ "tripleLargeGunMountK2" ], single: { "souk": 1, "houk": 2 }, }, }, { // extra +1 fp, +3 acc for Hyuuga Kai Ni ids: [554], multiple: { "houg": 1, "houm": 3 }, // extra +1 fp, +1 ar, +2 ev, +1 acc when synergy with `41cm Triple Gun Mount Kai Ni` synergy: { flags: [ "tripleLargeGunMountK2" ], single: { "houg": 1, "souk": 1, "houk": 2, "houm": 1 }, }, }, ], }, // 16inch Mk.I Triple Gun Mount "298": { count: 0, byClass: { // Nelson Class "88": { multiple: { "houg": 2, "souk": 1 }, }, // Queen Elizabeth Class "67": { multiple: { "houg": 2, "souk": 1, "houk": -2 }, }, // Kongou Class Kai Ni only (K2C incapable) "6": { remodel: 2, remodelCap: 2, multiple: { "houg": 1, "souk": 1, "houk": -3 }, }, }, }, // 16inch Mk.I Triple Gun Mount + AFCT Kai "299": { count: 0, byClass: { // Nelson Class "88": { multiple: { "houg": 2, "souk": 1 }, }, // Queen Elizabeth Class "67": { multiple: { "houg": 2, "souk": 1, "houk": -2 }, }, // Kongou Class Kai Ni only (K2C incapable) "6": { remodel: 2, remodelCap: 2, multiple: { "houg": 1, "souk": 1, "houk": -3 }, }, }, }, // 16inch Mk.I Triple Gun Mount Kai + FCR Type 284 "300": { count: 0, byClass: { // Nelson Class "88": { multiple: { "houg": 2, "souk": 1 }, }, // Queen Elizabeth Class "67": { multiple: { "houg": 2, "souk": 1, "houk": -2 }, }, // Kongou Class Kai Ni only (K2C incapable) "6": { remodel: 2, remodelCap: 2, multiple: { "houg": 1, "souk": 1, "houk": -3 }, }, }, }, // 16inch Mk.I Twin Gun Mount "330": { count: 0, byClass: { // Colorado Class "93": { multiple: { "houg": 1 }, }, // Nelson Class "88": [ { multiple: { "houg": 1 }, }, { remodel: 1, multiple: { "houg": 1 }, }, ], // Nagato Class "19": [ { multiple: { "houg": 1 }, }, // Kai Ni { remodel: 2, multiple: { "houg": 1 }, }, ], }, }, // 16inch Mk.V Twin Gun Mount "331": { count: 0, byClass: { // Colorado Class "93": [ { multiple: { "houg": 1 }, }, { remodel: 1, multiple: { "houg": 1, "houk": 1 }, }, ], // Nelson Class "88": [ { multiple: { "houg": 1 }, }, { remodel: 1, multiple: { "houg": 1 }, }, ], // Nagato Class "19": [ { multiple: { "houg": 1 }, }, // Kai Ni { remodel: 2, multiple: { "houg": 1 }, }, ], }, }, // 16inch Mk.VIII Twin Gun Mount Kai "332": { count: 0, byClass: { // Colorado Class "93": [ { multiple: { "houg": 1 }, }, { remodel: 1, multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, ], // Nelson Class "88": [ { multiple: { "houg": 1 }, }, { remodel: 1, multiple: { "houg": 1 }, }, ], // Nagato Class "19": [ { multiple: { "houg": 1 }, }, // Kai Ni { remodel: 2, multiple: { "houg": 1 }, }, ], }, }, // 16inch Triple Gun Mount Mk.6 "381": { count: 0, starsDist: [], byClass: { // Following American can equip Large Main Gun: // Iowa "65": [ { multiple: { "houg": 1 }, }, { minStars: 6, multiple: { "houg": 1 }, }, ], // Colorado "93": "65", // North Carolina Class "107": "65", // South Dakota "102": [ { multiple: { "houg": 2 }, }, { minStars: 6, multiple: { "houg": 1 }, }, ], }, }, // 16inch Triple Gun Mount Mk.6 mod.2 "385": { count: 0, starsDist: [], byClass: { // Following American can equip Large Main Gun: // Iowa "65": [ { multiple: { "houg": 1 }, }, { minStars: 6, multiple: { "houg": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], // Colorado "93": [ { multiple: { "houg": 2 }, }, { minStars: 6, multiple: { "houg": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], // South Dakota "102": [ { multiple: { "houg": 2, "souk": 1 }, }, { minStars: 6, multiple: { "houg": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], // North Carolina Class "107": "102", }, byShip: { // Any FBB stypes: [8], multiple: { "houg": 1 }, }, }, // 16inch Triple Gun Mount Mk.6 + GFCS "390": { count: 0, starsDist: [], byClass: { // Following American can equip Large Main Gun: // Iowa "65": [ { multiple: { "houg": 1 }, }, { minStars: 3, multiple: { "houg": 1 }, }, { minStars: 6, multiple: { "houk": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], // Colorado "93": [ { multiple: { "houg": 2 }, }, { minStars: 3, multiple: { "houg": 1 }, }, { minStars: 6, multiple: { "houk": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], // South Dakota "102": [ { multiple: { "houg": 2, "souk": 1 }, }, { minStars: 3, multiple: { "houg": 1 }, }, { minStars: 6, multiple: { "houk": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], // North Carolina Class "107": "102", }, byShip: { // Any FBB stypes: [8], multiple: { "houg": 1 }, }, }, // 16inch Triple Rapid Fire Gun Mount Mk.16 "386": { count: 0, starsDist: [], byClass: { // Following American can equip Medium Main Gun: // Colorado "93": [ { multiple: { "houg": 1 }, }, { minStars: 2, multiple: { "houg": 1 }, }, { minStars: 7, multiple: { "houg": 1 }, }, ], // Northampton "95": "93", // Atlanta "99": "93", // St. Louis "106": "93", // Brooklyn Class "110": "93", }, }, // 16inch Triple Rapid Fire Gun Mount Mk.16 mod.2 "387": { count: 0, starsDist: [], byClass: { // Following American can equip Medium Main Gun: // Colorado "93": [ { multiple: { "houg": 1 }, }, { minStars: 2, multiple: { "houg": 1 }, }, { minStars: 7, multiple: { "houg": 1 }, }, ], // Northampton "95": "93", // Atlanta "99": "93", // St. Louis "106": "93", // Brooklyn Class "110": "93", }, }, // 6inch Mk.XXIII Triple Gun Mount "399": { count: 0, starsDist: [], byClass: { // Town Class "108": [ { multiple: { "houg": 1, "houk": 2 }, }, { minStars: 3, multiple: { "houg": 1 }, }, { minStars: 5, multiple: { "houg": 1 }, }, ], }, }, // 305mm/46 Twin Gun Mount "426": { count: 0, byClass: { // Conte di Cavour Class "113": [ { multiple: { "houg": 3, "houk": 1 }, synergy: { flags: [ "triple305mm46LargeGunMount" ], single: { "houg": 1, "houk": 1 }, }, }, { minCount: 2, single: { "houg": 1, "houk": 1 }, synergy: { flags: [ "triple305mm46LargeGunMount" ], single: { "houg": -1, "houk": -1 }, }, }, ], // Gangut Class "73": [ { multiple: { "houg": 2, "houk": 1 }, synergy: { flags: [ "triple305mm46LargeGunMount" ], single: { "houg": 1 }, }, }, { minCount: 2, single: { "houg": 1 }, synergy: { flags: [ "triple305mm46LargeGunMount" ], single: { "houg": -1 }, }, }, ], }, }, // 305mm/46 Triple Gun Mount "427": { count: 0, byClass: { // Conte di Cavour Class "113": { multiple: { "houg": 2 }, }, // Gangut Class "73": { multiple: { "houg": 1 }, }, }, }, // 320mm/44 Twin Gun Mount "428": { count: 0, byClass: { // Conte di Cavour Class "113": [ { multiple: { "houg": 3, "houk": 1 }, synergy: { flags: [ "triple320mm44LargeGunMount" ], single: { "houg": 2, "houk": 1 }, }, }, { minCount: 2, single: { "houg": 2, "houk": 1 }, synergy: { flags: [ "triple320mm44LargeGunMount" ], single: { "houg": -2, "houk": -1 }, }, }, ], // Gangut Class "73": [ { multiple: { "houg": 2, "houk": 1 }, synergy: { flags: [ "triple320mm44LargeGunMount" ], single: { "houg": 1 }, }, }, { minCount: 2, single: { "houg": 1 }, synergy: { flags: [ "triple320mm44LargeGunMount" ], single: { "houg": -1 }, }, }, ], // V.Veneto Class "58": [ { multiple: { "houg": 1, "houk": 2 }, synergy: { flags: [ "triple320mm44LargeGunMount" ], single: { "houg": 2, "houk": 1 }, }, }, { minCount: 2, single: { "houg": 2, "houk": 1 }, synergy: { flags: [ "triple320mm44LargeGunMount" ], single: { "houg": -2, "houk": -1 }, }, }, ], }, }, // 320mm/44 Triple Gun Mount "429": { count: 0, byClass: { // Conte di Cavour Class "113": { multiple: { "houg": 2 }, }, // Gangut Class "73": { multiple: { "houg": 1 }, }, }, }, // 14cm Twin Gun Mount "119": { count: 0, byClass: { // Yuubari Class "34": { multiple: { "houg": 1 }, }, // Katori Class "56": "34", // Nisshin Class "90": { multiple: { "houg": 2, "raig": 1 }, }, }, }, // 14cm Twin Gun Mount Kai "310": { count: 0, starsDist: [], byClass: { // Yuubari Class "34": [ { multiple: { "houg": 2, "tyku": 1, "houk": 1 }, }, { minStars: 10, multiple: { "houg": 2 }, }, // Yuubari Kai Ni+ { remodel: 2, multiple: { "houg": 2, "tais": 1, "houk": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 3, "raig": 2, "houk": 2 }, }, }, // Yuubari Kai Ni+ with stars >= 7 { remodel: 2, minStars: 7, multiple: { "houg": 1, "raig": 1 }, }, ], // Katori Class "56": [ { multiple: { "houg": 2, "houk": 1 }, }, { minStars: 10, multiple: { "houg": 2, "houk": 2 }, }, ], // Nisshin Class "90": [ { multiple: { "houg": 3, "raig": 2, "tyku": 1, "houk": 1 }, }, { minStars: 10, multiple: { "houg": 1, "raig": 1 }, }, ], }, }, // 15.5cm Triple Gun Mount "5": { count: 0, byClass: { // Mogami Class "9": { multiple: { "houg": 1 }, }, // Ooyodo Class "52": "9", }, }, // 15.5cm Triple Gun Mount Kai "235": { count: 0, byClass: { // Mogami Class "9": { multiple: { "houg": 1, "tyku": 1 }, }, // Ooyodo Class "52": "9", }, byShip: { // Ooyodo Kai ids: [321], multiple: { "houg": 1, "houk": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 3, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "tyku": 3, "houk": 3 }, }, ], }, }, // 15.2cm Twin Gun Mount Kai "139": { count: 0, byShip: { // Noshiro Kai Ni, Yahagi Kai Ni/K2B ids: [662, 663, 668], multiple: { "houg": 2, "tyku": 1 }, }, }, // 15.2cm Twin Gun Mount Kai Ni "407": { count: 0, byShip: { // Noshiro Kai Ni, Yahagi Kai Ni/K2B ids: [662, 663, 668], multiple: { "houg": 4, "tyku": 2, "houk": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 2, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "tyku": 2, "houk": 3 }, }, ], }, }, // 20.3cm (No.2) Twin Gun Mount "90": { count: 0, byClass: { // Furutaka Class "7": { multiple: { "houg": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 3, "raig": 2, "houk": 2 }, }, }, // Aoba Class "13": "7", // Takao Class "8": { multiple: { "houg": 1 }, }, // Mogami Class "9": "8", // Myoukou Class "29": "8", // Tone Class "31": "8", }, byShip: [ { // Aoba all remodels extra Air Radar synergy origins: [61], synergy: { flags: [ "airRadar" ], single: { "tyku": 5, "houk": 2 }, }, }, { // Aoba Kai, extra +1 fp, +1 aa ids: [264], multiple: { "houg": 1, "tyku": 1 }, }, { // Kinugasa Kai Ni ids: [142], multiple: { "houg": 2, "houk": 1 }, }, { // Kinugasa Kai, Furutaka Kai Ni, Kako Kai Ni ids: [295, 416, 417], multiple: { "houg": 1 }, }, { // Mogami Kai Ni+ ids: [501, 506], multiple: { "houg": 1 }, }, ], }, // 20.3cm (No.3) Twin Gun Mount "50": { count: 0, byClass: { // Furutaka Class "7": { multiple: { "houg": 1 }, synergy: { // not stackable with No.2 gun's surface radar synergy flags: [ "twin203MediumGunMountNo2Nonexist", "surfaceRadar" ], distinct: { "houg": 1, "raig": 1, "houk": 1 }, }, }, // Aoba Class "13": "7", // Takao Class "8": { multiple: { "houg": 2, "houk": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 3, "raig": 2, "houk": 2 }, }, }, // Myoukou Class "29": "8", // Mogami Class "9": [ { multiple: { "houg": 2, "houk": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 3, "raig": 2, "houk": 2 }, }, }, { multiple: { "houg": 1 }, minCount: 2, }, ], // Tone Class "31": "9", }, byShip: { // Mogami Kai Ni+ ids: [501, 506], multiple: { "houg": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 1 }, }, { flags: [ "type21AirRadar" ], single: { "houg": 1, "tyku": 3, "houk": 2 }, }, { flags: [ "type21AirRadarK2" ], single: { "houg": 2 }, }, ], }, }, // 152mm/55 Triple Rapid Fire Gun Mount "340": { count: 0, byClass: { // Duca degli Abruzzi Class "92": { multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, }, }, // 152mm/55 Triple Rapid Fire Gun Mount Kai "341": { count: 0, byClass: { // Duca degli Abruzzi Class "92": { multiple: { "houg": 2, "tyku": 1, "houk": 1 }, }, // Gotland Class "89": { multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, }, }, // 65mm/64 Single Rapid Fire Gun Mount Kai "430": { count: 0, starsDist: [], byClass: { // Conte di Cavour Class "113": [ { multiple: { "tyku": 3, "houk": 2 }, }, { minStars: 2, multiple: { "houk": 1 }, }, { minStars: 4, multiple: { "tyku": 1 }, }, { minStars: 7, multiple: { "houk": 1 }, }, { minStars: 10, multiple: { "tyku": 1 }, }, ], // V.Veneto Class "58": [ { multiple: { "tyku": 2, "houk": 1 }, }, { minStars: 2, multiple: { "houk": 1 }, }, { minStars: 4, multiple: { "tyku": 1 }, }, { minStars: 7, multiple: { "houk": 1 }, }, { minStars: 10, multiple: { "tyku": 1 }, }, ], // Zara Class "64": "58", // Aquila Class "68": "58", // L.d.S.D.d.Abruzzi Class "92": "58", }, }, // Bofors 15.2cm Twin Gun Mount Model 1930 "303": { count: 0, byClass: { // Kuma Class "4": { multiple: { "houg": 1, "tyku": 1 }, }, // Sendai Class "16": "4", // Nagara Class "20": "4", // Agano Class "41": "4", // Gotland Class "89": { multiple: { "houg": 1, "tyku": 2, "houk": 1 }, }, }, }, // 8inch Triple Gun Mount Mk.9 "356": { count: 0, byClass: { // Mogami Class "9": { multiple: { "houg": 1 }, }, // Northampton Class "95": { multiple: { "houg": 2 }, }, }, }, // 8inch Triple Gun Mount Mk.9 mod.2 "357": { count: 0, byClass: { // Mogami Class "9": { multiple: { "houg": 1 }, }, // Northampton Class "95": { multiple: { "houg": 2 }, }, }, }, // 5inch Single High-angle Gun Mount Battery "358": { count: 0, byClass: { // Northampton Class "95": { multiple: { "houg": 2, "tyku": 3, "houk": 3 }, }, // Following British and Americans: Queen Elizabeth Class "67": { multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, // Ark Royal Class "78": "67", // Nelson Class "88": "67", // Iowa Class "65": "67", // Lexington Class "69": "67", // Casablanca Class "83": "67", // Essex Class "84": "67", // Colorado Class "93": "67", // Atlanta Class "99": "67", // South Dakota Class "102": "67", // Yorktown Class "105": "67", // St. Louis Class "106": "67", // North Carolina Class "107": "67", // Town Class "108": "67", // Brooklyn Class "110": "67", // Illustrious Class "112": "67", }, }, // 6inch Twin Rapid Fire Gun Mount Mk.XXI "359": { count: 0, byClass: { // Perth Class "96": { multiple: { "houg": 2, "tyku": 2, "houk": 1 }, }, // Yuubari Class "34": [ { multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, // Yuubari Kai Ni+ { remodel: 2, multiple: { "houg": 1, "tyku": 1 }, }, ], }, }, // Bofors 15cm Twin Rapid Fire Gun Mount Mk.9 Model 1938 "360": { count: 0, byClass: { // Agano Class "41": { multiple: { "houg": 1, "tyku": 1 }, }, // Gotland Class "89": { multiple: { "houg": 2, "tyku": 1, "houk": 1 }, }, // De Ryuter Class "98": { multiple: { "houg": 2, "tyku": 2, "houk": 1 }, }, }, }, // Bofors 15cm Twin Rapid Fire Gun Mount Mk.9 Kai + Single Rapid Fire Gun Mount Mk.10 Kai Model 1938 "361": { count: 0, byClass: { // Agano Class "41": { multiple: { "houg": 1, "tyku": 1 }, }, // Gotland Class "89": { multiple: { "houg": 2, "tyku": 1, "houk": 1 }, }, // De Ryuter Class "98": { multiple: { "houg": 2, "tyku": 2, "houk": 1 }, }, }, }, // 5inch Twin Dual-purpose Gun Mount (Concentrated Deployment) "362": { count: 0, byClass: { // Atlanta Class "99": { multiple: { "houg": 1, "tyku": 3, "houk": 2 }, }, // Colorado Class "93": { multiple: { "tyku": 1, "houk": 1 }, }, // Northampton Class "95": "93", // St. Louis Class "106": "93", // Brooklyn Class "110": "93", // Agano Class "41": { multiple: { "tyku": -1, "houk": -2 }, }, // Ooyodo Class "52": "41", // De Ryuter Class "98": "41", // Katori Class "56": { multiple: { "houg": -2, "tyku": -1, "houk": -4 }, }, // Gotland Class "89": "56", // Kuma Class "4": { multiple: { "houg": -3, "tyku": -2, "houk": -6 }, }, // Nagara Class "20": "4", // Sendai Class "16": "4", // Tenryuu Class "21": { multiple: { "houg": -3, "tyku": -3, "houk": -8 }, }, // Yuubari Class "34" : "21" }, }, // GFCS Mk.37 + 5inch Twin Dual-purpose Gun Mount (Concentrated Deployment) "363": { count: 0, byClass: { // Atlanta Class "99": { multiple: { "houg": 1, "tyku": 3, "houk": 2 }, }, // Colorado Class "93": { multiple: { "tyku": 1, "houk": 1 }, }, // Northampton Class "95": "93", // St. Louis Class "106": "93", // Brooklyn Class "110": "93", // Agano Class "41": { multiple: { "tyku": -1, "houk": -2 }, }, // Ooyodo Class "52": "41", // De Ryuter Class "98": "41", // Katori Class "56": { multiple: { "houg": -2, "tyku": -1, "houk": -4 }, }, // Gotland Class "89": "56", // Kuma Class "4": { multiple: { "houg": -3, "tyku": -2, "houk": -6 }, }, // Nagara Class "20": "4", // Sendai Class "16": "4", // Tenryuu Class "21": { multiple: { "houg": -3, "tyku": -3, "houk": -8 }, }, // Yuubari Class "34" : "21" }, }, // SK Radar "278": { count: 0, byClass: { // Following American: Northampton Class "95": { single: { "tyku": 1, "houk": 3, "saku": 1 }, }, // Iowa Class "65": "95", // Lexington Class "69": "95", // Casablanca Class "83": "95", // Essex Class "84": "95", // Colorado Class "93": "95", // Atlanta Class "99": "95", // South Dakota Class "102": "95", // Yorktown Class "105": "95", // St. Louis Class "106": "95", // North Carolina Class "107": "95", // Brooklyn Class "110": "95", // Following British: Queen Elizabeth Class "67": { single: { "tyku": 1, "houk": 2 }, }, // Ark Royal Class "78": "67", // Nelson Class "88": "67", // Town Class "108": "67", // Illustrious Class "112": "67", // Perth Class "96": { single: { "tyku": 1, "houk": 1 }, }, }, }, // SK + SG Radar "279": { count: 0, byClass: { // Following American: Northampton Class "95": { single: { "houg": 2, "tyku": 2, "houk": 3, "saku": 2 }, }, // Iowa Class "65": "95", // Lexington Class "69": "95", // Casablanca Class "83": "95", // Essex Class "84": "95", // Colorado Class "93": "95", // Atlanta Class "99": "95", // South Dakota Class "102": "95", // Yorktown Class "105": "95", // St. Louis Class "106": "95", // Brooklyn Class "110": "95", // North Carolina Class "107": "95", // Following British: Queen Elizabeth Class "67": { single: { "houg": 1, "tyku": 1, "houk": 2, "saku": 1 }, }, // Ark Royal Class "78": "67", // Nelson Class "88": "67", // Town Class "108": "67", // Illustrious Class "112": "67", // Perth Class "96": { single: { "houg": 1, "tyku": 1, "houk": 1 }, }, }, }, // 61cm Quadruple (Oxygen) Torpedo Mount "15": { count: 0, byClass: { // Kagerou Class K2 "30": { remodel: 2, excludes: [556, 557, 558, 559], multiple: { "raig": 2 }, countCap: 2, }, }, byShip: { // All remodels of Matsu Class Take origins: [642], single: { "raig": 5, "houk": 1 }, }, }, // 61cm Quintuple (Oxygen) Torpedo Mount "58": { count: 0, byClass: { // CLT types in Kuma Class "4": { stypes: [4], multiple: { "raig": 1 }, }, // Shimakaze Class "22": { multiple: { "raig": 1 }, }, // Akizuki Class "54": "22", }, }, // 53cm Twin Torpedo Mount "174": { count: 0, byClass: { // Kamikaze Class "66": { multiple: { "raig": 1, "houk": 2 }, }, // Kongou Class Kai Ni C "6": { remodel: 3, multiple: { "raig": 6, "houk": 3 }, }, // Yuubari Kai Ni+ "34": { remodel: 2, multiple: { "houg": 2, "raig": 4, "houk": 4 }, }, }, byShip: [ { // Yura Kai Ni ids: [488], multiple: { "houg": 2, "raig": 4, "houk": 4 }, }, ], }, // 53cm Bow (Oxygen) Torpedo Mount "67": { count: 0, byShip: { // -5 tp on other ship types except SS, SSV excludeStypes: [13, 14], multiple: { "raig": -5 }, }, }, // Prototype 61cm Sextuple (Oxygen) Torpedo Mount "179": { count: 0, byClass: { // Akizuki Class "54": { multiple: { "raig": 1 }, countCap: 2, }, }, }, // 533mm Quintuple Torpedo Mount (Initial Model) "314": { count: 0, byClass: { // John C. Butler Class "87": { multiple: { "houg": 1, "raig": 3 }, }, // Fletcher Class "91": "87", }, }, // 533mm Quintuple Torpedo Mount (Late Model) "376": { count: 0, byClass: { // Following Americans: John C. Butler Class "87": { multiple: { "houg": 2, "raig": 4 }, }, // Fletcher Class "91": "87", // Northampton Class "95": "87", // Atlanta Class "99": "87", // St. Louis Class "106": "87", // Brooklyn Class "110": "87", // Jervis Class "82": { multiple: { "houg": 1, "raig": 2 }, }, // Town Class "108": "82", // Perth Class "96": { multiple: { "houg": 1, "raig": 1 }, }, }, }, // 61cm Triple (Oxygen) Torpedo Mount Late Model "285": { count: 0, starsDist: [], byClass: { // Ayanami Class K2: Ayanami K2, Ushio K2, Akebono K2 "1": [ { remodel: 2, multiple: { "raig": 2, "houk": 1 }, countCap: 2, }, { // +1 fp if stars +max minStars: 10, remodel: 2, multiple: { "houg": 1 }, countCap: 2, }, ], // Akatsuki Class K2: Akatsuki K2, Hibiki K2 (Bep) "5": "1", // Hatsuharu Class K2: Hatsuharu K2, Hatsushimo K2 "10": "1", // Fubuki Class K2: Fubuki K2, Murakumo K2 "12": "1", }, }, // 61cm Quadruple (Oxygen) Torpedo Mount Late Model "286": { count: 0, starsDist: [], byClass: { // Asashio Class K2 "18": [ { remodel: 2, multiple: { "raig": 2, "houk": 1 }, countCap: 2, }, { // +1 fp if stars +max minStars: 10, remodel: 2, multiple: { "houg": 1 }, countCap: 2, }, ], // Shiratsuyu Class K2 "23": "18", // Yuugumo Class K2 "38": "18", // Kagerou Class K2 // except Isokaze / Hamakaze B Kai, Urakaze / Tanikaze D Kai "30": [ { remodel: 2, excludes: [556, 557, 558, 559], multiple: { "raig": 2, "houk": 1 }, countCap: 2, }, { // +1 tp if stars >= +5 minStars: 5, remodel: 2, excludes: [556, 557, 558, 559], multiple: { "raig": 1 }, countCap: 2, }, { // +1 fp if stars +max minStars: 10, remodel: 2, excludes: [556, 557, 558, 559], multiple: { "houg": 1 }, countCap: 2, }, ], }, byShip: [ { // All remodels of Matsu Class Take origins: [642], single: { "raig": 7, "houk": 2 }, }, { // extra +2 tp if stars >= +7 origins: [642], minStars: 7, single: { "raig": 2 }, }, { // extra +2 tp if stars +max origins: [642], minStars: 10, single: { "raig": 2 }, }, { // Noshiro Kai Ni, Yahagi Kai Ni/K2B ids: [662, 663, 668], multiple: { "raig": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "raig": 3, "houk": 2 }, }, }, ], }, // 533mm Triple Torpedo Mount "283": { count: 0, byClass: { // Tashkent Class "81": { multiple: { "houg": 1, "raig": 3, "souk": 1 }, }, }, byShip: { // Hibiki K2 (Bep) ids: [147], multiple: { "houg": 1, "raig": 3, "souk": 1 }, }, }, // 533mm Triple Torpedo Mount (Model 53-39) "400": { count: 0, byClass: { // Tashkent Class "81": { multiple: { "houg": 1, "raig": 5, "souk": 1, "houk": 2 }, synergy: { flags: [ "ru130mmB13SmallGunMount" ], single: { "houg": 2 }, }, }, }, byShip:{ // Hibiki K2 (Bep) ids: [147], multiple: { "houg": 1, "raig": 5, "souk": 1, "houk": 2 }, synergy: { flags: [ "ru130mmB13SmallGunMount" ], single: { "houg": 2 }, }, }, }, // Late Model 53cm Bow Torpedo Mount (8 tubes) "383": { count: 0, byClass: { // I-58 Class "36": { multiple: { "raig": 1 }, }, // I-400 Class "44": { multiple: { "raig": 2 }, }, // I-47 Class "103": { multiple: { "raig": 3 }, }, }, byShip: { // I-47 Kai ids: [607], multiple: { "raig": 1 }, }, }, // Late Model Submarine Radar & Passive Radiolocator "384": { count: 0, byClass: { // I-58 Class "36": { multiple: { "houk": 2 }, }, // I-400 Class "44": { multiple: { "houk": 3 }, }, // I-47 Class "103": { multiple: { "houk": 3 }, }, }, byShip: [ { // I-47 Kai ids: [607], multiple: { "houk": 1 }, }, { // Any ship who can equip it will get synergy +3 tp, +2 ev stypes: [13, 14], synergy: { flags: [ "submarineTorpedoLateModel" ], single: { "raig": 3, "houk": 2 }, }, }, ], }, // Type D Kai Kouhyouteki "364": { count: 0, byShip: [ { // Yuubari K2T ids: [623], multiple: { "houg": 1, "raig": 4, "houk": -2 }, }, { // Kitakami K2 ids: [119], multiple: { "raig": 2, "houk": -2 }, }, { // Ooi K2, Nisshin A, Kuma K2D, Mogami K2T, Yahagi K2B ids: [118, 586, 657, 506, 668], multiple: { "raig": 1, "houk": -2 }, }, { // All other ships who can equip it stypes: [3, 4, 13, 14, 16], excludes: [118, 119, 506, 586, 623, 657, 668], multiple: { "houg": -1, "houk": -7 }, }, ], }, // 12cm Single Gun Mount Kai Ni "293": { count: 0, byClass: { // Mutsuki Class "28": { multiple: { "houg": 2, "tyku": 1, "houk": 3 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 1, "houk": 3 }, }, { flags: [ "kamikazeTwinTorpedo" ], byCount: { gear: "kamikazeTwinTorpedo", "1": { "houg": 2, "raig": 4 }, "2": { "houg": 3, "raig": 7 }, "3": { "houg": 3, "raig": 7 }, }, }, ], }, // Kamikaze Class "66": "28", // Shimushu Class "74": { multiple: { "houg": 1, "tyku": 1, "houk": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "tais": 1, "houk": 3 }, }, }, // Etorofu Class "77": "74", }, }, // 12.7cm Single Gun Mount "78": { count: 0, starsDist: [], byClass: { // Z1 Class "48": [ { multiple: { "houg": 1, "houk": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 2, "houk": 2 }, }, }, { minStars: 7, multiple: { "houg": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], }, }, // 10cm Twin High-angle Gun Mount "3": { count: 0, byClass: { // Akizuki Class "54": { multiple: { "houg": 1, "tyku": 2, "houk": 1 }, }, }, }, // 10cm Twin High-angle Gun Mount + Anti-Aircraft Fire Director "122": { count: 0, starsDist: [], byClass: { // Akizuki Class "54": { multiple: { "houg": 1, "tyku": 2, "houk": 1 }, }, }, byShip: [ { // Yukikaze Kai Ni ids: [656], minStars: 4, multiple: { "houg": 5, "tyku": 3, "houk": 2 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 4, "houk": 3 }, }, { flags: [ "airRadar" ], single: { "tyku": 4, "houk": 3 }, }, ], }, ] }, // Locally Modified 12.7cm Twin High-angle Gun Mount "397": { count: 0, starsDist: [], byShip: [ { // Tan Yang ids: [651], multiple: { "houg": 5, "tyku": 2, "houk": 1 }, }, { // Tan Yang ids: [651], minStars: 4, multiple: { "houg": 4, "houk": 1 }, }, { // Yukikaze Kai Ni ids: [656], multiple: { "houg": 3, "tyku": 1, "houk": 1 }, }, { // Tan Yang/Yukikaze Kai Ni ids: [651, 656], synergy: { flags: [ "surfaceRadar" ], single: { "houg": 3, "houk": 3 }, }, }, ] }, // Locally Modified 10cm Twin High-angle Gun Mount "398": { count: 0, starsDist: [], byShip: [ { // Tan Yang ids: [651], multiple: { "houg": 4, "tyku": 4, "houk": 2 }, }, { // Tan Yang ids: [651], minStars: 4, multiple: { "houg": 3, "houk": 2 }, }, { // Yukikaze Kai Ni ids: [656], multiple: { "houg": 3, "tyku": 2, "houk": 2 }, }, { // Yukikaze Kai Ni ids: [656], minStars: 4, multiple: { "houg": 2, "houk": 1 }, }, { // Tan Yang/Yukikaze Kai Ni ids: [651, 656], synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 3, "houk": 3 }, }, { flags: [ "airRadar" ], single: { "tyku": 3, "houk": 3 }, }, ], }, ] }, // 12.7cm Single High-angle Gun Mount (Late Model) "229": { count: 0, starsDist: [], byClass: { // Mutsuki Class "28": { minStars: 7, multiple: { "houg": 1, "tyku": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 3 }, }, }, // Kamikaze Class "66": "28", // Yuubari Kai Ni+ "34": { remodel: 2, multiple: { "houg": 1, "tyku": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 1 }, }, { flags: [ "airRadar" ], single: { "tyku": 2, "houk": 2 }, }, ], }, }, byShip: [ { // All DE stypes: [1], minStars: 7, multiple: { "houg": 1, "tyku": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 4 }, }, }, { // All remodels of: Naka, Kinu origins: [56, 113], minStars: 7, multiple: { "houg": 2 }, }, { // All remodels of: Yura origins: [23], minStars: 7, multiple: { "houg": 2, "tyku": 1 }, }, { // Yura Kai, Naka Kai, Kinu Kai ids: [220, 224, 289], minStars: 7, multiple: { "tyku": 1 }, }, { // Naka Kai Ni, Kinu Kai Ni, Yura Kai Ni ids: [160, 487, 488], minStars: 7, multiple: { "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 3, "houk": 2 }, }, }, { // Yukikaze Kai Ni ids: [656], multiple: { "houg": 2, "tyku": 3, "tais": 2 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "tyku": 3, "houk": 2 }, }, ], }, ], }, // 12.7cm Single High-angle Gun Mount Kai Ni "379": { count: 0, byClass: { // Mutsuki Class "28": { multiple: { "houg": 1, "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 3 }, }, }, // Kamikaze Class "66": "28", // Tenyuu Class "21": { multiple: { "houg": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 3 }, }, }, // Yuubari Class "34": { multiple: { "houg": 1, "tais": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 3 }, }, }, // Matsu Class "101": [ { single: { "houg": 2, "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 4, "houk": 3 }, }, }, // Make another object in order to compatible with mstship's `.single || .multiple` handling { multiple: { "houg": 1, "tyku": 2 }, }, ] }, byShip: [ { // All DE stypes: [1], multiple: { "houg": 1, "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 4 }, }, }, { // All AV/CT stypes: [16, 21], multiple: { "houg": 1, "tyku": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 2 }, }, }, { // Synergy only for all CL/CLT stypes: [3, 4], synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 2 }, }, }, { // All remodels of: Isuzu, Yura, Naka, Kinu origins: [22, 23, 56, 113], multiple: { "houg": 2, "tais": 1 }, }, { // All remodels of: Ooi, Kitakami origins: [24, 25], multiple: { "houg": 2, "tyku": 2 }, }, { // Yura base, Isuzu base,Kai, Naka base,Kai, Kinu base,Kai extra +2 aa ids: [23, 22, 219, 56, 224, 113, 289], multiple: { "tyku": 2 }, }, { // Yura Kai, Isuzu K2, Naka K2, Kinu K2 extra +3 aa ids: [220, 141, 160, 487], multiple: { "tyku": 3 }, }, { // Yura Kai Ni extra +4 aa and synergy ids: [488], multiple: { "tyku": 4 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 2 }, }, }, { // Ooi K2,Kitakami K2, Isuzu K2, Naka K2, Kinu K2 extra synergy ids: [118, 119, 141, 160, 487], synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 1 }, }, }, { // Yura K2, Isuzu K2, Naka K2, Kinu K2 extra +1 asw ids: [488, 141, 160, 487], multiple: { "tais": 1 }, }, { // Tenryuu K2, Tatsuta K2, Yuubari K2D extra +2 asw ids: [477, 478, 624], multiple: { "tais": 2 }, }, { // Tenryuu K2, Tatsuta K2, Yuubari K2,K2D extra +2 aa ids: [477, 478, 622, 624], multiple: { "tyku": 2 }, }, { // Kiso K2, Tama K2, Kuma K2,K2D ids: [146, 547, 652, 657], single: { "houg": 2, "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 1 }, }, }, { // Tan Yang ids: [651], multiple: { "houg": 3, "tyku": 3 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 2 }, }, }, { // Yukikaze K2 ids: [656], multiple: { "houg": 3, "tyku": 3, "tais": 2, "houk": 3 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "tyku": 3, "houk": 2 }, }, ], }, ], }, // 12.7cm Twin High-angle Gun Mount Kai Ni "380": { count: 0, byClass: { // Tenyuu Class "21": { multiple: { "houg": 1 }, }, // Yuubari Class "34": { multiple: { "houg": 1, "tais": 1 }, }, // Matsu Class "101": [ { single: { "houg": 2, "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 4, "houk": 3 }, }, }, // Make another object in order to compatible with mstship's `.single || .multiple` handling { multiple: { "houg": 1, "tyku": 2 }, }, ], }, byShip: [ { // All AV/CT stypes: [16, 21], multiple: { "houg": 1, "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 1 }, }, }, { // Synergy only for all CL/CLT stypes: [3, 4], synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 1 }, }, }, { // All remodels of: Isuzu, Yura, Naka, Kinu origins: [22, 23, 56, 113], multiple: { "houg": 2, "tais": 1 }, }, { // All remodels of: Ooi, Kitakami origins: [24, 25], multiple: { "houg": 3, "tyku": 2 }, }, { // Yura base, Isuzu base,Kai, Naka base,Kai, Kinu base,Kai extra +2 aa ids: [23, 22, 219, 56, 224, 113, 289], multiple: { "tyku": 2 }, }, { // Yura Kai, Isuzu K2, Naka K2, Kinu K2 extra +3 aa ids: [220, 141, 160, 487], multiple: { "tyku": 3 }, }, { // Yura Kai Ni extra +4 aa ids: [488], multiple: { "tyku": 4 }, }, { // Ooi K2,Kitakami K2, Isuzu K2, Naka K2, Kinu K2, Yura K2, Tan Yang, Yukikaze K2 extra synergy ids: [118, 119, 141, 160, 487, 488, 651, 656], synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 2 }, }, }, { // Yura K2, Isuzu K2, Naka K2, Kinu K2 extra +1 asw ids: [488, 141, 160, 487], multiple: { "tais": 1 }, }, { // Tenryuu K2, Tatsuta K2, Yuubari K2D extra +2 asw ids: [477, 478, 624], multiple: { "tais": 2 }, }, { // Tenryuu K2, Tatsuta K2, Yuubari K2,K2D extra +2 aa ids: [477, 478, 622, 624], multiple: { "tyku": 2 }, }, { // Kuma K2,K2D ids: [652, 657], multiple: { "houg": 3 }, }, { // Kiso K2, Tama K2 ids: [146, 547], single: { "houg": 2 }, }, { // Kiso K2, Tama K2, Kuma K2,K2D ids: [146, 547, 652, 657], single: { "tyku": 2 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 3 }, }, }, { // Tan Yang/Yukikaze K2 ids: [651, 656], multiple: { "houg": 3, "tyku": 3 }, }, { // Ushio/Akebono K2 ids: [407, 665], multiple: { "houg": 2, "tyku": 2 }, }, { // Ushio/Akebono K2 ids: [407, 665], single: { "houg": 1, "tyku": 1, "houk": 2 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 1 }, }, { flags: [ "aaMachineGun" ], single: { "houg": 1, "tyku": 2, "houk": 1 }, }, ], }, ], }, // 12cm Single High-angle Gun Mount Model E "382": { count: 0, byClass: { // Mutsuki Class "28": { multiple: { "tyku": 2, "houk": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "tyku": 2, "houk": 2 }, }, ], }, // Kamikaze Class "66": "28", // Matsu Class "101": "28", }, byShip: [ { // All DE stypes: [1], multiple: { "tais": 1, "tyku": 2, "houk": 2 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 3 }, }, { flags: [ "airRadar" ], single: { "tyku": 2, "houk": 3 }, }, ], }, { // All remodels of: Yura, Naka, Kinu origins: [23, 56, 113], multiple: { "tyku": 1 }, }, { // Yura Kai, Naka Kai, Kinu Kai ids: [220, 224, 289], multiple: { "houk": 1 }, }, { // Yura Kai Ni, Naka Kai Ni, Kinu Kai Ni ids: [488, 160, 487], multiple: { "houk": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 1, "houk": 1 }, }, { flags: [ "airRadar" ], single: { "tyku": 2, "houk": 2 }, }, ], }, { // Yukikaze Kai Ni ids: [656], multiple: { "tyku": 3, "houk": 2 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "tyku": 3, "houk": 2 }, }, ], }, ], }, // 120mm Twin Gun Mount "147": { count: 0, byClass: { // Maestrale Class "61": { multiple: { "houg": 1, "houk": 1 }, }, }, }, // 120mm/50 Twin Gun Mount mod.1936 "393": { count: 0, byClass: { // Maestrale Class "61": [ { multiple: { "houg": 1, "houk": 1 }, }, { multiple: { "houg": 1, "tyku": 1 }, }, ], }, }, // 120mm/50 Twin Gun Mount Kai A.mod.1937 "394": { count: 0, byClass: { // Maestrale Class "61": [ { multiple: { "houg": 1, "houk": 1 }, }, { multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, ], }, byShip: { // extra +1 ev for Grecale all remodels origins: [614], multiple: { "houk": 1 }, }, }, // 130mm B-13 Twin Gun Mount "282": { count: 0, byClass: { // Tashkent Class "81": { multiple: { "houg": 2, "souk": 1 }, }, // Yuubari Class "34": "81", }, byShip: { // Hibiki K2 (Bep) ids: [147], multiple: { "houg": 2, "souk": 1 }, }, }, // 12.7cm Twin Gun Mount Model A "297": { count: 0, byClass: { // Fubuki Class "12": { multiple: { "houk": 2 }, }, // Ayanami Class "1": { multiple: { "houk": 1 }, }, // Akatsuki Class "5": "1", }, }, // 12.7cm Twin Gun Mount Model A Kai Ni "294": { count: 0, byClass: { // Ayanami Class "1": { multiple: { "houg": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 3, "raig": 1, "houk": 2 }, }, { flags: [ "tripleTorpedo" ], byCount: { gear: "tripleTorpedo", "1": { "houg": 1, "raig": 3 }, "2": { "houg": 2, "raig": 5 }, "3": { "houg": 2, "raig": 5 }, }, }, { flags: [ "tripleTorpedoLateModel" ], single: { "raig": 1 }, }, ], }, // Akatsuki Class "5": "1", // Fubuki Class "12": "1", }, }, // 12.7cm Twin Gun Mount Model B Kai Ni "63": { count: 0, byClass: { // Ayanami Class "1": { multiple: { "tyku": 1 }, }, // Akatsuki Class "5": "1", // Hatsuharu Class "10": "1", }, byShip: [ { // All remodels of Yuudachi origins: [45], multiple: { "houg": 1, "tyku": 1, "houk": 2 }, }, { // Yuudachi K2 ids: [144], multiple: { "raig": 1 }, }, { // Shigure K2, Shikinami K2 ids: [145, 627], multiple: { "houg": 1 }, }, { // Shiratsuyu Kai+, Murasame Kai+ ids: [242, 497, 244, 498], multiple: { "houk": 1 }, }, { // Kawakaze K2 ids: [469], multiple: { "houk": 2 }, }, ], }, // 12.7cm Twin Gun Mount Model C Kai Ni "266": { count: 0, byClass: { // Asashio Class "18": { multiple: { "houg": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "raig": 3, "houk": 1 }, }, }, // Shiratsuyu Class "23": "18", // Kagerou Class "30": [ { multiple: { "houg": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 3, "houk": 1 }, }, }, { remodel: 2, excludes: [556, 557, 558, 559, 648, 651], // Kagerou Class K2 total +2 fp til 2 guns multiple: { "houg": 1 }, countCap: 2, }, { remodel: 2, excludes: [556, 557, 558, 559, 648, 651], // Kagerou Class K2 total +5 instead of +4 if guns = 2 // https://wikiwiki.jp/kancolle/%E9%99%BD%E7%82%8E%E6%94%B9%E4%BA%8C single: { "houg": 1 }, minCount: 2, }, ], }, byShip: { // Yukikaze, Shigure, Isokaze, extra +1 ev origins: [20, 43, 167], multiple: { "houk": 1 }, }, }, // 12.7cm Twin Gun Mount Model D Kai Ni // https://wikiwiki.jp/kancolle/12.7cm%E9%80%A3%E8%A3%85%E7%A0%B2D%E5%9E%8B%E6%94%B9%E4%BA%8C "267": { count: 0, byClass: { // Shimakaze Class "22": [ { multiple: { "houg": 2, "houk": 1 }, }, { // Shimakaze Kai, total +3 fp, +3 tp, +3 ev remodel: 1, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "raig": 3, "houk": 2 }, }, }, ], // Kagerou Class "30": { multiple: { "houg": 1, "houk": 1 }, }, // Yuugumo Class "38": [ { multiple: { "houg": 2, "houk": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 3, "houk": 1 }, }, }, // A code typo suspected in both sides, which supposed to give non-K2 ships +2 tp, instead of giving all, // see https://github.com/Tibowl/KCBugTracker/issues/42 // here should follow server-side's value, so +2 tp has been added to previous line, and Akigumo K2's synergy /* { // remodels except all of Yuugumo Class K2 excludes: [542, 543, 563, 564, 569, 578], synergy: { flags: [ "surfaceRadar" ], single: { "raig": 2 }, }, }, */ { // Yuugumo Class K2 remodel: 2, multiple: { "houg": 1 }, synergy: { flags: [ "surfaceRadar" ], single: { "houg": 1, "raig": 3, "houk": 2 }, }, }, ], }, byShip: [ { // Kagerou K2, Shiranui K2, Kuroshio K2, Yukikaze K2, Oyashio K2 ids: [566, 567, 568, 656, 670], single: { "houg": 1 }, }, { // Akigumo Kai Ni ids: [648], multiple: { "houg": 2 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 3, "raig": 6, "houk": 3 }, }, { flags: [ "skilledLookouts" ], single: { "houg": 2, "tyku": 2, "houk": 3 }, }, { flags: [ "searchlightSmall" ], single: { "houg": 3, "houk": -3 }, }, ], }, { // Takanami K2 ids: [649], multiple: { "houg": 1 }, }, ] }, // 12.7cm Twin Gun Mount Model D Kai 3 "366": { count: 0, byClass: { // Shimakaze Class "22": [ { multiple: { "houg": 2, "houk": 1 }, }, { // Shimakaze Kai remodel: 1, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 4, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "houg": 1, "tyku": 5, "houk": 2 }, }, ], }, { // Shimakaze Kai, one-time +3 AA remodel: 1, single: { "tyku": 3 }, }, { // Shimakaze Kai, one-time +5 AA for 2 guns remodel: 1, single: { "tyku": 2 }, minCount: 2, }, ], // Kagerou Class "30": { multiple: { "houg": 1, "houk": 1 }, }, // Yuugumo Class "38": [ { multiple: { "houg": 2, "houk": 1 }, }, { // Yuugumo Class K2 remodel: 2, multiple: { "houg": 1 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 4, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "houg": 1, "tyku": 5, "houk": 2 }, }, ], }, { // Yuugumo Class K2, one-time +3 AA remodel: 2, single: { "tyku": 3 }, }, { // Yuugumo Class K2, one-time +5 AA for 2 guns remodel: 2, single: { "tyku": 2 }, minCount: 2, }, ], }, byShip: [ { // Kagerou K2, Shiranui K2, Kuroshio K2, Yukikaze K2, Oyashio K2 +1 fp, +2 aa for one or two gun(s) ids: [566, 567, 568, 656, 670], multiple: { "houg": 1, "tyku": 2 }, countCap: 2, }, { // Okinami Kai Ni, Akigumo Kai Ni ids: [569, 648], single: { "houg": 1, "tyku": 2 }, }, { // Akigumo Kai Ni, one-time +3 AA ids: [648], single: { "tyku": 3 }, }, { // Akigumo Kai Ni, one-time +5 AA for 2 guns ids: [648], single: { "tyku": 2 }, minCount: 2, }, { // Akigumo Kai Ni ids: [648], multiple: { "houg": 2 }, synergy: [ { flags: [ "surfaceRadar" ], single: { "houg": 2, "raig": 4, "houk": 2 }, }, { flags: [ "airRadar" ], single: { "houg": 1, "tyku": 5, "houk": 2 }, }, { flags: [ "twin127SmallGunMountModelDK2Nonexist", "skilledLookouts" ], single: { "houg": 2, "tyku": 2, "houk": 3 }, }, { flags: [ "twin127SmallGunMountModelDK2Nonexist", "searchlightSmall" ], single: { "houg": 3, "houk": -3 }, }, ], }, { // Takanami K2 ids: [649], multiple: { "houg": 1 }, }, ], }, // 12.7cm Twin Gun Mount Model A Kai 3 + AAFD "295": { count: 0, byClass: { // Ayanami Class "1": { multiple: { "houg": 2, "tyku": 2 }, synergy: [ { flags: [ "airRadar" ], single: { "tyku": 6 }, }, { flags: [ "surfaceRadar" ], single: { "houg": 3, "raig": 1, "houk": 2 }, }, { flags: [ "tripleTorpedo" ], byCount: { gear: "tripleTorpedo", "1": { "houg": 1, "raig": 3 }, "2": { "houg": 2, "raig": 5 }, "3": { "houg": 2, "raig": 5 }, }, }, { flags: [ "tripleTorpedoLateModel" ], single: { "raig": 1 }, }, ], }, // Akatsuki Class "5": "1", // Fubuki Class "12": "1", }, }, // 12.7cm Twin Gun Mount Model B Kai 4 + AAFD "296": { count: 0, byClass: { // Ayanami Class "1": { multiple: { "houg": 1 }, synergy: [ { flags: [ "airRadar" ], single: { "tyku": 5 }, }, { flags: [ "surfaceRadar" ], single: { "houg": 1, "raig": 2, "houk": 2 }, }, { flags: [ "tripleTorpedoOxygenLateModel" ], single: { "houg": 1, "raig": 3 }, }, ], }, // Akatsuki Class "5": "1", // Shiratsuyu Class "23": { multiple: { "houg": 1, "houk": 1 }, synergy: [ { flags: [ "airRadar" ], single: { "tyku": 6 }, }, { flags: [ "surfaceRadar" ], single: { "houg": 1, "raig": 3, "houk": 2 }, }, { flags: [ "quadrupleTorpedoOxygenLateModel" ], single: { "houg": 1, "raig": 3 }, }, ], }, // Hatsuharu Class "10": { multiple: { "houg": 1, "houk": 1 }, synergy: [ { flags: [ "airRadar" ], single: { "tyku": 5 }, }, { flags: [ "surfaceRadar" ], single: { "houg": 1, "raig": 2, "houk": 2 }, }, { flags: [ "tripleTorpedoOxygenLateModel" ], single: { "houg": 1, "raig": 3 }, }, ], }, }, byShip: [ { // Shiratsuyu K2 ids: [497], multiple: { "houg": 1, "houk": 1 }, }, { // Yuudachi K2 ids: [144], multiple: { "houg": 1, "raig": 1 }, }, { // Shigure K2 ids: [145], multiple: { "houg": 1, "tyku": 1 }, }, { // Murasame K2 ids: [498], multiple: { "tyku": 1, "houk": 1 }, }, { // Kawakaze/Umikaze K2, Shiratsuyu/Murasame Kai, Yamakaze K2+ ids: [469, 587, 242, 244, 588, 667], multiple: { "houk": 1 }, }, { // Shikinami K2 ids: [627], multiple: { "houg": 2, "raig": 1}, }, ], }, // 5inch Single Gun Mount Mk.30 Kai "313": { count: 0, byClass: { // John C. Butler Class "87": { multiple: { "houg": 2, "tyku": 2, "souk": 1, "houk": 1 }, }, // Fletcher Class "91": "87", }, byShip: { // Tan Yang/Yukikaze K2 ids: [651, 656], multiple: { "houg": 2, "tyku": 2, "souk": 1, "houk": 1 }, }, }, // 5inch Single Gun Mount Mk.30 Kai + GFCS Mk.37 "308": { count: 0, byClass: { // John C. Butler Class, totally +2 fp from DD stype "87": { multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, // Fletcher Class "91": "87", // Atlanta Class "99": "87", // St. Louis Class "106": "87", // Brooklyn Class "110": "87", }, byShip: [ { // All DE stypes: [1], multiple: { "tyku": 1, "houk": 1 }, }, { // All DD stypes: [2], multiple: { "houg": 1 }, }, { // Tan Yang/Yukikaze K2 ids: [651, 656], multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, ], }, // 8cm High-angle Gun "66": { count: 0, byShip: [ { // Noshiro K2, Yahagi K2+ ids: [662, 663, 668], multiple: { "tyku": 2, "houk": 1 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 1, "houk": 2 }, }, }, { // Mogami K2+ ids: [501, 506], multiple: { "houg": 1, "tyku": 2, "houk": 2 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 1, "houk": 2 }, }, }, ], }, // 8cm High-angle Gun Kai + Extra Machine Guns "220": { count: 0, byShip: [ { // Noshiro K2, Yahagi K2+, Mogami K2+ ids: [662, 663, 668, 501, 506], multiple: { "houg": 1, "tyku": 3, "houk": 2 }, synergy: { flags: [ "airRadar" ], single: { "tyku": 3, "houk": 3 }, }, }, { // Noshiro K2, Yahagi K2+ ids: [662, 663, 668], multiple: { "tyku": 2, "houk": 1 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 1, "houk": 2 }, }, }, { // Mogami K2+ ids: [501, 506], multiple: { "houg": 1, "tyku": 2, "houk": 2 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 1, "houk": 2 }, }, }, ] }, // Type 21 Air Radar "30": { count: 0, byClass: { // Akizuki Class "54": { single: { "tyku": 3, "houk": 2, "saku": 2 }, }, }, byShip: { // Mogami Kai+ ids: [73, 501, 506], single: { "tyku": 3, "houk": 2, "saku": 2 }, }, }, // Type 21 Air Radar Kai Ni "410": { count: 0, byClass: { // Akizuki Class "54": { single: { "houg": 1, "souk": 1, "tyku": 5, "houk": 4, "saku": 2 }, }, }, byShip: { // Mogami Kai+ ids: [73, 501, 506], single: { "houg": 1, "souk": 1, "tyku": 5, "houk": 4, "saku": 2 }, }, }, // Type 42 Air Radar Kai Ni "411": { count: 0, starsDist: [], byShip: [ { // All DD stypes: [2], multiple: { "houk": -9 }, }, { // All CL/CLT stypes: [3, 4], multiple: { "houk": -7 }, }, { // All CT stypes: [21], multiple: { "houk": -6 }, }, { // All CA/CAV stypes: [5, 6], multiple: { "houk": -5 }, }, { // stars >= +4 on members below ids: [151, 411, 412, 541, 573, 553, 554], minStars: 4, single: { "houg": 1, "tyku": 1 }, }, { // stars +10 on members below ids: [151, 411, 412, 541, 573, 553, 554], minStars: 10, single: { "houg": 1, "tyku": 1 }, }, { // Haurna K2, Fusou K2, Yamashiro K2 ids: [151, 411, 412], single: { "houg": 3, "tyku": 4 }, }, { // Nagato K2, Mutsu K2, Ise K2, Hyuuga K2 ids: [541, 573, 553, 554], single: { "houg": 2, "tyku": 2 }, }, ], }, // GFCS Mk.37 "307": { count: 0, byClass: { // Following Americans: Iowa Class "65": { multiple: { "houg": 1, "tyku": 1, "houk": 1 }, }, // Lexington Class "69": "65", // Casablanca Class "83": "65", // Essex Class "84": "65", // John C. Butler Class "87": "65", // Fletcher Class "91": "65", // Colorado Class "93": "65", // Northampton Class "95": "65", // Atlanta Class "99": "65", // South Dakota Class "102": "65", // Yorktown Class "105": "65", // St. Louis Class "106": "65", // North Carolina Class "107": "65", // Brooklyn Class "110": "65", }, }, // SG Radar (Initial Model) "315": { count: 0, byClass: { // Following Americans: Iowa Class "65": { multiple: { "houg": 2, "houk": 3, "saku": 4 }, }, // Lexington Class "69": "65", // Casablanca Class "83": "65", // Essex Class "84": "65", // Colorado Class "93": "65", // Northampton Class "95": "65", // Atlanta Class "99": "65", // South Dakota Class "102": "65", // Yorktown Class "105": "65", // St. Louis Class "106": "65", // North Carolina Class "107": "65", // Brooklyn Class "110": "65", // John C. Butler Class, range from medium to long "87": [ { multiple: { "houg": 3, "houk": 3, "saku": 4 }, }, { single: { "leng": 1 }, }, ], // Fletcher Class "91": "87", }, byShip: { // Tan Yang/Yukikaze K2 ids: [651, 656], single: { "houg": 2, "houk": 2, "saku": 3, "leng": 1 }, }, }, // Type 13 Air Radar Kai "106": { count: 0, byShip: [ { // Ushio K2, Shigure K2, Hatsushimo K2, Haruna K2, Nagato K2 ids: [407, 145, 419, 151, 541], multiple: { "houg": 1, "tyku": 2, "houk": 3, "souk": 1 }, }, { // All remodels of: Isokaze, Hamakaze, Asashimo, Kasumi, Yukikaze, Suzutsuki, Yahagi origins: [167, 170, 425, 49, 20, 532, 139], multiple: { "tyku": 2, "houk": 2, "souk": 1 }, }, { // All remodels of: Hibiki, Ooyodo, Kashima origins: [35, 183, 465], multiple: { "tyku": 1, "houk": 3, "souk": 1 }, }, { // Yahagi K2+ ids: [663, 668], single: { "houg": 1, "tyku": 1, "houk": 1, "souk": 1 }, }, { // Yahagi K2B ids: [668], single: { "tyku": 1, "houk": 1 }, }, ], }, // 25mm Twin Autocannon Mount "39": { count: 0, byClass: { // Katori Class "56": { multiple: { "houg": 1, "tyku": 2, "houk": 2 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 2, "houk": 2 }, }, }, }, byShip: [ { // Noshiro Kai Ni, Yahagi Kai Ni ids: [662, 663], multiple: { "tyku": 2, "houk": 1 }, }, { // Yahagi Kai Ni B ids: [668], multiple: { "tyku": 3, "houk": 2 }, }, ], }, // 25mm Triple Autocannon Mount "40": { count: 0, byClass: { // Katori Class "56": { multiple: { "houg": 1, "tyku": 2, "houk": 2 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 2, "houk": 2 }, }, }, }, byShip: [ { // Noshiro Kai Ni, Yahagi Kai Ni ids: [662, 663], multiple: { "tyku": 2, "houk": 1 }, }, { // Yahagi Kai Ni B ids: [668], multiple: { "tyku": 3, "houk": 2 }, }, ], }, // 25mm Single Autocannon Mount "49": { count: 0, byClass: { // Katori Class "56": { multiple: { "houg": 1, "tyku": 2, "houk": 2 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 2, "houk": 2 }, }, }, }, byShip: [ { // Noshiro Kai Ni, Yahagi Kai Ni ids: [662, 663], multiple: { "tyku": 2, "houk": 1 }, }, { // Yahagi Kai Ni B ids: [668], multiple: { "tyku": 3, "houk": 2 }, }, ], }, // 25mm Triple Autocannon Mount (Concentrated Deployment) "131": { count: 0, byClass: { // Katori Class "56": { multiple: { "houg": 1, "tyku": 2, "houk": 2 }, synergy: { flags: [ "airRadar" ], distinct: { "tyku": 2, "houk": 2 }, }, }, }, byShip: [ { // Noshiro Kai Ni, Yahagi Kai Ni ids: [662, 663], multiple: { "tyku": 2, "houk": 1 }, }, { // Yahagi Kai Ni B ids: [668], multiple: { "tyku": 3, "houk": 2 }, }, ], }, // Type 94 Anti-Aircraft Fire Director "121": { count: 0, byClass: { // Akizuki Class "54": { single: { "tyku": 4, "houk": 2 }, synergy: { flags: [ "airRadar" ], single: { "tyku": 2, "houk": 2 }, }, }, }, }, // Type 1 Armor-Piercing Shell Kai "365": { count: 0, byClass: { // Ise Class "2": { single: { "houg": 1 }, }, // Kongou Class "6": [ { single: { "houg": 1 }, }, { // Extra +2 fp for Kongou Class Kai Ni C remodel: 3, single: { "houg": 2 }, }, ], // Nagato Class "19": [ { single: { "houg": 1 }, }, { remodel: 2, single: { "houg": 1 }, }, ], // Fusou Class "26": { single: { "houg": 1 }, }, // Yamato Class "37": [ { single: { "houg": 1 }, }, { remodel: 1, single: { "houg": 1 }, }, ], }, }, // Type 3 Shell "35": { count: 0, byClass: { "6": { // Kongou Class Kai Ni C remodel: 3, single: { "houg": 1, "tyku": 1 }, }, }, byShip: [ { // Kongou K2 +1 fp, +1 aa ids: [149], single: { "houg": 1, "tyku": 1 }, }, { // Hiei K2 +1 aa ids: [150], single: { "tyku": 1 }, }, { // Haruna K2 +1 aa, +1 ev ids: [151], single: { "tyku": 1, "houk": 1 }, }, { // Kirishima K2 +1 fp ids: [152], single: { "houg": 1 }, }, ], }, // Type 3 Shell Kai "317": { count: 0, byClass: { "6": [ { // Kongou Class +1 fp, +1 aa single: { "houg": 1, "tyku": 1 }, }, { // Kongou Class K2C totally +3 fp, +3 aa remodel: 3, single: { "houg": 2, "tyku": 2 }, }, ], // Nagato Class Kai Ni +1 fp, +2 aa "19": { remodel: 2, single: { "houg": 1, "tyku": 2 }, }, }, byShip: [ { // Kongou K2 totally +3 fp, +3 aa ids: [149], single: { "houg": 2, "tyku": 2 }, }, { // Hiei K2 totally +2 fp, +2 aa ids: [150], single: { "houg": 1, "tyku": 1 }, }, { // Haruna K2 totally +2 fp, +2 aa, +1 ev ids: [151], single: { "houg": 1, "tyku": 1, "houk": 1 }, }, { // Kirishima K2 totally +3 fp, +2 aa ids: [152], single: { "houg": 2, "tyku": 1 }, }, { // Mutsu Kai Ni totally +2 fp, +2 aa, +1 ev ids: [573], single: { "houg": 1, "houk": 1 }, }, ], }, // 20-tube 7inch UP Rocket Launchers "301": { count: 0, byClass: { // Queen Elizabeth Class "67": { multiple: { "souk": 1, "tyku": 2, "houk": 1 }, }, // Ark Royal Class "78": "67", // Jervis Class "82": "67", // Nelson Class "88": "67", // Town Class "108": "67", // Illustrious Class "112": "67", }, }, // Type 93 Passive Sonar "46": { count: 0, byClass: { // Katori Class "56": { synergy: { flags: [ "domesticSonar" ], distinct: { "houk": 3, "tais": 2 }, }, }, }, }, // Type 3 Active Sonar "47": { count: 0, starsDist: [], byClass: { // Katori Class "56": { synergy: { flags: [ "domesticSonar" ], distinct: { "houk": 3, "tais": 2 }, }, }, }, byShip: [ { // All remodels of: Kamikaze, Harukaze, Shigure, Yamakaze, Maikaze, Asashimo origins: [471, 473, 43, 457, 122, 425], multiple: { "houg": 1, "houk": 2, "tais": 3 }, }, { // All remodels of: Ushio, Ikazuchi, Yamagumo, Isokaze, Hamakaze, Kishinami origins: [16, 36, 414, 167, 170, 527], multiple: { "houk": 2, "tais": 2 }, }, ], }, // Type 3 Active Sonar Kai "438": { count: 0, byClass: { // Ayanami Class "1": { single: { "houk": 1, "tais": 1 }, }, // Akatsuki Class "5": "1", // Hatsuharu Class "10": "1", // Fubuki Class "12": "1", // Asashio Class "18": "1", // Shimakaze Class "22": "1", // Shiratsuyu Class "23": "1", // Mutsuki Class "28": "1", // Kagerou Class "30": "1", // Yuugumo Class "38": "1", // Akizuki Class "54": "1", // Kamikaze Class "66": "1", // Matsu Class "101": "1", // Katori Class "56": { synergy: { flags: [ "domesticSonar" ], distinct: { "houk": 3, "tais": 2 }, }, }, }, byShip: [ { // All remodels of: Kamikaze, Harukaze, Shigure, Yamakaze, Maikaze, Asashimo origins: [471, 473, 43, 457, 122, 425], multiple: { "houg": 1, "houk": 2, "tais": 3 }, }, { // All remodels of: Ushio, Ikazuchi, Yamagumo, Isokaze, Hamakaze, Kishinami origins: [16, 36, 414, 167, 170, 527], multiple: { "houk": 2, "tais": 2 }, }, { // All remodels of: Ushio, Maikaze, Isokaze, Hamakaze, Ikazuchi, Yamagumo, Umikaze, Kawakaze, Suzukaze origins: [16, 122, 167, 170, 36, 414, 458, 459, 47], single: { "tais": 1 }, }, { // All remodels of: Shigure, Yamakaze, Kamikaze, Harukaze, Mikura, Ishigaki origins: [43, 457, 473, 611, 585], single: { "houk": 1, "tais": 1 }, }, { // Naka K2, Yura K2, Isuzu K2 ids: [160, 488, 141], single: { "houk": 1, "tais": 1 }, }, { // Shigure K2, Harukaze Kai, Kamikaze Kai, Asashimo K2, Yamakaze K2+ ids: [145, 363, 476, 578, 588, 667], minStars: 4, single: { "tais": 1 }, }, { // Shigure K2, Harukaze Kai, Kamikaze Kai, Asashimo K2, Yamakaze K2+ ids: [145, 363, 476, 578, 588, 667], minStars: 6, single: { "houk": 1 }, }, { // Shigure K2, Harukaze Kai, Kamikaze Kai, Asashimo K2, Yamakaze K2+ ids: [145, 363, 476, 578, 588, 667], minStars: 8, single: { "tais": 1 }, }, { // Shigure K2, Harukaze Kai, Kamikaze Kai, Asashimo K2, Yamakaze K2+ ids: [145, 363, 476, 578, 588, 667], minStars: 10, single: { "houk": 1 }, }, ], }, // Type 0 Passive Sonar "132": { count: 0, byClass: { // Katori Class "56": { synergy: { flags: [ "domesticSonar" ], distinct: { "houk": 3, "tais": 2 }, }, }, }, }, // Type 4 Passive Sonar "149": { count: 0, byClass: { // Akizuki Class "54": { single: { "houk": 2, "tais": 1 }, }, // Katori Class "56": { synergy: { flags: [ "domesticSonar" ], distinct: { "houk": 3, "tais": 2 }, }, }, }, byShip: [ { // Yuubari K2/T, Isuzu K2, Naka K2, Yura K2, Yukikaze K2 ids: [622, 623, 141, 160, 488, 656], single: { "houk": 3, "tais": 1 }, }, { // Yuubari K2D ids: [624], single: { "houk": 5, "tais": 3 }, }, { // Noshiro K2 ids: [662], single: { "tais": 2, "houk": 4 }, }, ], }, // Type 94 Depth Charge Projector "44": { count: 0, byClass: { // Katori Class "56": { multiple: { "houk": 2, "tais": 3 }, }, }, }, // Type 3 Depth Charge Projector "45": { count: 0, byClass: { // Katori Class "56": { multiple: { "houk": 2, "tais": 3 }, }, }, }, // Type 3 Depth Charge Projector (Concentrated Deployment) "287": { count: 0, byClass: { // Katori Class "56": { multiple: { "houk": 2, "tais": 3 }, }, }, byShip: [ { // Yuubari K2D, Isuzu K2, Naka K2, Yura K2, Yukikaze K2 ids: [624, 141, 160, 488, 656], multiple: { "houk": 1, "tais": 1 }, }, { // Noshiro K2 ids: [662], multiple: { "tais": 3 }, }, ], }, // Prototype 15cm 9-tube ASW Rocket Launcher "288": { count: 0, byClass: { // Katori Class "56": { multiple: { "houk": 2, "tais": 3 }, }, }, byShip: [ { // Isuzu K2, Naka K2, Yura K2, Yukikaze K2 ids: [141, 160, 488, 656], multiple: { "houk": 1, "tais": 2 }, }, { // Yuubari K2D ids: [624], multiple: { "houg": 1, "houk": 2, "tais": 3 }, }, { // Noshiro K2 ids: [662], multiple: { "tais": 4, "houk": 1 }, }, ], }, // RUR-4A Weapon Alpha Kai "377": { count: 0, byClass: { // Following Americans: John C. Butler Class "87": { single: { "houk": 1, "tais": 2 }, }, // Fletcher Class "91": "87", // Atlanta Class "99": "87", // St. Louis Class "106": "87", // Brooklyn Class "110": "87", // Jervis Class "82": { single: { "houk": 1, "tais": 1 }, }, // Perth Class "96": "82", // Town Class "108": "82", }, byShip: [ { // Fletcher Mk.II, extra +1 ASW, +1 EV ids: [629], single: { "houk": 2, "tais": 1 }, }, { // Tan Yang/Yukikaze K2 ids: [651, 656], single: { "houk": 2, "tais": 1 }, }, ], }, // Lightweight ASW Torpedo (Initial Test Model) "378": { count: 0, byClass: { // Following Americans: John C. Butler Class "87": { single: { "houk": 1, "tais": 3 }, }, // Fletcher Class "91": "87", // Atlanta Class "99": "87", // St. Louis Class "106": "87", // Brooklyn Class "110": "87", // Jervis Class "82": { single: { "houk": 1, "tais": 2 }, }, // Town Class "108": "82", // Perth Class "96": { single: { "houk": 1, "tais": 1 }, }, }, byShip: [ { // Fletcher Mk.II, extra +1 ASW, +1 EV ids: [629], single: { "houk": 1, "tais": 1 }, }, { // Tan Yang/Yukikaze K2 ids: [651, 656], single: { "houk": 1, "tais": 1 }, }, ], }, // Hedgehog (Initial Model) "439": { count: 0, // Country by ctype implemented in main.js, see #SlotItemEffectParamModel.prototype.getCountryNameList // Following classes should be applied to all of `アメリカ` and `イギリス` byClass: { // Jervis Class "82": { single: { "tais": 2 }, }, // John C. Butler Class "87": "82", // Fletcher Class "91": "82", // Atlanta Class "99": "82", // St. Louis Class "106": "82", // Town Class "108": "82", // Brooklyn Class "110": "82", // Matsu Class "101": { single: { "tais": 1 }, }, }, byShip: [ { // All DE stypes: [1], single: { "houk": 1, "tais": 2 }, }, { // All DD/CL/CT stypes: [2, 3, 21], single: { "houk": 1, "tais": 1 }, }, ], }, // Arctic Camouflage "268": { count: 0, byShip: { // Tama K / K2, Kiso K / K2 ids: [146, 216, 217, 547], single: { "souk": 2, "houk": 7 }, }, }, // New Kanhon Design Anti-torpedo Bulge (Large) "204": { count: 0, starsDist: [], byClass: { // Kongou Class Kai Ni C "6": [ { remodel: 3, single: { "raig": 1, "souk": 1 }, }, { remodel: 3, minStars: 7, single: { "souk": 1 }, }, { remodel: 3, minStars: 10, single: { "raig": 1 }, }, ], }, }, // Soukoutei (Armored Boat Class) "408": { count: 0, byShip: [ { // Shinshuumaru origins: [621], multiple: { "houg": 2, "saku": 2, "houk": 2 }, }, { // Akitsumaru origins: [161], multiple: { "houg": 1, "tais": 1, "saku": 1, "houk": 1 }, }, { // All DD (if can equip Daihatsu ofc) stypes: [2], multiple: { "houg": 1, "saku": 1, "houk": -5 }, }, ], }, // Armed Daihatsu "409": { count: 0, byShip: [ { // Shinshuumaru origins: [621], multiple: { "houg": 1, "tyku": 2, "houk": 3 }, }, { // Akitsumaru origins: [161], multiple: { "houg": 1, "tyku": 1, "tais": 1, "houk": 2 }, }, ], }, // New Model High Temperature High Pressure Boiler "87": { count: 0, starsDist: [], byClass: { // Kongou Class Kai Ni C "6": [ { remodel: 3, single: { "raig": 1, "houk": 2 }, }, { remodel: 3, minStars: 6, single: { "houk": 1 }, }, { remodel: 3, minStars: 8, single: { "raig": 1 }, }, { remodel: 3, minStars: 10, single: { "houg": 1 }, }, ], // I-203 Class, 1 boiler without Turbine: Slow -> Fast "109": { single: { "soku": 5, }, }, }, }, // Pugliese Underwater Protection Bulkhead "136": { count: 0, starsDist: [], byClass: { // Italian large ships: V.Veneto Class "58": [ { single: { "souk": 2, "houk": 1 }, }, { minStars: 3, multiple: { "souk": 1 }, }, { minStars: 6, multiple: { "souk": 1 }, }, { minStars: 10, multiple: { "souk": 1 }, }, ], // Aquila Class "68": "58", // Conte di Cavour Class "113": "58", }, byShip: { // Conte di Cavour Nuovo ids: [879], single: { "souk": 1, "houk": 1 }, }, }, // Skilled Lookouts "129": { count: 0, byClass: { // All IJN DD fp +1, tp +2, asw +2, ev +2, los +1 // Ayanami Class "1": { multiple: { "houg": 1, "raig": 2, "tais": 2, "houk": 2, "saku": 1 }, }, // Akatsuki Class "5": "1", // Hatsuharu Class "10": "1", // Fubuki Class "12": "1", // Asashio Class "18": "1", // Shimakaze Class "22": "1", // Shiratsuyu Class "23": "1", // Mutsuki Class "28": "1", // Kagerou Class "30": "1", // Yuugumo Class "38": "1", // Akizuki Class "54": "1", // Kamikaze Class "66": "1", // Matsu Class "101": "1", // All IJN CL fp +1, tp +2, ev +2, los +3 // Kuma Class "4": { multiple: { "houg": 1, "raig": 2, "houk": 2, "saku": 3 }, }, // Sendai Class "16": "4", // Nagara Class "20": "4", // Tenryuu Class "21": "4", // Yuubari Class "34": "4", // Agano Class "41": "4", // Ooyodo Class "52": "4", // Katori Class "56": "4", // All IJN CA fp +1, ev +2, los +3 // Furutaka Class "7": { multiple: { "houg": 1, "houk": 2, "saku": 3 }, }, // Takao Class "8": "7", // Mogami Class "9": "7", // Aoba Class "13": "7", // Myoukou Class "29": "7", // Tone Class "31": "7", }, }, // Torpedo Squadron Skilled Lookouts "412": { count: 0, starsDist: [], byClass: { // All IJN DD // Ayanami Class "1": [ { single: { "houg": 2, "raig": 4, "tais": 2 }, }, { multiple: { "houk": 3, "saku": 1 }, }, { minStars: 4, single: { "houg": 1 }, }, { minStars: 8, single: { "raig": 1 }, }, ], // Akatsuki Class "5": "1", // Hatsuharu Class "10": "1", // Fubuki Class "12": "1", // Asashio Class "18": "1", // Shimakaze Class "22": "1", // Shiratsuyu Class "23": "1", // Mutsuki Class "28": "1", // Kagerou Class "30": "1", // Yuugumo Class "38": "1", // Akizuki Class "54": "1", // Kamikaze Class "66": "1", // Matsu Class "101": "1", // All IJN CL // Kuma Class "4": [ { single: { "houg": 3, "raig": 3 }, }, { multiple: { "houk": 2, "saku": 3 }, }, { minStars: 4, single: { "houg": 1 }, }, { minStars: 8, single: { "raig": 1 }, }, ], // Sendai Class "16": "4", // Nagara Class "20": "4", // Tenryuu Class "21": "4", // Yuubari Class "34": "4", // Agano Class "41": "4", // Ooyodo Class "52": "4", // Katori Class "56": "4", // All IJN CA // Furutaka Class "7": [ { single: { "houg": 1 }, }, { multiple: { "houk": 1, "saku": 1 }, }, ], // Takao Class "8": "7", // Mogami Class "9": "7", // Aoba Class "13": "7", // Myoukou Class "29": "7", // Tone Class "31": "7", }, }, // Elite Torpedo Squadron Command Facility "413": { count: 0, byClass: { // Ignore if specific ships can equip or not // Ayanami Class "1":{ single: { "houg": 2, "raig": 2, "houk": 4 }, }, // Akatsuki Class "5": "1", // Hatsuharu Class "10": "1", // Fubuki Class "12": "1", // Asashio Class "18": "1", // Shimakaze Class "22": "1", // Shiratsuyu Class "23": "1", // Mutsuki Class "28": "1", // Kagerou Class "30": "1", // Kamikaze Class "66": "1", // Matsu Class "101": "1", // Yuugumo Class extra +2 fp, +3 tp, +3 ev "38": { single: { "houg": 4, "raig": 5, "houk": 7 }, }, // Akizuki Class "54": "38", // Katori Class "56": { single: { "houg": 4, "raig": 2, "houk": 2 }, }, // Tenryuu Class extra +2 aa, +1 tp, +1 ev "21": { single: { "houg": 4, "raig": 3, "tyku": 2, "houk": 3 }, }, // Yuubari Class "34": "21", // Kuma Class extra +1 fp, +2 tp, +3 ev "4": { single: { "houg": 5, "raig": 4, "houk": 5 }, }, // Sendai Class "16": "4", // Nagara Class "20": "4", // Agano Class "41": "4", // Ooyodo Class "52": "4", }, byShip: [ { // Naka, Yura, Yahagi, Noshiro, Hamanami, Shimakaze, Kiyoshimo, Hatsushimo origins: [56, 23, 139, 138, 484, 50, 41], single: { "tyku": 1, "houk": 1 }, }, { // Jintsuu, Sendai, Naganami, Hatsushimo, Teruzuki origins: [55, 54, 135, 41, 422], single: { "houg": 1, "raig": 1 }, }, { // Jintsuu Kai Ni ids: [159], single: { "houg": 2 }, }, { // Naganami Kai Ni ids: [543], single: { "houg": 1, "houk": 1 }, }, ], }, // All Seaplane Reconnaissances "t2_10": { count: 0, byShip: [ { // Noshiro Kai Ni, Yahagi Kai Ni/K2B ids: [662, 663, 668], single: { "houg": 2, "tais": 3, "houk": 1 }, }, { // Mogami K2+ ids: [501, 506], single: { "houg": 2 }, }, ], }, // All Seaplane Bombers "t2_11": { count: 0, byShip: [ { // Noshiro Kai Ni, Yahagi Kai Ni/K2B ids: [662, 663, 668], single: { "houg": 1, "tais": 1, "houk": 1 }, }, { // Mogami K2+ ids: [501, 506], single: { "houg": 1, "houk": 1 }, }, ], }, // All Rotorcraft "t2_25": { count: 0, byShip: [ { // Noshiro Kai Ni ids: [662], single: { "tais": 4, "houk": 1 }, }, { // Yahagi Kai Ni+ ids: [663, 668], single: { "tais": 3, "houk": 1 }, }, ], }, // All Small Searchlights "t2_29": { count: 0, byShip: [ { // All remodels of: Akatsuki, Choukai, Kirishima, Hiei origins: [34, 69, 85, 86], single: { "houg": 4, "houk": -1 }, }, { // Jintsuu origins: [55], single: { "houg": 8, "raig": 8, "houk": -1 }, }, { // Akigumo origins: [132], multiple: { "houg": 2 }, }, { // Yukikaze origins: [20], multiple: { "houg": 1, "tyku": 1 }, }, { // Noshiro Kai Ni, Yahagi Kai Ni/K2B ids: [662, 663, 668], single: { "houg": 4, "raig": 2 }, }, ], }, // All Large Searchlights "t2_42": { count: 0, byShip: [ { // All remodels of: Kirishima, Hiei origins: [85, 86], single: { "houg": 6, "houk": -2 }, }, { // Hiei Kai Ni C ids: [592], single: { "houg": 3, "raig": 3 }, synergy: { flags: [ "kamikazeTwinTorpedo" ], single: { "raig": 5 }, }, }, { // Yamato, Musashi origins: [131, 143], single: { "houg": 4, "houk": -1 }, }, ], }, // All Radars "t3_11": { count: 0, byShip: [ { // Okinami K2, Akigumo K2 with Air Radar fp +1, aa +2, ev +3 // btw1, main.js also counted Surface Radar for her at the same time, but no bouns assigned at all. // btw2, main.js's function `get_type3_nums` refers `api_type[2]` in fact, not our 't3'(`api_type[3]`), so it uses `12 || 13` for all radars. ids: [569, 648], synergy: { flags: [ "airRadar" ], single: { "houg": 1, "tyku": 2, "houk": 3 }, }, }, ], }, // Improved Kanhon Type Turbine, speed boost synergy with boilers // https://wikiwiki.jp/kancolle/%E9%80%9F%E5%8A%9B#da6be20e "33": { count: 0, byShip: [ { // Fast Group A: Shimakaze, Tashkent, Taihou, Shoukaku, Zuikaku, Mogami, Mikuma, Suzuya, Kumano, Tone, Chikuma, Victorious? origins: [50, 516, 153, 110, 111, 70, 120, 124, 125, 71, 72, 885], synergy: [ { flags: [ "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": 5 }, "2": { "soku": 10 }, "3": { "soku": 10 }, "4": { "soku": 10 }, "5": { "soku": 10 }, }, }, { flags: [ "newModelBoiler" ], single: { "soku": 10 }, }, ], }, { // Fast Group B1: Amatsukaze, Iowa, Souryuu, Hiryuu, Unryuu, Amagi, Kongou, Haruna, Kirishima, Hiei, Agano, Noshiro, Yahagi, Sakawa origins: [181, 440, 90, 91, 404, 331, 78, 79, 85, 86, 137, 138, 139, 140], excludes: [662], synergy: [ { flags: [ "enhancedBoiler" ], single: { "soku": 5 }, }, { flags: [ "newModelBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": 5 }, "2": { "soku": 10 }, "3": { "soku": 10 }, "4": { "soku": 10 }, "5": { "soku": 10 }, }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "2": { "soku": -5 }, "3": { "soku": -5 }, "4": { "soku": -5 }, }, }, ], }, { // Fast Group B2: Yuubari Kai Ni/K2D, Noshiro K2 // Almost fast CV: Akagi, Katsuragi, Intrepid, Ark Royal, Aquila, Graf Zeppelin, Saratoga, Hornet // Almost FBB: Littorio, Roma, Bismarck, Richelieu, South Dakota, Washington, Conte di Cavour Kai+ // All fast DD: not here, see next item // All fast CL/CLT: Nagara, Isuzu, Yura, Ooi, Kitakami, Tenryuu, Tatsuta, Natori, Sendai, Jintsuu, Naka, Kuma, Tama, Kiso, Kinu, Abukuma, Ooyodo, Gotland, Abruzzi, Garibaldi, Atlanta, De Ruyter, Perth, Helena, Sheffield, Honolulu? // All fast CA(V): Furutaka, Kako, Aoba, Myoukou, Nachi, Ashigara, Haguro, Takao, Atago, Maya, Choukai, Kinugasa, Prinz Eugen, Zara, Pola, Houston, Northampton // All fast CVL: Shouhou, Ryuujou, Zuihou, Chitose-Kou, Chiyoda-Kou, Ryuuhou K2 origins: [115, 138, 441, 442, 171, 492, 602, 654, 83, 332, 549, 515, 444, 432, 433, 603, 21, 22, 23, 24, 25, 51, 52, 53, 54, 55, 56, 99, 100, 101, 113, 114, 183, 574, 589, 590, 597, 604, 613, 615, 514, 598, 877, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 123, 176, 448, 449, 595, 655, 74, 76, 116, 102, 103, 184 ], excludes: [115, 293, 623, 138, 306, 102, 103, 104, 105, 106, 107, 184, 185, 318, 883, 877], synergy: [ { flags: [ "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": 5 }, "2": { "soku": 5 }, "3": { "soku": 10 }, "4": { "soku": 10 }, "5": { "soku": 10 }, }, }, { flags: [ "newModelBoiler" ], byCount: { gear: "newModelBoiler", "1": { "soku": 5 }, "2": { "soku": 10 }, "3": { "soku": 10 }, "4": { "soku": 10 }, "5": { "soku": 10 }, }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": -5 }, "2": { "soku": -5 }, "3": { "soku": -5 }, "4": { "soku": -5 }, }, }, ], }, { // Fast Group B2 for all fast DDs stypes: [2], // Except slow DDs(see Slow Group B special below) and DDs in other groups: // Samuel B.Roberts, Shimakaze, Tashkent, Amatsukaze excludes: [561, 681, 50, 229, 516, 395, 181, 316], synergy: [ { flags: [ "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": 5 }, "2": { "soku": 5 }, "3": { "soku": 10 }, "4": { "soku": 10 }, }, }, { flags: [ "newModelBoiler" ], byCount: { gear: "newModelBoiler", "1": { "soku": 5 }, "2": { "soku": 10 }, "3": { "soku": 10 }, "4": { "soku": 10 }, }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": -5 }, "2": { "soku": -5 }, "3": { "soku": -5 }, }, }, ], }, { // Fast Group C: Yuubari/Yuubari Kai, Kaga, fast AV: Chitose, Chiyoda, Nisshin origins: [115, 84, 102, 103, 581], excludes: [622, 623, 624, 108, 109, 291, 292, 296, 297], synergy: [ { flags: [ "enhancedBoiler" ], single: { "soku": 5 }, }, { flags: [ "newModelBoiler" ], single: { "soku": 5 }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], single: { "soku": -5 }, }, ], }, { // Slow Group A: Yamato, Musashi, Nagato Kai Ni, Mutsu Kai Ni origins: [131, 143, 80, 81], excludes: [80, 275, 81, 276], synergy: [ { flags: [ "enhancedBoiler" ], single: { "soku": 5 }, }, { flags: [ "newModelBoiler" ], byCount: { gear: "newModelBoiler", "1": { "soku": 5 }, "2": { "soku": 10 }, "3": { "soku": 15 }, "4": { "soku": 15 }, "5": { "soku": 15 }, }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "2": { "soku": 5 }, "3": { "soku": 5 }, "4": { "soku": 5 }, }, }, ], }, { // Slow Group B: Taigei/Ryuuhou, Jingei, Chougei, Kamoi, Katori, Kashima, Shinshumaru, Souya (AGS) // All slow BB(V): Fusou, Yamashiro, Ise, Hyuuga, Nagato, Mutsu, Warspite, Nelson, Colorado, Gangut, Conte di Cavour (base remodel) // Slow CVL: Hiyou, Houshou, Junyou, Taiyou, Shinyou, Gambier Bay // Slow AV: Akitsushima, Mizuho, Commandant Teste origins: [184, 634, 635, 162, 154, 465, 621, 699, 26, 27, 77, 87, 80, 81, 439, 571, 601, 511, 877, 75, 89, 92, 521, 534, 544, 445, 451, 491 ], excludes: [541, 573, 888, 878, 879], synergy: [ { flags: [ "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": 5 }, "2": { "soku": 5 }, "3": { "soku": 10 }, "4": { "soku": 10 }, "5": { "soku": 10 }, }, }, { flags: [ "newModelBoiler" ], byCount: { gear: "newModelBoiler", "1": { "soku": 5 }, "2": { "soku": 10 }, "3": { "soku": 10 }, "4": { "soku": 10 }, "5": { "soku": 10 }, }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "1": { "soku": -5 }, "3": { "soku": -5 }, "4": { "soku": -5 }, }, }, { flags: [ "enhancedBoiler", "newModelBoiler" ], byCount: { gear: "newModelBoiler", "2": { "soku": -5 }, "3": { "soku": -5 }, "4": { "soku": -5 }, }, }, ], }, { // Slow Group B special: Yuubari Kai Ni Toku, Samuel B.Roberts ids: [623, 561, 681], single: { "soku": 5 }, synergy: [ { flags: [ "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "3": { "soku": 5 }, "4": { "soku": 5 }, "5": { "soku": 5 }, }, }, { flags: [ "newModelBoiler" ], byCount: { gear: "newModelBoiler", "2": { "soku": 5 }, "3": { "soku": 5 }, "4": { "soku": 5 }, "5": { "soku": 5 }, }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], byCount: { gear: "enhancedBoiler", "2": { "soku": 5 }, }, }, ], }, { // Slow Group C: Akashi, Hayasui, Akitsumaru // All SS(V): I-168, I-58, I-8, I-19, I-26, I-13, I-400, I-401, I-14, I-47, U-511, UIT-25, Maruyu, I-203 origins: [182, 460, 161, 126, 127, 128, 191, 483, 493, 155, 494, 495, 636, 431, 539, 163, 882], synergy: [ { flags: [ "enhancedBoiler" ], single: { "soku": 5 }, }, { flags: [ "newModelBoiler" ], single: { "soku": 5 }, }, { flags: [ "newModelBoiler", "enhancedBoiler" ], single: { "soku": -5 }, }, ], }, ], }, }; }; })();
/* global define, describe, it, expect, beforeEach */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['_tree', 'underscore'], factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. /* global module, require */ module.exports = factory(require('../../src/_tree'), require('underscore')); } else { // Browser globals (root is window) factory(root._tree, root._); } }(this, function (_tree, _) { 'use strict'; describe('tree.walk', function () { describe('on an empty tree', function () { var tree; beforeEach(function () { tree = _tree.create(); }); describe('with method tree.walk.dfpre', function () { it('finds only the root node', function () { var ids = []; expect(tree).toBeDefined(); expect(tree.walk).toBeDefined(); tree.walk(function (n) { ids.push(n.__id); }, tree.walk.dfpre); expect(ids.length).toBe(1); expect(ids[0]).toBe(0); }); }); describe('with method tree.walk.dfpost', function () { it('finds only the root node', function () { var ids = []; tree.walk(function (n) { ids.push(n.__id); }, tree.walk.dfpost); expect(ids.length).toBe(1); expect(ids[0]).toBe(0); }); }); describe('with method tree.walk.bfpre', function () { it('finds only the root node', function () { var ids = []; tree.walk(function (n) { ids.push(n.__id); }, tree.walk.bfpre); expect(ids.length).toBe(1); expect(ids[0]).toBe(0); }); }); describe('with method tree.walk.bfpost', function () { it('finds only the root node', function () { var ids = []; tree.walk(function (n) { ids.push(n.__id); }, tree.walk.bfpost); expect(ids.length).toBe(1); expect(ids[0]).toBe(0); }); }); }); describe('on a complicated tree', function () { var tree; beforeEach(function () { tree = _tree.inflate([1, [2, 3, [4, 5], 6, [7, [8, 9], 10, [11, [12]]]]], _tree.inflate.byAdjacencyList); }); describe('with method tree.walk.dfpre', function () { it('finds all nodes in the correct order', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.dfpre); expect(vals).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); }); }); describe('with method tree.walk.dfpost', function () { it('finds all nodes in the correct order', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.dfpost); expect(vals).toEqual([2, 4, 5, 3, 8, 9, 7, 12, 11, 10, 6, 1]); }); }); describe('with method tree.walk.bfpre', function () { it('finds all nodes in the correct order', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.bfpre); expect(vals).toEqual([1, 2, 3, 6, 4, 5, 7, 10, 8, 9, 11, 12]); }); }); describe('with method tree.walk.bfpost', function () { it('finds all nodes in the correct order', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.bfpost); expect(vals).toEqual([12, 8, 9, 11, 4, 5, 7, 10, 2, 3, 6, 1]); }); }); describe('starting from non-root', function () { it('throws on non-node', function () { var tree = _tree.create(); expect(_.bind(tree.walk, this, function(){}, tree.walk.dfpre)).toThrow(); expect(_.bind(tree.walk, this, function(){}, tree.walk.dfpre, null)).toThrow(); expect(_.bind(tree.walk, this, function(){}, tree.walk.dfpre, 1)).toThrow(); expect(_.bind(tree.walk, this, function(){}, tree.walk.dfpre, [1, [2]])).toThrow(); }); it('throws if node does not exist', function () { var otherTree = _tree.create(), rt = otherTree.root(), err = function() { try { tree.walk(function(){}, tree.walk.dfpre, rt); } catch (e) { return e.message; } return 'did not error'; }; expect(_.bind(tree.walk, this, function(){}, tree.walk.dfpre, rt)).toThrow(); expect(err()).toEqual('startNode does not exist in the tree'); }); it('walks the root fine', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.dfpre, tree.root()); expect(vals).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); }); it('walks a single node', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.dfpre, tree.root().children()[0]); expect(vals).toEqual([2]); }); it('walks a subtree', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.dfpre, tree.root().children()[1]); expect(vals).toEqual([3, 4, 5]); }); it('walks a different subtree', function () { var vals = []; tree.walk(function (n) { vals.push(n.data()); }, tree.walk.dfpre, tree.root().children()[2]); expect(vals).toEqual([6, 7, 8, 9, 10, 11, 12]); }); }); }); }); }));
import typescript from '@rollup/plugin-typescript' import replace from '@rollup/plugin-replace' import resolve from '@rollup/plugin-node-resolve' import { uglify } from 'rollup-plugin-uglify' import pkg from './package.json' // These plugins are used for all builds const sharedPlugins = [ replace({ preventAssignment: false, exclude: 'node_modules/**', __VERSION__: pkg.version }), resolve() ] // These plugins are used for UMD builds const umdPlugins = [ ...sharedPlugins, typescript({ tsconfig: './tsconfig.json', exclude: [ "./src/server.ts", "./src/server/**" ] }) ] // These plugins are used for Node builds const nodePlugins = [ ...sharedPlugins, typescript({ tsconfig: './tsconfig.json', exclude: [ "./src/browser.ts", "./src/browser/**" ] }) ] export default [ // Browser build { input: 'src/browser.ts', output: { name: 'Honeybadger', file: pkg.browser, format: 'umd', sourcemap: true }, plugins: umdPlugins }, // Browser build (minified) { input: 'src/browser.ts', output: { name: 'Honeybadger', file: 'dist/browser/honeybadger.min.js', format: 'umd', sourcemap: true }, plugins: [...umdPlugins, uglify()] }, // Server build { input: 'src/server.ts', external: ['http', 'https', 'url'], output: { file: pkg.main, format: 'cjs' }, plugins: nodePlugins } ]
/** * jQuery.marquee - scrolling text like old marquee element * @author Aamir Afridi - aamirafridi(at)gmail(dot)com / http://aamirafridi.com/jquery/jquery-marquee-plugin */; (function($) { $.fn.marquee = function(options) { return this.each(function() { // Extend the options if any provided var o = $.extend({}, $.fn.marquee.defaults, options), $this = $(this), $marqueeWrapper, containerWidth, animationCss, verticalDir, elWidth, loopCount = 3, playState = 'animation-play-state', css3AnimationIsSupported = false, //Private methods _prefixedEvent = function(element, type, callback) { var pfx = ["webkit", "moz", "MS", "o", ""]; for (var p = 0; p < pfx.length; p++) { if (!pfx[p]) type = type.toLowerCase(); element.addEventListener(pfx[p] + type, callback, false); } }, _objToString = function(obj) { var tabjson = []; for (var p in obj) { if (obj.hasOwnProperty(p)) { tabjson.push(p + ':' + obj[p]); } } tabjson.push(); return '{' + tabjson.join(',') + '}'; }, _startAnimationWithDelay = function() { $this.timer = setTimeout(animate, o.delayBeforeStart); }, //Public methods methods = { pause: function() { if (css3AnimationIsSupported && o.allowCss3Support) { $marqueeWrapper.css(playState, 'paused'); } else { //pause using pause plugin if ($.fn.pause) { $marqueeWrapper.pause(); } } //save the status $this.data('runningStatus', 'paused'); //fire event $this.trigger('paused'); }, resume: function() { //resume using css3 if (css3AnimationIsSupported && o.allowCss3Support) { $marqueeWrapper.css(playState, 'running'); } else { //resume using pause plugin if ($.fn.resume) { $marqueeWrapper.resume(); } } //save the status $this.data('runningStatus', 'resumed'); //fire event $this.trigger('resumed'); }, toggle: function() { methods[$this.data('runningStatus') == 'resumed' ? 'pause' : 'resume'](); }, destroy: function() { //Clear timer clearTimeout($this.timer); //Unbind all events $this.find("*").andSelf().unbind(); //Just unwrap the elements that has been added using this plugin $this.html($this.find('.js-marquee:first').html()); } }; //Check for methods if (typeof options === 'string') { if ($.isFunction(methods[options])) { //Following two IF statements to support public methods if (!$marqueeWrapper) { $marqueeWrapper = $this.find('.js-marquee-wrapper'); } if ($this.data('css3AnimationIsSupported') === true) { css3AnimationIsSupported = true; } methods[options](); } return; } /* Check if element has data attributes. They have top priority For details https://twitter.com/aamirafridi/status/403848044069679104 - Can't find a better solution :/ jQuery 1.3.2 doesn't support $.data().KEY hence writting the following */ var dataAttributes = {}, attr; $.each(o, function(key, value) { //Check if element has this data attribute attr = $this.attr('data-' + key); if (typeof attr !== 'undefined') { //Now check if value is boolean or not switch (attr) { case 'true': attr = true; break; case 'false': attr = false; break; } o[key] = attr; } }); //since speed option is changed to duration, to support speed for those who are already using it o.duration = o.speed || o.duration; //Shortcut to see if direction is upward or downward verticalDir = o.direction == 'up' || o.direction == 'down'; //no gap if not duplicated o.gap = o.duplicated ? o.gap : 0; //wrap inner content into a div $this.wrapInner('<div class="js-marquee"></div>'); //Make copy of the element var $el = $this.find('.js-marquee').css({ 'margin-right': o.gap, 'float': 'left' }); if (o.duplicated) { $el.clone(true).appendTo($this); } //wrap both inner elements into one div $this.wrapInner('<div style="width:100000px" class="js-marquee-wrapper"></div>'); //Save the reference of the wrapper $marqueeWrapper = $this.find('.js-marquee-wrapper'); //If direction is up or down, get the height of main element if (verticalDir) { var containerHeight = $this.height(); $marqueeWrapper.removeAttr('style'); $this.height(containerHeight); //Change the CSS for js-marquee element $this.find('.js-marquee').css({ 'float': 'none', 'margin-bottom': o.gap, 'margin-right': 0 }); //Remove bottom margin from 2nd element if duplicated if (o.duplicated) $this.find('.js-marquee:last').css({ 'margin-bottom': 0 }); var elHeight = $this.find('.js-marquee:first').height() + o.gap; // adjust the animation speed according to the text length // formula is to: (Height of the text node / Height of the main container) * speed; o.duration = ((parseInt(elHeight, 10) + parseInt(containerHeight, 10)) / parseInt(containerHeight, 10)) * o.duration; } else { //Save the width of the each element so we can use it in animation elWidth = $this.find('.js-marquee:first').width() + 16 + o.gap; //container width containerWidth = $this.width(); // adjust the animation speed according to the text length // formula is to: (Width of the text node / Width of the main container) * speed; o.duration = ((parseInt(elWidth, 10) + parseInt(containerWidth, 10)) / parseInt(containerWidth, 10)) * o.duration; } //if duplicated than reduce the speed if (o.duplicated) { o.duration = o.duration / 2; } if (o.allowCss3Support) { var elm = document.body || document.createElement('div'), animationName = 'marqueeAnimation-' + Math.floor(Math.random() * 10000000), domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), animationString = 'animation', animationCss3Str = '', keyframeString = ''; //Check css3 support if (elm.style.animation) { keyframeString = '@keyframes ' + animationName + ' '; css3AnimationIsSupported = true; } if (css3AnimationIsSupported === false) { for (var i = 0; i < domPrefixes.length; i++) { if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) { var prefix = '-' + domPrefixes[i].toLowerCase() + '-'; animationString = prefix + animationString; playState = prefix + playState; keyframeString = '@' + prefix + 'keyframes ' + animationName + ' '; css3AnimationIsSupported = true; break; } } } if (css3AnimationIsSupported) { animationCss3Str = animationName + ' ' + o.duration / 1000 + 's ' + o.delayBeforeStart / 1000 + 's infinite ' + o.css3easing; $this.data('css3AnimationIsSupported', true); } } var _rePositionVertically = function() { $marqueeWrapper.css('margin-top', o.direction == 'up' ? containerHeight + 'px' : '-' + elHeight + 'px'); }, _rePositionHorizontally = function() { $marqueeWrapper.css('margin-left', o.direction == 'left' ? '0px' : '-' + elWidth + 'px'); }; //if duplicated option is set to true than position the wrapper if (o.duplicated) { if (verticalDir) { $marqueeWrapper.css('margin-top', o.direction == 'up' ? containerHeight + 'px' : '-' + ((elHeight * 2) - o.gap) + 'px'); } else { $marqueeWrapper.css('margin-left', o.direction == 'left' ? containerWidth + 'px' : '-' + ((elWidth * 2) - o.gap) + 'px'); } loopCount = 1; } else { if (verticalDir) { _rePositionVertically(); } else { _rePositionHorizontally(); } } //Animate recursive method var animate = function() { if (o.duplicated) { //When duplicated, the first loop will be scroll longer so double the duration if (loopCount === 1) { o._originalDuration = o.duration; if (verticalDir) { o.duration = o.direction == 'up' ? o.duration + (containerHeight / ((elHeight) / o.duration)) : o.duration * 2; } else { o.duration = o.direction == 'left' ? o.duration + (containerWidth / ((elWidth) / o.duration)) : o.duration * 2; } //Adjust the css3 animation as well if (animationCss3Str) { animationCss3Str = animationName + ' ' + o.duration / 1000 + 's ' + o.delayBeforeStart / 1000 + 's ' + o.css3easing; } loopCount++; } //On 2nd loop things back to normal, normal duration for the rest of animations else if (loopCount === 2) { o.duration = o._originalDuration; //Adjust the css3 animation as well if (animationCss3Str) { animationName = animationName + '0'; keyframeString = $.trim(keyframeString) + '0 '; animationCss3Str = animationName + ' ' + o.duration / 1000 + 's 0s infinite ' + o.css3easing; } loopCount++; } } if (verticalDir) { if (o.duplicated) { //Adjust the starting point of animation only when first loops finishes if (loopCount > 2) { $marqueeWrapper.css('margin-top', o.direction == 'up' ? 0 : '-' + elHeight + 'px'); } animationCss = { 'margin-top': o.direction == 'up' ? '-' + elHeight + 'px' : 0 }; } else { _rePositionVertically(); animationCss = { 'margin-top': o.direction == 'up' ? '-' + ($marqueeWrapper.height()) + 'px' : containerHeight + 'px' }; } } else { if (o.duplicated) { //Adjust the starting point of animation only when first loops finishes if (loopCount > 2) { $marqueeWrapper.css('margin-left', o.direction == 'left' ? 0 : '-' + elWidth + 'px'); } animationCss = { 'margin-left': o.direction == 'left' ? '-' + elWidth + 'px' : 0 }; } else { _rePositionHorizontally(); animationCss = { 'margin-left': o.direction == 'left' ? '-' + elWidth + 'px' : containerWidth + 'px' }; } } //fire event $this.trigger('beforeStarting'); //If css3 support is available than do it with css3, otherwise use jQuery as fallback if (css3AnimationIsSupported) { //Add css3 animation to the element $marqueeWrapper.css(animationString, animationCss3Str); var keyframeCss = keyframeString + ' { 100% ' + _objToString(animationCss) + '}', $styles = $('style'); //Now add the keyframe animation to the head if ($styles.length !== 0) { //Bug fixed for jQuery 1.3.x - Instead of using .last(), use following $styles.filter(":last").append(keyframeCss); } else { $('head').append('<style>' + keyframeCss + '</style>'); } //Animation iteration event _prefixedEvent($marqueeWrapper[0], "AnimationIteration", function() { $this.trigger('finished'); }); //Animation stopped _prefixedEvent($marqueeWrapper[0], "AnimationEnd", function() { $this.trigger('finished'); }); } else { //Start animating $marqueeWrapper.animate(animationCss, o.duration, o.easing, function() { //fire event $this.trigger('finished'); //animate again if (o.pauseOnCycle) { _startAnimationWithDelay(); } else { animate(); } }); } //save the status $this.data('runningStatus', 'resumed'); }; //bind pause and resume events $this.bind('pause', methods.pause); $this.bind('resume', methods.resume); if (o.pauseOnHover) { $this.bind('mouseenter mouseleave', methods.toggle); } //If css3 animation is supported than call animate method at once if (css3AnimationIsSupported && o.allowCss3Support) { animate(); } else { //Starts the recursive method _startAnimationWithDelay(); } }); }; //End of Plugin // Public: plugin defaults options $.fn.marquee.defaults = { //If you wish to always animate using jQuery allowCss3Support: true, //works when allowCss3Support is set to true - for full list see http://www.w3.org/TR/2013/WD-css3-transitions-20131119/#transition-timing-function css3easing: 'linear', //requires jQuery easing plugin. Default is 'linear' easing: 'linear', //pause time before the next animation turn in milliseconds delayBeforeStart: 1000, //'left', 'right', 'up' or 'down' direction: 'left', //true or false - should the marquee be duplicated to show an effect of continues flow duplicated: false, //speed in milliseconds of the marquee in milliseconds duration: 5000, //gap in pixels between the tickers gap: 20, //on cycle pause the marquee pauseOnCycle: false, //on hover pause the marquee - using jQuery plugin https://github.com/tobia/Pause pauseOnHover: false }; })(jQuery);
'use strict'; import test from 'blue-tape' import possum from '../src/possum' import stampit from 'stampit' import Promise from 'bluebird' import {EventEmitter2 as EventEmitter} from 'eventemitter2' import EventEmitter3 from 'eventemitter3' const buildMachineProto = (cfg) => { cfg = (cfg || { initialState: 'unlocked' ,namespace: 'door' }) return possum .compose(stampit.convertConstructor(EventEmitter)) .config(cfg) .states({ 'locked': { 'enterCode': function( args, target ) { let p = Promise.resolve() if(args.code === target.code) { return p .then(this.transition.bind(this, 'unlocked')) } return p .then(this.handle.bind(this,'deny' )) } , 'deny': function( args, target ) { this.deferUntilTransition() return Promise.resolve() .then(this.transition.bind(this,'denied')) } } , 'unlocked': { 'lock': function( args, target ) { return Promise.resolve() .then(this.transition.bind(this,'locked')) } } , 'denied': { '_enter': function( target ) { target.denials++ } , 'deny': function( args, target ) { return Promise.delay(90) .then(this.transition.bind(this,'locked')) } , '_exit': function( target ) { target.restarts++ } } }) } const buildMachine = (cfg) => { return buildMachineProto(cfg).create(); } test('[async] state lifecycle', (assert) => { let model = stampit() .refs({ name: 'deadbolt' , code: '123' , denials: 0 , restarts: 0 }) .create() let machine = buildMachine({ initialState: 'locked' }) machine.target(model) return machine.handle('enterCode', { code: '456' }) .then(function(){ assert.equal(machine.currentState, 'locked') assert.equal(model.denials,1) assert.equal(model.restarts,1) }) }) test('[async] handler transitions',(assert) => { assert.plan(1) let model = stampit() .refs({ name: 'deadbolt', code: '123'}) .create() let machine = buildMachine() machine.target(model) return machine.handle('lock').then(function(){ assert.equal(machine.currentState, 'locked') }) }) test('[async] events are emitted', (assert) => { let model = stampit() .refs({ name: 'deadbolt', code: '123'}) .create() let machine = buildMachineProto() .create() machine.target(model) let events = {} machine.on('door.handled',function(e) { events[e.event] = e }) machine.on('door.transitioned',function(e) { events[e.event] = e }) return machine.handle('lock') .tap(function(){ let e = events['door.handled'] assert.ok(e, 'event not raised') assert.equal(e.topic,'handled') assert.equal(e.state,'unlocked', 'state during handled is preserved') assert.equal(e.payload.inputType, 'lock') assert.ok(e.id, 'id is on handled event') assert.ok(e.timestamp, 'handled event is timestamped') }) .tap(function(){ let e = events['door.transitioned'] assert.ok(e, 'event not raised') assert.equal(e.topic,'transitioned') assert.equal(e.payload.fromState,'unlocked','fromState is preserved') assert.equal(e.payload.toState,'locked', 'currentState is represented') assert.ok(e.id, 'id is on the event') assert.ok(e.timestamp, 'timestamped event') }) }) test('[async] transition deferral', ( assert ) => { let model = stampit() .refs({ name: 'deadbolt', code: '123'}) .create() let machine = buildMachineProto({ initialState: 'locked' }) .create() let events = [] machine.onAny(function(e, data) { if(e) { events.push(data) } }) //use bad code return machine.handle('enterCode', { code: '456'}) .then(function() { assert.equal(events.length, 12) assert.equal(machine.currentState, 'locked') assert.equal(events[0].topic, 'handling') assert.equal(events[0].payload.inputType, 'enterCode') assert.equal(events[1].topic, 'invoked') assert.equal(events[1].payload.inputType, 'enterCode') assert.equal(events[2].topic, 'handling') assert.equal(events[2].payload.inputType, 'deny') assert.equal(events[3].topic, 'deferred') assert.equal(events[3].payload.inputType, 'deny') assert.equal(events[4].topic, 'invoked') assert.equal(events[4].payload.inputType, 'deny') assert.equal(events[5].topic, 'transitioned') assert.equal(events[5].payload.toState, 'denied') assert.equal(events[6].topic, 'handling') assert.equal(events[6].payload.inputType, 'deny') assert.equal(events[6].state, 'denied') assert.equal(events[7].topic, 'invoked') assert.equal(events[7].payload.inputType, 'deny') assert.equal(events[7].state, 'denied') assert.equal(events[8].topic, 'transitioned') assert.equal(events[8].payload.toState, 'locked') //now we rewind from all the promises assert.equal(events[9].topic, 'handled') assert.equal(events[9].payload.inputType, 'deny') assert.equal(events[10].topic, 'handled') assert.equal(events[10].payload.inputType, 'deny') assert.equal(events[11].topic, 'handled') assert.equal(events[11].payload.inputType, 'enterCode') }) }) test('[async] multiple deferrals', (assert) => { let machine = possum .compose(stampit.convertConstructor(EventEmitter)) .config({ initialState: 'a' , namespace: 'foo' }) .target({ hits: []}) .states({ 'a': { 'b': function(args, target) { this.deferUntilTransition() target.hits.push({ state: this.currentState , args: args , inputType: 'b' }) return Promise.resolve() .then(this.transition.bind(this,'b')) } } , 'b': { 'b': function(args, target ) { this.deferUntilTransition() target.hits.push({ state: this.currentState , args: args , inputType: 'b' }) return Promise.resolve() .then(this.transition.bind(this,'dob')) } } , 'dob': { 'b': function(args, target) { target.hits.push({ state: this.currentState , args: args , inputType: 'b' }) } } }) .create() return machine.handle('b', { foo: 'bar'}) .then(function(it){ let hits = machine.target().hits assert.equal(machine.currentState,'dob') assert.equal(hits.length, 3) assert.deepEqual(hits[0], { state: 'a' , inputType: 'b' , args: { foo: 'bar'} }) assert.deepEqual(hits[1], { state: 'b' , inputType: 'b' , args: { foo: 'bar'} }) assert.deepEqual(hits[2], { state: 'dob' , inputType: 'b' , args: { foo: 'bar'} }) }) })
//@flow /******************************************************************************* * Imports *******************************************************************************/ import React from "react"; import marked from "marked"; import type { Page } from "tldr/Page"; import { Markdown } from "tldr/components/Markdown"; import Link from "tldr/components/Link"; /******************************************************************************* * Public API *******************************************************************************/ export default ({ body, path }: Page) => ( <section className="content"> <Markdown className="page" body={body} /> <Link href={path} text="Edit this page on Github" /> </section> );
import React, { Component, PropTypes } from 'react'; import { Link, browserHistory } from 'react-router'; import { connect } from 'react-redux'; import { addComment, removeComment } from '../Comment/CommentActions'; import { updateGame } from '../Game/GameActions'; // Import Style import styles from './App.css'; // Import Components import Helmet from 'react-helmet'; import DevTools from './components/DevTools'; import Header from './components/Header/Header'; import Footer from './components/Footer/Footer'; // Import Actions import { toggleAddPost } from './AppActions'; import { switchLanguage } from '../../modules/Intl/IntlActions'; export class App extends Component { constructor(props) { super(props); this.state = { isMounted: false }; } componentDidMount() { this.setState({isMounted: true}); // eslint-disable-line const socket = io.connect(); socket.on('commentAdded', this.commentReceived); socket.on('commentRemoved', this.commentDeleted); socket.on('gameStatusUpdated', this.gameStatusUpdated); } commentReceived = (response) => { this.props.dispatch(addComment(response.comment)); }; commentDeleted = (response) => { this.props.dispatch(removeComment(response.comment)); }; gameStatusUpdated = (response) => { this.props.dispatch(updateGame(response.game)); }; toggleAddPostSection = () => { this.props.dispatch(toggleAddPost()); }; signOut = () => { localStorage.clear(); browserHistory.push('/'); }; render() { return ( <div> {false && this.state.isMounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools />} <div> <Helmet title="Text Broadcast Service" meta={[ { charset: 'utf-8' }, { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge', }, { name: 'viewport', content: 'width=device-width, initial-scale=1', }, ]} /> <div className={styles.container}> <div className={styles.side}></div> <div className={styles.center}> <Header switchLanguage={lang => this.props.dispatch(switchLanguage(lang))} intl={this.props.intl} toggleAddPost={this.toggleAddPostSection} signOut = {this.signOut} /> <div className={styles.container}> {this.props.children} </div> </div> <div className={styles.side}></div> </div> </div> </div> ); } } App.propTypes = { children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; // Retrieve data from store as props function mapStateToProps(store) { return { intl: store.intl, }; } export default connect(mapStateToProps)(App);
var DOCUMENTER_CURRENT_VERSION = "previews/PR99";
$(window).load(function(){ // CREATE RANDOM COLORS ON PROJECT HOVER $('.get-color').hover(function() { var randomcolor = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);}); //console.log(color); //SHOW RANDOM HEX COLOR $('.hover-mask').css({background: [randomcolor]}) }); //END RANDOM COLORS FUNCTION $('#more').hover( function() { $('#about').css({background: 'none'}) }, function() { $('#about').css({background: 'black'}) } ); $('.indiv-project').click(function(e){ e.preventDefault(); var elem = $(this), image = elem.find('.project-image').html(), title = elem.find('.project-title').text(), descr = elem.find('.project-description').html(), elemDataCont = elem.find('.project-description'); $('#project-title').text(title); $('#project-content').html(descr); $('#project-image').html(image); openProject(); }); function openProject(){ $('#project-preview').addClass('open'); //Makes prject div appear $('.container').animate({'opacity':0},300);//Makes projects disappear setTimeout(function(){ $('#project-preview').slideDown(); $('.container').slideUp(); },300); } function closeProject(){ $('#project-preview').removeClass('open'); $('#project-preview').animate({'opacity':0},300); setTimeout(function(){ $('.container').slideDown(); $('#project-preview').slideUp(); $('.container').animate({'opacity':1},300); },300); } $('.close-preview').click(function(){ closeProject(); }) //HIDE PROJECT DIV IF CLICK OUTSIDE PROJECT // function hideDiv(e) { // if (!$(e.target).is('#project-preview') && !$(e.target).parents().is('#project-preview')) { // closeProject(); // // $('#project-preview').hide(); // } // } // $(document).on('click', function(e) { // hideDiv(e); // }); $('#yellowbubble').magnificPopup({ items: { src: '#yellowpiece', type: 'inline' }, closeBtnInside: true }); $('#bluebubble').magnificPopup({ items: { src: '#bluepiece', type: 'inline' }, closeBtnInside: true }); $('#pinkbubble').magnificPopup({ items: { src: '#pinkpiece', type: 'inline' }, closeBtnInside: true }); // $("#question").click(function(){ // $("#answer").slideToggle("fast"); // }); // $("#barcode-desc").click(function(){ // $("#scanner-code").closest($("#barcode-desc")).slideToggle("fast"); // }); // $('#toggle-container h3').each(function() { // var tis = $(this), // state = false, // answer = tis.next('div') // .hide() // .css('height','auto') // .slideUp(); // tis.click(function() { // state = !state; // answer.slideToggle(state); // tis.toggleClass('active',state); // }); // }); //******************************************************* //FINISH LATER IF YOU WANT TO ADD RESUME // $('.resume-link').click(function(e){ // e.preventDefault(); // // var elem = $(this), // // image = elem.find('.resume-image').html(), // // descr = elem.find('.resume-description').html(), // // elemDataCont = elem.find('.resume-description'); // $('#resume-image').html('.resume-image'); // openResume(); // }); // function openResume(){ // $('#resume-preview').addClass('open'); //Makes prject div appear // $('.container').animate({'opacity':0},300);//Makes projects disappear // setTimeout(function(){ // $('#resume-preview').slideDown(); // $('.container').slideUp(); // },300); // } // function closeProject(){ // $('#resume-preview').removeClass('open'); // $('#resume-preview').animate({'opacity':0},300); // setTimeout(function(){ // $('.container').slideDown(); // $('#resume-preview').slideUp(); // $('.container').animate({'opacity':1},300); // },300); // } // $('.close-preview').click(function(){ // closeProject(); // }) });
import 'classnames'; import 'history/createBrowserHistory'; import 'lodash'; import 'marked'; import 'proptypes'; import 'react'; import 'react-dom'; import 'react-helmet'; import 'react-redux'; import 'react-router-dom'; import 'react-router-redux'; import 'redux'; import 'redux-devtools-extension/logOnlyInProduction'; import 'redux-logger'; import 'redux-thunk'; import 'updeep';
(function () { "use strict"; var easm = { registers: { ax: 0, bx: 0, cx: 0, dx: 0 }, stack: [], regPat: /ax|bx|cx|dx/, source: "", init: function () { this.registers.ax = 0; this.registers.bx = 0; this.registers.cx = 0; this.registers.dx = 0; this.stack = []; this.source = ""; }, mov: function (dest, val) { this.registers[dest] = val; }, inc: function (dest) { this.registers[dest] += 1; }, dec: function (dest) { this.registers[dest] -= 1; }, add: function (a, b) { if (b.match(this.regPat)) { this.registers[a] += this.registers[b]; } else { this.registers[a] += Number(b); } }, sub: function (a, b) { if (b.match(this.regPat)) { this.registers[a] -= this.registers[b]; } else { this.registers[a] -= Number(b); } }, mul: function (a, b) { if (b.match(this.regPat)) { this.registers[a] *= this.registers[b]; } else { this.registers[a] *= Number(b); } }, div: function (a, b) { if (b.match(this.regPat)) { this.registers[a] /= this.registers[b]; } else { this.registers[a] /= Number(b); } }, push: function (val) { if (val.match(this.regPat)) { this.stack.push(this.registers[val]); } else { this.stack.push(Number(val)); } }, pop: function (dest) { this.registers[dest] = this.stack.pop(); }, echo: function (rg) { var out = document.getElementById("output"); out.value += this.registers[rg] + "\n"; }, error: function (message, line) { var out = document.getElementById("output"); out.value += "Error at line " + line + ": " + message + "\n"; }, dump: function () { var out = document.getElementById("output"); out.value += "Stack: " + this.stack.join() + "\n"; }, clear: function () { var out = document.getElementById("output"); out.value = ""; }, getSource: function (input) { this.source = input; }, execute: function () { var codeLines = this.source.split("\n"), commandPattern, isCommand, command, operation, a, b; codeLines.forEach(function (currentValue, index, array) { commandPattern = /^([a-z]{3,4})\s+([a-z]{2}),?\s*([a-z0-9]+)?(\s*;[\w\W]*)?$/; isCommand = commandPattern.test(currentValue); if (isCommand) { command = currentValue.match(commandPattern); operation = command[1]; a = command[2]; if (typeof command[3] === "undefined") { b = ""; } else { b = command[3]; } easm.parse(index, operation, a, b); } }); }, parse: function (index, operation, a, b) { switch (operation) { case "mov": this.mov(a, b); break; case "inc": this.inc(a); break; case "dec": this.dec(a); break; case "add": this.add(a, b); break; case "sub": this.sub(a, b); break; case "mul": this.mul(a, b); break; case "div": this.div(a, b); break; case "push": this.push(a); break; case "pop": this.pop(a); break; case "echo": this.echo(a); break; case "dump": this.dump(); break; default: easm.error(operation + " command type not exists, please check manual", index); return; } } }, runBtn = document.getElementById("run"), input = document.getElementById("code"); document.addEventListener("DOMContentLoaded", function (e) { runBtn.addEventListener("click", function (e) { easm.clear(); easm.init(); easm.getSource(input.value); easm.execute(); }); }); }());
function EnviaFormSC() { document.FormMesa.submit(); } function EnviaFormDepar() { document.FormDepar.submit(); } function incrementa(id) { document.getElementById(id).value++; } function decrementa(id) { if(document.getElementById(id).value > 1) document.getElementById(id).value--; } function refresca(seg) { setTimeout('document.location.reload()',seg); } function asigna_valores_iniciales(id){ var ini; ini=document.getElementById(id).value; if (ini==""){ document.getElementById(id).value=0; } } function CargarCosto(){ var val1; var val2; var total; val1=document.getElementById('existencias_edit').value; val2=document.getElementById('costounitario_edit').value; total=val1*val2; document.getElementById('costototal_edit').value=total; } function RepiteFuncion(fun,seg) { setInterval(fun,seg); } function envia(){ if (confirm('¿Estas seguro que deseas registrar este egreso?')){ document.FrmArriendos.submit(); document.FrmArriendos.reset(); } }
/** * Copyright (c) 2017-present, Alejandro Mantilla <@AlejoJamC>. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree or translated in the assets folder. */ /** * Module dependencies. */ var async = require('async'); var logger = require('../utils/logger').logger; var Sensor = require('../models/sensors').Sensor; var Watcherman = require('../models/watchermen').Watcherman; var dweetClient = require('node-dweetio'); var dweetio = new dweetClient(); var twilioClient = require('twilio'); var TwilioAccountSid = process.env.TWILIO_TOKEN_SID; var twilioAuthToken = process.env.TWILIO_TOKEN_AUTH; var twilio = new twilioClient(TwilioAccountSid, twilioAuthToken); // ENDPOINT: /sensors METHOD: GET exports.getSensors = function(req, res) { // Use the 'Sensor' model to find all sensors Sensor.find(function(err, sensors) { // Check for errors and show message if (err) { logger.error(err); return res.json({ message: 'Error trying to list sensors', data: err }); } // success res.status(200).json(sensors); }); }; // ENDPOINT: /sensors/:id METHOD: GET exports.getSensorById = function(req, res) { // Use the 'Sensor' model to find all sensors Sensor.findById(req.params.id, function(err, sensor) { // Check for errors and show message if (err) { logger.error(err); return res.json({ message: 'Error trying to get the sensor information', data: err }); } // success res.status(200).json(sensor); }); }; // ENDPOINT: /sensors METHOD: POST exports.postSensor = function(req, res) { // Create a new instance of the Sensor model var sensor = new Sensor(); var name = req.body.name; var clientId = req.body.clientId; // Parse values to float with 2 decimals var values = {}; var humidity = Number(req.body.values.humidity).toFixed(2); var temperature = Number(req.body.values.temperature).toFixed(2); values.humidity = humidity; values.temperature = temperature; // Set the Sensor properties that came from the POST data sensor.name = name; sensor.values = values; sensor.clientId = clientId; // Calling dweet.io platform dweetio.dweet_for(clientId, {'humidity': humidity, 'temperature': temperature}, function(err, dweet){ logger.info('published in https://dweet.io successfully'); // "my-thing" logger.info(dweet.thing); // "my-thing" logger.info(dweet.content); // The content of the dweet logger.info(dweet.created); // The create date of the dweet }); // Validate max / min humidity and temperature var tempMin = process.env.TEMPERATURE_MIN; var tempMax = process.env.TEMPERATURE_MAX; var humiMin = process.env.HUMIDITY_MIN; var humiMax = process.env.HUMIDITY_MAX; var generateSMS = false; var contentSMS = ''; if(Number(temperature) < Number(tempMin)){ generateSMS = true; contentSMS += 'Alerta de Temperatura Minima (' + tempMin + '), actual: ' + temperature + '. '; } if(Number(temperature) > Number(tempMax)){ generateSMS = true; contentSMS += 'Alterta de Temperatura Maxima (' + tempMax + '), actual: ' + temperature + '. '; } if(Number(humidity) < Number(humiMin)){ generateSMS = true; contentSMS += 'Alerta de Humedad Minima (' + humiMin + '), actual: ' + humidity + '. '; } if(Number(humidity) > Number(humiMax)){ generateSMS = true; contentSMS += 'Alerta de Humedad Maxima (' + humiMax + '), actual: ' + humidity + '. '; } logger.info(contentSMS); // Send SMS twilio if(generateSMS){ // Get list of phone numbers to Watcherman.find(function(err, watchermen) { // Check for errors and show message if (err) { logger.error(err); return res.json({ message: 'Error trying to list watchermen', data: err }); } // success logger.info(JSON.stringify(watchermen)); if(watchermen.length > 0){ async.forEach(watchermen, function (watcherman, callback) { // validate if have to send sms message if(watcherman.sms){ var phone = '+57 ' + watcherman.mobile; logger.info(phone); twilio.messages.create({ to: phone, from: process.env.DEFAULT_FROM_MOBILE, body: contentSMS }, callback); } // validate if needs to generate a voice message if(watcherman.voice){ } }, function (err) { if (err) { logger.error(err); return res.json({ message: 'Error send twilio sms message', data: err }); } // Success return res.status(200).send('SMS send successfully'); }); } }); } sensor.save(function(err) { // Check for errors and show message if (err) { logger.error(err); return res.json({ message: 'Error trying to create a new sensor', data: err }); } //Success res.status(200).json({ message: 'Sensor created successfully!', data: sensor }); }); }; // ENDPOINT: /sensors/voice METHOD: POST exports.postVoiceMessage = function (req, res) { var toNumber = '+57' + req.body.to; var urlMessage = req.body.url; logger.info(toNumber); logger.info(urlMessage); twilio.calls.create({ url: urlMessage, to: toNumber, from: process.env.DEFAULT_FROM_MOBILE }, function(err, call) { if(err){ logger.info(err); return res.status(400).send('Error haciendo llamada al # ' + toNumber); } logger.info(call.sid); return res.status(200).send('Llamada exitosa al # ' + toNumber); }); }; // ENDPOINT: /sensors/:id METHOD: PUT exports.putSensor = function(req, res) { Sensor.findById(req.params.id, function(err, sensor) { // Check for errors and show message if (err) { logger.error(err); return res.json(err); } // Set the Sensor properties that came from the PUT data sensor.name = req.body.name; sensor.values = req.body.values; sensor.clientId = req.body.clientId; sensor.save(function(err) { // Check for errors and show message if (err) { logger.error(err); return res.json({ message: 'Error trying to update sensor information', data: err }); } // success res.status(200).json({ message: 'Sensor updated successfully', data: sensor }); }); }); }; // ENDPOINT: /sensors/:id METHOD: DELETE exports.deleteSensor = function(req, res) { Sensor.findByIdAndRemove(req.params.id, function(err) { // Check for errors and show message if (err) { logger.error(err); return res.json({ message: 'Error trying to delete sensor information', data: err }); } // success res.status(200).json({ message: 'Sensor deleted successfully!' }); }); };
jQuery(document).ready(function ($) { $("a.trigger").click(function (event) { event.preventDefault(); linkLocation = $(this).attr("href");; console.log(linkLocation); $("body").fadeOut(1000, redirectPage); }); function redirectPage() { console.log(linkLocation); window.location = linkLocation; } initSelectedNav(); //toggle 3d navigation $('.cd-3d-nav-trigger').on('click', function () { toggle3dBlock(!$('.cd-header').hasClass('nav-is-visible')); }); //select a new item from the 3d navigation $('.cd-3d-nav').on('click', 'a', function () { var selected = $(this); selected.parent('li').addClass('cd-selected').siblings('li').removeClass('cd-selected'); updateSelectedNav('close'); }); $(window).on('resize', function () { window.requestAnimationFrame(updateSelectedNav); }); function toggle3dBlock(addOrRemove) { if (typeof (addOrRemove) === 'undefined') addOrRemove = true; $('.cd-header').toggleClass('nav-is-visible', addOrRemove); $('.cd-3d-nav-container').toggleClass('nav-is-visible', addOrRemove); $('#content').toggleClass('nav-is-visible', addOrRemove).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () { //fix marker position when opening the menu (after a window resize) addOrRemove && updateSelectedNav(); }); } function initSelectedNav() { var path = window.location.pathname; $('.cd-3d-nav li a').each(function () { if (this.getAttribute('href') == path) { $(this).parent().toggleClass('cd-selected'); window.requestAnimationFrame(updateSelectedNav); return; } }) }; //this function update the .cd-marker position function updateSelectedNav(type) { var selectedItem = $('.cd-selected'), selectedItemPosition = selectedItem.index() + 1, leftPosition = selectedItem.offset().left, backgroundColor = selectedItem.data('color'), marker = $('.cd-marker'); marker.removeClassPrefix('color').addClass('color-' + selectedItemPosition).css({ 'left': leftPosition, }); if (type == 'close') { marker.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () { toggle3dBlock(false); }); } } $.fn.removeClassPrefix = function (prefix) { this.each(function (i, el) { var classes = el.className.split(" ").filter(function (c) { return c.lastIndexOf(prefix, 0) !== 0; }); el.className = $.trim(classes.join(" ")); }); return this; }; });
'use strict' const path = require('path') module.exports = (filePath) => { const extname = path.extname(filePath) switch (extname) { case '.jpeg': return 'jpeg' case '.jpg': return 'jpg' case '.jpe': return 'jpeg' case '.png': return 'png' case '.webp': return 'webp' default: return 'unsupported' } }
import { connect } from 'react-redux'; import forEach from 'lodash/forEach'; import { fetchPosts } from 'src/actions'; export default connect( state => ({ sources: state.qus[state.selectedQu].sources, }), dispatch => ({ dispatch, }), ({ selectedQu, sources }, { dispatch }) => ({ refresh: () => { forEach(sources, (source) => { dispatch(fetchPosts(source)); }); }, }) );
const _ = require('./utils'); // Enable followers-only mode on a channel.. function followersonly(channel, minutes) { channel = _.channel(channel); minutes = _.get(minutes, 30); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/followers ${minutes}`, (resolve, reject) => { // Received _promiseFollowers event, resolve or reject.. this.once('_promiseFollowers', err => { if(!err) { resolve([ channel, ~~minutes ]); } else { reject(err); } }); }); } // Disable followers-only mode on a channel.. function followersonlyoff(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/followersoff', (resolve, reject) => { // Received _promiseFollowersoff event, resolve or reject.. this.once('_promiseFollowersoff', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); } // Leave a channel.. function part(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), null, `PART ${channel}`, (resolve, reject) => { // Received _promisePart event, resolve or reject.. this.once('_promisePart', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); } // Enable R9KBeta mode on a channel.. function r9kbeta(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/r9kbeta', (resolve, reject) => { // Received _promiseR9kbeta event, resolve or reject.. this.once('_promiseR9kbeta', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); } // Disable R9KBeta mode on a channel.. function r9kbetaoff(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/r9kbetaoff', (resolve, reject) => { // Received _promiseR9kbetaoff event, resolve or reject.. this.once('_promiseR9kbetaoff', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); } // Enable slow mode on a channel.. function slow(channel, seconds) { channel = _.channel(channel); seconds = _.get(seconds, 300); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/slow ${seconds}`, (resolve, reject) => { // Received _promiseSlow event, resolve or reject.. this.once('_promiseSlow', err => { if(!err) { resolve([ channel, ~~seconds ]); } else { reject(err); } }); }); } // Disable slow mode on a channel.. function slowoff(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/slowoff', (resolve, reject) => { // Received _promiseSlowoff event, resolve or reject.. this.once('_promiseSlowoff', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); } module.exports = { // Send action message (/me <message>) on a channel.. action(channel, message) { channel = _.channel(channel); message = `\u0001ACTION ${message}\u0001`; // Send the command to the server and race the Promise against a delay.. return this._sendMessage(this._getPromiseDelay(), channel, message, (resolve, _reject) => { // At this time, there is no possible way to detect if a message has been sent has been eaten // by the server, so we can only resolve the Promise. resolve([ channel, message ]); }); }, // Ban username on channel.. ban(channel, username, reason) { channel = _.channel(channel); username = _.username(username); reason = _.get(reason, ''); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/ban ${username} ${reason}`, (resolve, reject) => { // Received _promiseBan event, resolve or reject.. this.once('_promiseBan', err => { if(!err) { resolve([ channel, username, reason ]); } else { reject(err); } }); }); }, // Clear all messages on a channel.. clear(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/clear', (resolve, reject) => { // Received _promiseClear event, resolve or reject.. this.once('_promiseClear', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); }, // Change the color of your username.. color(channel, newColor) { newColor = _.get(newColor, channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), '#tmijs', `/color ${newColor}`, (resolve, reject) => { // Received _promiseColor event, resolve or reject.. this.once('_promiseColor', err => { if(!err) { resolve([ newColor ]); } else { reject(err); } }); }); }, // Run commercial on a channel for X seconds.. commercial(channel, seconds) { channel = _.channel(channel); seconds = _.get(seconds, 30); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/commercial ${seconds}`, (resolve, reject) => { // Received _promiseCommercial event, resolve or reject.. this.once('_promiseCommercial', err => { if(!err) { resolve([ channel, ~~seconds ]); } else { reject(err); } }); }); }, // Delete a specific message on a channel deletemessage(channel, messageUUID) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/delete ${messageUUID}`, (resolve, reject) => { // Received _promiseDeletemessage event, resolve or reject.. this.once('_promiseDeletemessage', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); }, // Enable emote-only mode on a channel.. emoteonly(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/emoteonly', (resolve, reject) => { // Received _promiseEmoteonly event, resolve or reject.. this.once('_promiseEmoteonly', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); }, // Disable emote-only mode on a channel.. emoteonlyoff(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/emoteonlyoff', (resolve, reject) => { // Received _promiseEmoteonlyoff event, resolve or reject.. this.once('_promiseEmoteonlyoff', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); }, // Enable followers-only mode on a channel.. followersonly: followersonly, // Alias for followersonly().. followersmode: followersonly, // Disable followers-only mode on a channel.. followersonlyoff: followersonlyoff, // Alias for followersonlyoff().. followersmodeoff: followersonlyoff, // Host a channel.. host(channel, target) { channel = _.channel(channel); target = _.username(target); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(2000, channel, `/host ${target}`, (resolve, reject) => { // Received _promiseHost event, resolve or reject.. this.once('_promiseHost', (err, remaining) => { if(!err) { resolve([ channel, target, ~~remaining ]); } else { reject(err); } }); }); }, // Join a channel.. join(channel) { channel = _.channel(channel); // Send the command to the server .. return this._sendCommand(null, null, `JOIN ${channel}`, (resolve, reject) => { const eventName = '_promiseJoin'; let hasFulfilled = false; const listener = (err, joinedChannel) => { if(channel === _.channel(joinedChannel)) { // Received _promiseJoin event for the target channel, resolve or reject.. this.removeListener(eventName, listener); hasFulfilled = true; if(!err) { resolve([ channel ]); } else { reject(err); } } }; this.on(eventName, listener); // Race the Promise against a delay.. const delay = this._getPromiseDelay(); _.promiseDelay(delay).then(() => { if(!hasFulfilled) { this.emit(eventName, 'No response from Twitch.', channel); } }); }); }, // Mod username on channel.. mod(channel, username) { channel = _.channel(channel); username = _.username(username); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/mod ${username}`, (resolve, reject) => { // Received _promiseMod event, resolve or reject.. this.once('_promiseMod', err => { if(!err) { resolve([ channel, username ]); } else { reject(err); } }); }); }, // Get list of mods on a channel.. mods(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/mods', (resolve, reject) => { // Received _promiseMods event, resolve or reject.. this.once('_promiseMods', (err, mods) => { if(!err) { // Update the internal list of moderators.. mods.forEach(username => { if(!this.moderators[channel]) { this.moderators[channel] = []; } if(!this.moderators[channel].includes(username)) { this.moderators[channel].push(username); } }); resolve(mods); } else { reject(err); } }); }); }, // Leave a channel.. part: part, // Alias for part().. leave: part, // Send a ping to the server.. ping() { // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), null, 'PING', (resolve, _reject) => { // Update the internal ping timeout check interval.. this.latency = new Date(); this.pingTimeout = setTimeout(() => { if(this.ws !== null) { this.wasCloseCalled = false; this.log.error('Ping timeout.'); this.ws.close(); clearInterval(this.pingLoop); clearTimeout(this.pingTimeout); } }, _.get(this.opts.connection.timeout, 9999)); // Received _promisePing event, resolve or reject.. this.once('_promisePing', latency => resolve([ parseFloat(latency) ])); }); }, // Enable R9KBeta mode on a channel.. r9kbeta: r9kbeta, // Alias for r9kbeta().. r9kmode: r9kbeta, // Disable R9KBeta mode on a channel.. r9kbetaoff: r9kbetaoff, // Alias for r9kbetaoff().. r9kmodeoff: r9kbetaoff, // Send a raw message to the server.. raw(message) { // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), null, message, (resolve, _reject) => { resolve([ message ]); }); }, // Send a message on a channel.. say(channel, message) { channel = _.channel(channel); if((message.startsWith('.') && !message.startsWith('..')) || message.startsWith('/') || message.startsWith('\\')) { // Check if the message is an action message.. if(message.substr(1, 3) === 'me ') { return this.action(channel, message.substr(4)); } else { // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, message, (resolve, _reject) => { // At this time, there is no possible way to detect if a message has been sent has been eaten // by the server, so we can only resolve the Promise. resolve([ channel, message ]); }); } } // Send the command to the server and race the Promise against a delay.. return this._sendMessage(this._getPromiseDelay(), channel, message, (resolve, _reject) => { // At this time, there is no possible way to detect if a message has been sent has been eaten // by the server, so we can only resolve the Promise. resolve([ channel, message ]); }); }, // Enable slow mode on a channel.. slow: slow, // Alias for slow().. slowmode: slow, // Disable slow mode on a channel.. slowoff: slowoff, // Alias for slowoff().. slowmodeoff: slowoff, // Enable subscribers mode on a channel.. subscribers(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/subscribers', (resolve, reject) => { // Received _promiseSubscribers event, resolve or reject.. this.once('_promiseSubscribers', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); }, // Disable subscribers mode on a channel.. subscribersoff(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/subscribersoff', (resolve, reject) => { // Received _promiseSubscribersoff event, resolve or reject.. this.once('_promiseSubscribersoff', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); }, // Timeout username on channel for X seconds.. timeout(channel, username, seconds, reason) { channel = _.channel(channel); username = _.username(username); if(seconds !== null && !_.isInteger(seconds)) { reason = seconds; seconds = 300; } seconds = _.get(seconds, 300); reason = _.get(reason, ''); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/timeout ${username} ${seconds} ${reason}`, (resolve, reject) => { // Received _promiseTimeout event, resolve or reject.. this.once('_promiseTimeout', err => { if(!err) { resolve([ channel, username, ~~seconds, reason ]); } else { reject(err); } }); }); }, // Unban username on channel.. unban(channel, username) { channel = _.channel(channel); username = _.username(username); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/unban ${username}`, (resolve, reject) => { // Received _promiseUnban event, resolve or reject.. this.once('_promiseUnban', err => { if(!err) { resolve([ channel, username ]); } else { reject(err); } }); }); }, // End the current hosting.. unhost(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(2000, channel, '/unhost', (resolve, reject) => { // Received _promiseUnhost event, resolve or reject.. this.once('_promiseUnhost', err => { if(!err) { resolve([ channel ]); } else { reject(err); } }); }); }, // Unmod username on channel.. unmod(channel, username) { channel = _.channel(channel); username = _.username(username); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/unmod ${username}`, (resolve, reject) => { // Received _promiseUnmod event, resolve or reject.. this.once('_promiseUnmod', err => { if(!err) { resolve([ channel, username ]); } else { reject(err); } }); }); }, // Unvip username on channel.. unvip(channel, username) { channel = _.channel(channel); username = _.username(username); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/unvip ${username}`, (resolve, reject) => { // Received _promiseUnvip event, resolve or reject.. this.once('_promiseUnvip', err => { if(!err) { resolve([ channel, username ]); } else { reject(err); } }); }); }, // Add username to VIP list on channel.. vip(channel, username) { channel = _.channel(channel); username = _.username(username); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, `/vip ${username}`, (resolve, reject) => { // Received _promiseVip event, resolve or reject.. this.once('_promiseVip', err => { if(!err) { resolve([ channel, username ]); } else { reject(err); } }); }); }, // Get list of VIPs on a channel.. vips(channel) { channel = _.channel(channel); // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), channel, '/vips', (resolve, reject) => { // Received _promiseVips event, resolve or reject.. this.once('_promiseVips', (err, vips) => { if(!err) { resolve(vips); } else { reject(err); } }); }); }, // Send an whisper message to a user.. whisper(username, message) { username = _.username(username); // The server will not send a whisper to the account that sent it. if(username === this.getUsername()) { return Promise.reject('Cannot send a whisper to the same account.'); } // Send the command to the server and race the Promise against a delay.. return this._sendCommand(this._getPromiseDelay(), '#tmijs', `/w ${username} ${message}`, (_resolve, reject) => { this.once('_promiseWhisper', err => { if (err) { reject(err); } }); }).catch(err => { // Either an "actual" error occured or the timeout triggered // the latter means no errors have occured and we can resolve // else just elevate the error if(err && typeof err === 'string' && err.indexOf('No response from Twitch.') !== 0) { throw err; } const from = _.channel(username); const userstate = Object.assign({ 'message-type': 'whisper', 'message-id': null, 'thread-id': null, username: this.getUsername() }, this.globaluserstate); // Emit for both, whisper and message.. this.emits([ 'whisper', 'message' ], [ [ from, userstate, message, true ], [ from, userstate, message, true ] ]); return [ username, message ]; }); } };
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.imgs2file = { setUp: function (done) { // setup here if necessary done(); }, default_options: function (test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function (test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.ActionSelect. sap.ui.define(['jquery.sap.global', './Select', './library'], function(jQuery, Select, library) { "use strict"; /** * Constructor for a new ActionSelect. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * The ActionSelect control provides a list of predefined items that allows end users to choose options and additionally trigger some actions. * @extends sap.m.Select * * @author SAP SE * @version 1.26.8 * * @constructor * @public * @since 1.16 * @alias sap.m.ActionSelect * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ActionSelect = Select.extend("sap.m.ActionSelect", /** @lends sap.m.ActionSelect.prototype */ { metadata : { library : "sap.m", associations : { /** * Buttons to be added to the ActionSelect content. */ buttons : {type : "sap.m.Button", multiple : true, singularName : "button"} } }}); ActionSelect.prototype.init = function() { Select.prototype.init.call(this); this.getList().addEventDelegate({ onfocusin: this.onfocusinList }, this); }; /* =========================================================== */ /* Internal methods and properties */ /* =========================================================== */ /* ----------------------------------------------------------- */ /* Private methods */ /* ----------------------------------------------------------- */ /** * Determines whether the ActionSelect has content or not. * * @return {boolean} * @override * @private */ ActionSelect.prototype.hasContent = function() { return Select.prototype.hasContent.call(this) || !!this.getButtons().length; }; /** * Add additional content. * * @override * @private */ ActionSelect.prototype.addContent = function() { var oCore = sap.ui.getCore(), oPicker = this.getPicker(); this.getButtons().forEach(function(sButtonId) { oPicker.addContent(oCore.byId(sButtonId)); }); }; /* =========================================================== */ /* Lifecycle methods */ /* =========================================================== */ /** * Called after the ActionSelect picker pop-up is render. * * @override * @protected */ ActionSelect.prototype.onAfterRenderingPicker = function() { Select.prototype.onAfterRenderingPicker.call(this); this.getPicker().addStyleClass(sap.m.ActionSelectRenderer.CSS_CLASS + "Picker"); }; /* =========================================================== */ /* API methods */ /* =========================================================== */ /* ----------------------------------------------------------- */ /* Public methods */ /* ----------------------------------------------------------- */ /** * Button to be removed from the ActionSelect content. * * @param {int | string | sap.m.Button} vButton The button to remove or its index or id. * @returns {string} The id of the removed button or null. * @public */ ActionSelect.prototype.removeButton = function(vButton) { var oPicker = this.getPicker(); if (oPicker) { if (typeof vButton === "number") { vButton = this.getButtons()[vButton]; } oPicker.removeContent(vButton); } return this.removeAssociation("buttons", vButton); }; /** * Remove all buttons from the ActionSelect. * * @returns {string[]} An array with the ids of the removed elements (might be empty). * @public */ ActionSelect.prototype.removeAllButtons = function() { var oPicker = this.getPicker(); if (oPicker) { this.getButtons().forEach(function(sButtonId) { oPicker.removeContent(sButtonId); }); } return this.removeAllAssociation("buttons"); }; //Keyboard Navigation for Action buttons /** * Handler for SHIFT-TAB key - 'tab previous' sap ui5 key event. * * @param oEvent - key event * @private * */ ActionSelect.prototype.onsaptabprevious = function(oEvent) { // check whether event is marked or not if ( oEvent.isMarked() || !this.getEnabled()) { return; } // mark the event for components that needs to know if the event was handled oEvent.setMarked(); var aButtons = this.getButtons(); var oPicker = this.getPicker(); if (oPicker && oPicker.isOpen() && aButtons.length > 0) { sap.ui.getCore().byId(aButtons[aButtons.length - 1]).focus(); oEvent.preventDefault(); } }; /** * Handler for TAB key - sap 'tab next' key event. * * @param oEvent - key event * @private * */ ActionSelect.prototype.onsaptabnext = function(oEvent) { // check whether event is marked or not if ( oEvent.isMarked() || !this.getEnabled()) { return; } // mark the event for components that needs to know if the event was handled oEvent.setMarked(); var aButtons = this.getButtons(); var oPicker = this.getPicker(); if (oPicker && oPicker.isOpen() && aButtons.length > 0) { sap.ui.getCore().byId(aButtons[0]).focus(); oEvent.preventDefault(); } }; /** * Handle the focus leave event. * * @param {jQuery.Event} oEvent The event object. * @private */ ActionSelect.prototype.onsapfocusleave = function(oEvent) { // Keep focus on Action Select's input field if does not go to // the buttons in Action sheet part of the ActionSelect var aButtons = this.getButtons(); var bKeepFocus = (aButtons.indexOf(oEvent.relatedControlId) == -1); if (bKeepFocus) { Select.prototype.onsapfocusleave.apply(this, arguments); } }; /** * Handler for focus in event on The Selection List. * * @param oEvent - key event * @private */ ActionSelect.prototype.onfocusinList = function(oEvent) { if (document.activeElement !== this.getList().getDomRef()) { this.focus(); } }; return ActionSelect; }, /* bExport= */ true);
import {dirname} from 'node:path'; import {fileURLToPath} from 'node:url'; import buildParserOptions from 'minimist-options'; import parseArguments from 'yargs-parser'; import camelCaseKeys from 'camelcase-keys'; import decamelize from 'decamelize'; import decamelizeKeys from 'decamelize-keys'; import trimNewlines from 'trim-newlines'; import redent from 'redent'; import {readPackageUpSync} from 'read-pkg-up'; import hardRejection from 'hard-rejection'; import normalizePackageData from 'normalize-package-data'; const isFlagMissing = (flagName, definedFlags, receivedFlags, input) => { const flag = definedFlags[flagName]; let isFlagRequired = true; if (typeof flag.isRequired === 'function') { isFlagRequired = flag.isRequired(receivedFlags, input); if (typeof isFlagRequired !== 'boolean') { throw new TypeError(`Return value for isRequired callback should be of type boolean, but ${typeof isFlagRequired} was returned.`); } } if (typeof receivedFlags[flagName] === 'undefined') { return isFlagRequired; } return flag.isMultiple && receivedFlags[flagName].length === 0 && isFlagRequired; }; const getMissingRequiredFlags = (flags, receivedFlags, input) => { const missingRequiredFlags = []; if (typeof flags === 'undefined') { return []; } for (const flagName of Object.keys(flags)) { if (flags[flagName].isRequired && isFlagMissing(flagName, flags, receivedFlags, input)) { missingRequiredFlags.push({key: flagName, ...flags[flagName]}); } } return missingRequiredFlags; }; const reportMissingRequiredFlags = missingRequiredFlags => { console.error(`Missing required flag${missingRequiredFlags.length > 1 ? 's' : ''}`); for (const flag of missingRequiredFlags) { console.error(`\t--${decamelize(flag.key, {separator: '-'})}${flag.alias ? `, -${flag.alias}` : ''}`); } }; const validateOptions = ({flags}) => { const invalidFlags = Object.keys(flags).filter(flagKey => flagKey.includes('-') && flagKey !== '--'); if (invalidFlags.length > 0) { throw new Error(`Flag keys may not contain '-': ${invalidFlags.join(', ')}`); } }; const reportUnknownFlags = unknownFlags => { console.error([ `Unknown flag${unknownFlags.length > 1 ? 's' : ''}`, ...unknownFlags, ].join('\n')); }; const buildParserFlags = ({flags, booleanDefault}) => { const parserFlags = {}; for (const [flagKey, flagValue] of Object.entries(flags)) { const flag = {...flagValue}; if ( typeof booleanDefault !== 'undefined' && flag.type === 'boolean' && !Object.prototype.hasOwnProperty.call(flag, 'default') ) { flag.default = flag.isMultiple ? [booleanDefault] : booleanDefault; } if (flag.isMultiple) { flag.type = flag.type ? `${flag.type}-array` : 'array'; flag.default = flag.default || []; delete flag.isMultiple; } parserFlags[flagKey] = flag; } return parserFlags; }; const validateFlags = (flags, options) => { for (const [flagKey, flagValue] of Object.entries(options.flags)) { if (flagKey !== '--' && !flagValue.isMultiple && Array.isArray(flags[flagKey])) { throw new Error(`The flag --${flagKey} can only be set once.`); } } }; const meow = (helpText, options = {}) => { if (typeof helpText !== 'string') { options = helpText; helpText = ''; } if (!(options.importMeta && options.importMeta.url)) { throw new TypeError('The `importMeta` option is required. Its value must be `import.meta`.'); } const foundPackage = readPackageUpSync({ cwd: dirname(fileURLToPath(options.importMeta.url)), normalize: false, }); options = { pkg: foundPackage ? foundPackage.packageJson : {}, argv: process.argv.slice(2), flags: {}, inferType: false, input: 'string', help: helpText, autoHelp: true, autoVersion: true, booleanDefault: false, hardRejection: true, allowUnknownFlags: true, ...options, }; if (options.hardRejection) { hardRejection(); } validateOptions(options); let parserOptions = { arguments: options.input, ...buildParserFlags(options), }; parserOptions = decamelizeKeys(parserOptions, '-', {exclude: ['stopEarly', '--']}); if (options.inferType) { delete parserOptions.arguments; } parserOptions = buildParserOptions(parserOptions); parserOptions.configuration = { ...parserOptions.configuration, 'greedy-arrays': false, }; if (parserOptions['--']) { parserOptions.configuration['populate--'] = true; } if (!options.allowUnknownFlags) { // Collect unknown options in `argv._` to be checked later. parserOptions.configuration['unknown-options-as-args'] = true; } const {pkg: package_} = options; const argv = parseArguments(options.argv, parserOptions); let help = redent(trimNewlines((options.help || '').replace(/\t+\n*$/, '')), 2); normalizePackageData(package_); process.title = package_.bin ? Object.keys(package_.bin)[0] : package_.name; let {description} = options; if (!description && description !== false) { ({description} = package_); } help = (description ? `\n ${description}\n` : '') + (help ? `\n${help}\n` : '\n'); const showHelp = code => { console.log(help); process.exit(typeof code === 'number' ? code : 2); }; const showVersion = () => { console.log(typeof options.version === 'string' ? options.version : package_.version); process.exit(0); }; if (argv._.length === 0 && options.argv.length === 1) { if (argv.version === true && options.autoVersion) { showVersion(); } else if (argv.help === true && options.autoHelp) { showHelp(0); } } const input = argv._; delete argv._; if (!options.allowUnknownFlags) { const unknownFlags = input.filter(item => typeof item === 'string' && item.startsWith('-')); if (unknownFlags.length > 0) { reportUnknownFlags(unknownFlags); process.exit(2); } } const flags = camelCaseKeys(argv, {exclude: ['--', /^\w$/]}); const unnormalizedFlags = {...flags}; validateFlags(flags, options); for (const flagValue of Object.values(options.flags)) { delete flags[flagValue.alias]; } const missingRequiredFlags = getMissingRequiredFlags(options.flags, flags, input); if (missingRequiredFlags.length > 0) { reportMissingRequiredFlags(missingRequiredFlags); process.exit(2); } return { input, flags, unnormalizedFlags, pkg: package_, help, showHelp, showVersion, }; }; export default meow;
/*! p5.sound.js v0.3.0 2016-01-31 */ (function (root, factory) { if (typeof define === 'function' && define.amd) define('p5.sound', ['HW0/02-bar clock/libraries/p5'], function (p5) { (factory(p5));}); else if (typeof exports === 'object') factory(require('../p5')); else factory(root['p5']); }(this, function (p5) { /** * p5.sound extends p5 with <a href="http://caniuse.com/audio-api" * target="_blank">Web Audio</a> functionality including audio input, * playback, analysis and synthesis. * <br/><br/> * <a href="#/p5.SoundFile"><b>p5.SoundFile</b></a>: Load and play sound files.<br/> * <a href="#/p5.Amplitude"><b>p5.Amplitude</b></a>: Get the current volume of a sound.<br/> * <a href="#/p5.AudioIn"><b>p5.AudioIn</b></a>: Get sound from an input source, typically * a computer microphone.<br/> * <a href="#/p5.FFT"><b>p5.FFT</b></a>: Analyze the frequency of sound. Returns * results from the frequency spectrum or time domain (waveform).<br/> * <a href="#/p5.Oscillator"><b>p5.Oscillator</b></a>: Generate Sine, * Triangle, Square and Sawtooth waveforms. Base class of * <a href="#/p5.Noise">p5.Noise</a> and <a href="#/p5.Pulse">p5.Pulse</a>. * <br/> * <a href="#/p5.Env"><b>p5.Env</b></a>: An Envelope is a series * of fades over time. Often used to control an object's * output gain level as an "ADSR Envelope" (Attack, Decay, * Sustain, Release). Can also modulate other parameters.<br/> * <a href="#/p5.Delay"><b>p5.Delay</b></a>: A delay effect with * parameters for feedback, delayTime, and lowpass filter.<br/> * <a href="#/p5.Filter"><b>p5.Filter</b></a>: Filter the frequency range of a * sound. * <br/> * <a href="#/p5.Reverb"><b>p5.Reverb</b></a>: Add reverb to a sound by specifying * duration and decay. <br/> * <b><a href="#/p5.Convolver">p5.Convolver</a>:</b> Extends * <a href="#/p5.Reverb">p5.Reverb</a> to simulate the sound of real * physical spaces through convolution.<br/> * <b><a href="#/p5.SoundRecorder">p5.SoundRecorder</a></b>: Record sound for playback * / save the .wav file. * <b><a href="#/p5.Phrase">p5.Phrase</a></b>, <b><a href="#/p5.Part">p5.Part</a></b> and * <b><a href="#/p5.Score">p5.Score</a></b>: Compose musical sequences. * <br/><br/> * p5.sound is on <a href="https://github.com/therewasaguy/p5.sound/">GitHub</a>. * Download the latest version * <a href="https://github.com/therewasaguy/p5.sound/blob/master/lib/p5.sound.js">here</a>. * * @module p5.sound * @submodule p5.sound * @for p5.sound * @main */ /** * p5.sound developed by Jason Sigal for the Processing Foundation, Google Summer of Code 2014. The MIT License (MIT). * * http://github.com/therewasaguy/p5.sound * * Some of the many audio libraries & resources that inspire p5.sound: * - TONE.js (c) Yotam Mann, 2014. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js * - buzz.js (c) Jay Salvat, 2013. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/ * - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0 * - wavesurfer.js https://github.com/katspaugh/wavesurfer.js * - Web Audio Components by Jordan Santell https://github.com/web-audio-components * - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound * * Web Audio API: http://w3.org/TR/webaudio/ */ var sndcore; sndcore = function () { 'use strict'; /* AudioContext Monkeypatch Copyright 2013 Chris Wilson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function (global, exports, perf) { exports = exports || {}; 'use strict'; function fixSetTarget(param) { if (!param) // if NYI, just return return; if (!param.setTargetAtTime) param.setTargetAtTime = param.setTargetValueAtTime; } if (window.hasOwnProperty('webkitAudioContext') && !window.hasOwnProperty('AudioContext')) { window.AudioContext = webkitAudioContext; if (!AudioContext.prototype.hasOwnProperty('createGain')) AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; if (!AudioContext.prototype.hasOwnProperty('createDelay')) AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; if (!AudioContext.prototype.hasOwnProperty('createScriptProcessor')) AudioContext.prototype.createScriptProcessor = AudioContext.prototype.createJavaScriptNode; if (!AudioContext.prototype.hasOwnProperty('createPeriodicWave')) AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; AudioContext.prototype.internal_createGain = AudioContext.prototype.createGain; AudioContext.prototype.createGain = function () { var node = this.internal_createGain(); fixSetTarget(node.gain); return node; }; AudioContext.prototype.internal_createDelay = AudioContext.prototype.createDelay; AudioContext.prototype.createDelay = function (maxDelayTime) { var node = maxDelayTime ? this.internal_createDelay(maxDelayTime) : this.internal_createDelay(); fixSetTarget(node.delayTime); return node; }; AudioContext.prototype.internal_createBufferSource = AudioContext.prototype.createBufferSource; AudioContext.prototype.createBufferSource = function () { var node = this.internal_createBufferSource(); if (!node.start) { node.start = function (when, offset, duration) { if (offset || duration) this.noteGrainOn(when || 0, offset, duration); else this.noteOn(when || 0); }; } else { node.internal_start = node.start; node.start = function (when, offset, duration) { if (typeof duration !== 'undefined') node.internal_start(when || 0, offset, duration); else node.internal_start(when || 0, offset || 0); }; } if (!node.stop) { node.stop = function (when) { this.noteOff(when || 0); }; } else { node.internal_stop = node.stop; node.stop = function (when) { node.internal_stop(when || 0); }; } fixSetTarget(node.playbackRate); return node; }; AudioContext.prototype.internal_createDynamicsCompressor = AudioContext.prototype.createDynamicsCompressor; AudioContext.prototype.createDynamicsCompressor = function () { var node = this.internal_createDynamicsCompressor(); fixSetTarget(node.threshold); fixSetTarget(node.knee); fixSetTarget(node.ratio); fixSetTarget(node.reduction); fixSetTarget(node.attack); fixSetTarget(node.release); return node; }; AudioContext.prototype.internal_createBiquadFilter = AudioContext.prototype.createBiquadFilter; AudioContext.prototype.createBiquadFilter = function () { var node = this.internal_createBiquadFilter(); fixSetTarget(node.frequency); fixSetTarget(node.detune); fixSetTarget(node.Q); fixSetTarget(node.gain); return node; }; if (AudioContext.prototype.hasOwnProperty('createOscillator')) { AudioContext.prototype.internal_createOscillator = AudioContext.prototype.createOscillator; AudioContext.prototype.createOscillator = function () { var node = this.internal_createOscillator(); if (!node.start) { node.start = function (when) { this.noteOn(when || 0); }; } else { node.internal_start = node.start; node.start = function (when) { node.internal_start(when || 0); }; } if (!node.stop) { node.stop = function (when) { this.noteOff(when || 0); }; } else { node.internal_stop = node.stop; node.stop = function (when) { node.internal_stop(when || 0); }; } if (!node.setPeriodicWave) node.setPeriodicWave = node.setWaveTable; fixSetTarget(node.frequency); fixSetTarget(node.detune); return node; }; } } if (window.hasOwnProperty('webkitOfflineAudioContext') && !window.hasOwnProperty('OfflineAudioContext')) { window.OfflineAudioContext = webkitOfflineAudioContext; } return exports; }(window)); // <-- end MonkeyPatch. // Create the Audio Context var audiocontext = new window.AudioContext(); /** * <p>Returns the Audio Context for this sketch. Useful for users * who would like to dig deeper into the <a target='_blank' href= * 'http://webaudio.github.io/web-audio-api/'>Web Audio API * </a>.</p> * * @method getAudioContext * @return {Object} AudioContext for this sketch */ p5.prototype.getAudioContext = function () { return audiocontext; }; // Polyfill for AudioIn, also handled by p5.dom createCapture navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; /** * Determine which filetypes are supported (inspired by buzz.js) * The audio element (el) will only be used to test browser support for various audio formats */ var el = document.createElement('audio'); p5.prototype.isSupported = function () { return !!el.canPlayType; }; var isOGGSupported = function () { return !!el.canPlayType && el.canPlayType('audio/ogg; codecs="vorbis"'); }; var isMP3Supported = function () { return !!el.canPlayType && el.canPlayType('audio/mpeg;'); }; var isWAVSupported = function () { return !!el.canPlayType && el.canPlayType('audio/wav; codecs="1"'); }; var isAACSupported = function () { return !!el.canPlayType && (el.canPlayType('audio/x-m4a;') || el.canPlayType('audio/aac;')); }; var isAIFSupported = function () { return !!el.canPlayType && el.canPlayType('audio/x-aiff;'); }; p5.prototype.isFileSupported = function (extension) { switch (extension.toLowerCase()) { case 'mp3': return isMP3Supported(); case 'wav': return isWAVSupported(); case 'ogg': return isOGGSupported(); case 'aac', 'm4a', 'mp4': return isAACSupported(); case 'aif', 'aiff': return isAIFSupported(); default: return false; } }; // if it is iOS, we have to have a user interaction to start Web Audio // http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ var iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false; if (iOS) { var iosStarted = false; var startIOS = function () { if (iosStarted) return; // create empty buffer var buffer = audiocontext.createBuffer(1, 1, 22050); var source = audiocontext.createBufferSource(); source.buffer = buffer; // connect to output (your speakers) source.connect(audiocontext.destination); // play the file source.start(0); console.log('start ios!'); if (audiocontext.state === 'running') { iosStarted = true; } }; document.addEventListener('touchend', startIOS, false); document.addEventListener('touchstart', startIOS, false); } }(); var master; master = function () { 'use strict'; /** * Master contains AudioContext and the master sound output. */ var Master = function () { var audiocontext = p5.prototype.getAudioContext(); this.input = audiocontext.createGain(); this.output = audiocontext.createGain(); //put a hard limiter on the output this.limiter = audiocontext.createDynamicsCompressor(); this.limiter.threshold.value = 0; this.limiter.ratio.value = 100; this.audiocontext = audiocontext; this.output.disconnect(); // an array of input sources this.inputSources = []; // connect input to limiter this.input.connect(this.limiter); // connect limiter to output this.limiter.connect(this.output); // meter is just for global Amplitude / FFT analysis this.meter = audiocontext.createGain(); this.fftMeter = audiocontext.createGain(); this.output.connect(this.meter); this.output.connect(this.fftMeter); // connect output to destination this.output.connect(this.audiocontext.destination); // an array of all sounds in the sketch this.soundArray = []; // an array of all musical parts in the sketch this.parts = []; // file extensions to search for this.extensions = []; }; // create a single instance of the p5Sound / master output for use within this sketch var p5sound = new Master(); /** * Returns a number representing the master amplitude (volume) for sound * in this sketch. * * @method getMasterVolume * @return {Number} Master amplitude (volume) for sound in this sketch. * Should be between 0.0 (silence) and 1.0. */ p5.prototype.getMasterVolume = function () { return p5sound.output.gain.value; }; /** * <p>Scale the output of all sound in this sketch</p> * Scaled between 0.0 (silence) and 1.0 (full volume). * 1.0 is the maximum amplitude of a digital sound, so multiplying * by greater than 1.0 may cause digital distortion. To * fade, provide a <code>rampTime</code> parameter. For more * complex fades, see the Env class. * * Alternately, you can pass in a signal source such as an * oscillator to modulate the amplitude with an audio signal. * * <p><b>How This Works</b>: When you load the p5.sound module, it * creates a single instance of p5sound. All sound objects in this * module output to p5sound before reaching your computer's output. * So if you change the amplitude of p5sound, it impacts all of the * sound in this module.</p> * * <p>If no value is provided, returns a Web Audio API Gain Node</p> * * @method masterVolume * @param {Number|Object} volume Volume (amplitude) between 0.0 * and 1.0 or modulating signal/oscillator * @param {Number} [rampTime] Fade for t seconds * @param {Number} [timeFromNow] Schedule this event to happen at * t seconds in the future */ p5.prototype.masterVolume = function (vol, rampTime, tFromNow) { if (typeof vol === 'number') { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = p5sound.output.gain.value; p5sound.output.gain.cancelScheduledValues(now + tFromNow); p5sound.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); p5sound.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); } else if (vol) { vol.connect(p5sound.output.gain); } else { // return the Gain Node return p5sound.output.gain; } }; /** * p5.soundOut is the p5.sound master output. It sends output to * the destination of this window's web audio context. It contains * Web Audio API nodes including a dyanmicsCompressor (<code>.limiter</code>), * and Gain Nodes for <code>.input</code> and <code>.output</code>. * * @property p5.soundOut * @type {Object} */ p5.soundOut = p5sound; /** * a silent connection to the DesinationNode * which will ensure that anything connected to it * will not be garbage collected * * @private */ p5.soundOut._silentNode = p5sound.audiocontext.createGain(); p5.soundOut._silentNode.gain.value = 0; p5.soundOut._silentNode.connect(p5sound.audiocontext.destination); return p5sound; }(sndcore); var helpers; helpers = function () { 'use strict'; var p5sound = master; /** * Returns a number representing the sample rate, in samples per second, * of all sound objects in this audio context. It is determined by the * sampling rate of your operating system's sound card, and it is not * currently possile to change. * It is often 44100, or twice the range of human hearing. * * @method sampleRate * @return {Number} samplerate samples per second */ p5.prototype.sampleRate = function () { return p5sound.audiocontext.sampleRate; }; /** * Returns the closest MIDI note value for * a given frequency. * * @param {Number} frequency A freqeuncy, for example, the "A" * above Middle C is 440Hz * @return {Number} MIDI note value */ p5.prototype.freqToMidi = function (f) { var mathlog2 = Math.log(f / 440) / Math.log(2); var m = Math.round(12 * mathlog2) + 57; return m; }; /** * Returns the frequency value of a MIDI note value. * General MIDI treats notes as integers where middle C * is 60, C# is 61, D is 62 etc. Useful for generating * musical frequencies with oscillators. * * @method midiToFreq * @param {Number} midiNote The number of a MIDI note * @return {Number} Frequency value of the given MIDI note * @example * <div><code> * var notes = [60, 64, 67, 72]; * var i = 0; * * function setup() { * osc = new p5.Oscillator('Triangle'); * osc.start(); * frameRate(1); * } * * function draw() { * var freq = midiToFreq(notes[i]); * osc.freq(freq); * i++; * if (i >= notes.length){ * i = 0; * } * } * </code></div> */ p5.prototype.midiToFreq = function (m) { return 440 * Math.pow(2, (m - 69) / 12); }; /** * List the SoundFile formats that you will include. LoadSound * will search your directory for these extensions, and will pick * a format that is compatable with the client's web browser. * <a href="http://media.io/">Here</a> is a free online file * converter. * * @method soundFormats * @param {String|Strings} formats i.e. 'mp3', 'wav', 'ogg' * @example * <div><code> * function preload() { * // set the global sound formats * soundFormats('mp3', 'ogg'); * * // load either beatbox.mp3, or .ogg, depending on browser * mySound = loadSound('../sounds/beatbox.mp3'); * } * * function setup() { * mySound.play(); * } * </code></div> */ p5.prototype.soundFormats = function () { // reset extensions array p5sound.extensions = []; // add extensions for (var i = 0; i < arguments.length; i++) { arguments[i] = arguments[i].toLowerCase(); if ([ 'mp3', 'wav', 'ogg', 'm4a', 'aac' ].indexOf(arguments[i]) > -1) { p5sound.extensions.push(arguments[i]); } else { throw arguments[i] + ' is not a valid sound format!'; } } }; p5.prototype.disposeSound = function () { for (var i = 0; i < p5sound.soundArray.length; i++) { p5sound.soundArray[i].dispose(); } }; // register removeSound to dispose of p5sound SoundFiles, Convolvers, // Oscillators etc when sketch ends p5.prototype.registerMethod('remove', p5.prototype.disposeSound); p5.prototype._checkFileFormats = function (paths) { var path; // if path is a single string, check to see if extension is provided if (typeof paths === 'string') { path = paths; // see if extension is provided var extTest = path.split('.').pop(); // if an extension is provided... if ([ 'mp3', 'wav', 'ogg', 'm4a', 'aac' ].indexOf(extTest) > -1) { var supported = p5.prototype.isFileSupported(extTest); if (supported) { path = path; } else { var pathSplit = path.split('.'); var pathCore = pathSplit[pathSplit.length - 1]; for (var i = 0; i < p5sound.extensions.length; i++) { var extension = p5sound.extensions[i]; var supported = p5.prototype.isFileSupported(extension); if (supported) { pathCore = ''; if (pathSplit.length === 2) { pathCore += pathSplit[0]; } for (var i = 1; i <= pathSplit.length - 2; i++) { var p = pathSplit[i]; pathCore += '.' + p; } path = pathCore += '.'; path = path += extension; break; } } } } else { for (var i = 0; i < p5sound.extensions.length; i++) { var extension = p5sound.extensions[i]; var supported = p5.prototype.isFileSupported(extension); if (supported) { path = path + '.' + extension; break; } } } } else if (typeof paths === 'object') { for (var i = 0; i < paths.length; i++) { var extension = paths[i].split('.').pop(); var supported = p5.prototype.isFileSupported(extension); if (supported) { // console.log('.'+extension + ' is ' + supported + // ' supported by your browser.'); path = paths[i]; break; } } } return path; }; /** * Used by Osc and Env to chain signal math */ p5.prototype._mathChain = function (o, math, thisChain, nextChain, type) { // if this type of math already exists in the chain, replace it for (var i in o.mathOps) { if (o.mathOps[i] instanceof type) { o.mathOps[i].dispose(); thisChain = i; if (thisChain < o.mathOps.length - 1) { nextChain = o.mathOps[i + 1]; } } } o.mathOps[thisChain - 1].disconnect(); o.mathOps[thisChain - 1].connect(math); math.connect(nextChain); o.mathOps[thisChain] = math; return o; }; }(master); var errorHandler; errorHandler = function () { 'use strict'; /** * Helper function to generate an error * with a custom stack trace that points to the sketch * and removes other parts of the stack trace. * * @private * * @param {String} name custom error name * @param {String} errorTrace custom error trace * @param {String} failedPath path to the file that failed to load * @property {String} name custom error name * @property {String} message custom error message * @property {String} stack trace the error back to a line in the user's sketch. * Note: this edits out stack trace within p5.js and p5.sound. * @property {String} originalStack unedited, original stack trace * @property {String} failedPath path to the file that failed to load * @return {Error} returns a custom Error object */ var CustomError = function (name, errorTrace, failedPath) { var err = new Error(); var tempStack, splitStack; err.name = name; err.originalStack = err.stack + errorTrace; tempStack = err.stack + errorTrace; err.failedPath = failedPath; // only print the part of the stack trace that refers to the user code: var splitStack = tempStack.split('\n'); splitStack = splitStack.filter(function (ln) { return !ln.match(/(p5.|native code|globalInit)/g); }); err.stack = splitStack.join('\n'); return err; }; return CustomError; }(); var panner; panner = function () { 'use strict'; var p5sound = master; var ac = p5sound.audiocontext; // Stereo panner // if there is a stereo panner node use it if (typeof ac.createStereoPanner !== 'undefined') { p5.Panner = function (input, output, numInputChannels) { this.stereoPanner = this.input = ac.createStereoPanner(); input.connect(this.stereoPanner); this.stereoPanner.connect(output); }; p5.Panner.prototype.pan = function (val, tFromNow) { var time = tFromNow || 0; var t = ac.currentTime + time; this.stereoPanner.pan.linearRampToValueAtTime(val, t); }; p5.Panner.prototype.inputChannels = function (numChannels) { }; p5.Panner.prototype.connect = function (obj) { this.stereoPanner.connect(obj); }; p5.Panner.prototype.disconnect = function (obj) { this.stereoPanner.disconnect(); }; } else { // if there is no createStereoPanner object // such as in safari 7.1.7 at the time of writing this // use this method to create the effect p5.Panner = function (input, output, numInputChannels) { this.input = ac.createGain(); input.connect(this.input); this.left = ac.createGain(); this.right = ac.createGain(); this.left.channelInterpretation = 'discrete'; this.right.channelInterpretation = 'discrete'; // if input is stereo if (numInputChannels > 1) { this.splitter = ac.createChannelSplitter(2); this.input.connect(this.splitter); this.splitter.connect(this.left, 1); this.splitter.connect(this.right, 0); } else { this.input.connect(this.left); this.input.connect(this.right); } this.output = ac.createChannelMerger(2); this.left.connect(this.output, 0, 1); this.right.connect(this.output, 0, 0); this.output.connect(output); }; // -1 is left, +1 is right p5.Panner.prototype.pan = function (val, tFromNow) { var time = tFromNow || 0; var t = ac.currentTime + time; var v = (val + 1) / 2; var rightVal = Math.cos(v * Math.PI / 2); var leftVal = Math.sin(v * Math.PI / 2); this.left.gain.linearRampToValueAtTime(leftVal, t); this.right.gain.linearRampToValueAtTime(rightVal, t); }; p5.Panner.prototype.inputChannels = function (numChannels) { if (numChannels === 1) { this.input.disconnect(); this.input.connect(this.left); this.input.connect(this.right); } else if (numChannels === 2) { if (typeof (this.splitter === 'undefined')) { this.splitter = ac.createChannelSplitter(2); } this.input.disconnect(); this.input.connect(this.splitter); this.splitter.connect(this.left, 1); this.splitter.connect(this.right, 0); } }; p5.Panner.prototype.connect = function (obj) { this.output.connect(obj); }; p5.Panner.prototype.disconnect = function (obj) { this.output.disconnect(); }; } // 3D panner p5.Panner3D = function (input, output) { var panner3D = ac.createPanner(); panner3D.panningModel = 'HRTF'; panner3D.distanceModel = 'linear'; panner3D.setPosition(0, 0, 0); input.connect(panner3D); panner3D.connect(output); panner3D.pan = function (xVal, yVal, zVal) { panner3D.setPosition(xVal, yVal, zVal); }; return panner3D; }; }(master); var soundfile; soundfile = function () { 'use strict'; var CustomError = errorHandler; var p5sound = master; var ac = p5sound.audiocontext; /** * <p>SoundFile object with a path to a file.</p> * * <p>The p5.SoundFile may not be available immediately because * it loads the file information asynchronously.</p> * * <p>To do something with the sound as soon as it loads * pass the name of a function as the second parameter.</p> * * <p>Only one file path is required. However, audio file formats * (i.e. mp3, ogg, wav and m4a/aac) are not supported by all * web browsers. If you want to ensure compatability, instead of a single * file path, you may include an Array of filepaths, and the browser will * choose a format that works.</p> * * @class p5.SoundFile * @constructor * @param {String/Array} path path to a sound file (String). Optionally, * you may include multiple file formats in * an array. Alternately, accepts an object * from the HTML5 File API, or a p5.File. * @param {Function} [successCallback] Name of a function to call once file loads * @param {Function} [errorCallback] Name of a function to call if file fails to * load. This function will receive an error or * XMLHttpRequest object with information * about what went wrong. * @param {Function} [whileLoadingCallback] Name of a function to call while file * is loading. That function will * receive percentage loaded * (between 0 and 1) as a * parameter. * * @return {Object} p5.SoundFile Object * @example * <div><code> * * function preload() { * mySound = loadSound('assets/doorbell.mp3'); * } * * function setup() { * mySound.setVolume(0.1); * mySound.play(); * } * * </code></div> */ p5.SoundFile = function (paths, onload, onerror, whileLoading) { if (typeof paths !== 'undefined') { if (typeof paths == 'string' || typeof paths[0] == 'string') { var path = p5.prototype._checkFileFormats(paths); this.url = path; } else if (typeof paths == 'object') { if (!(window.File && window.FileReader && window.FileList && window.Blob)) { // The File API isn't supported in this browser throw 'Unable to load file because the File API is not supported'; } } // if type is a p5.File...get the actual file if (paths.file) { paths = paths.file; } this.file = paths; } // private _onended callback, set by the method: onended(callback) this._onended = function () { }; this._looping = false; this._playing = false; this._paused = false; this._pauseTime = 0; // cues for scheduling events with addCue() removeCue() this._cues = []; // position of the most recently played sample this._lastPos = 0; this._counterNode; this._scopeNode; // array of sources so that they can all be stopped! this.bufferSourceNodes = []; // current source this.bufferSourceNode = null; this.buffer = null; this.playbackRate = 1; this.gain = 1; this.input = p5sound.audiocontext.createGain(); this.output = p5sound.audiocontext.createGain(); this.reversed = false; // start and end of playback / loop this.startTime = 0; this.endTime = null; this.pauseTime = 0; // "restart" would stop playback before retriggering this.mode = 'sustain'; // time that playback was started, in millis this.startMillis = null; // stereo panning this.panPosition = 0; this.panner = new p5.Panner(this.output, p5sound.input, 2); // it is possible to instantiate a soundfile with no path if (this.url || this.file) { this.load(onload, onerror); } // add this p5.SoundFile to the soundArray p5sound.soundArray.push(this); if (typeof whileLoading === 'function') { this._whileLoading = whileLoading; } else { this._whileLoading = function () { }; } }; // register preload handling of loadSound p5.prototype.registerPreloadMethod('loadSound', p5.prototype); /** * loadSound() returns a new p5.SoundFile from a specified * path. If called during preload(), the p5.SoundFile will be ready * to play in time for setup() and draw(). If called outside of * preload, the p5.SoundFile will not be ready immediately, so * loadSound accepts a callback as the second parameter. Using a * <a href="https://github.com/processing/p5.js/wiki/Local-server"> * local server</a> is recommended when loading external files. * * @method loadSound * @param {String/Array} path Path to the sound file, or an array with * paths to soundfiles in multiple formats * i.e. ['sound.ogg', 'sound.mp3']. * Alternately, accepts an object: either * from the HTML5 File API, or a p5.File. * @param {Function} [successCallback] Name of a function to call once file loads * @param {Function} [errorCallback] Name of a function to call if there is * an error loading the file. * @param {Function} [whileLoading] Name of a function to call while file is loading. * This function will receive the percentage loaded * so far, from 0.0 to 1.0. * @return {SoundFile} Returns a p5.SoundFile * @example * <div><code> * function preload() { * mySound = loadSound('assets/doorbell.mp3'); * } * * function setup() { * mySound.setVolume(0.1); * mySound.play(); * } * </code></div> */ p5.prototype.loadSound = function (path, callback, onerror, whileLoading) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } var s = new p5.SoundFile(path, callback, onerror, whileLoading); return s; }; /** * This is a helper function that the p5.SoundFile calls to load * itself. Accepts a callback (the name of another function) * as an optional parameter. * * @private * @param {Function} [successCallback] Name of a function to call once file loads * @param {Function} [errorCallback] Name of a function to call if there is an error */ p5.SoundFile.prototype.load = function (callback, errorCallback) { var loggedError = false; var self = this; var errorTrace = new Error().stack; if (this.url != undefined && this.url != '') { var request = new XMLHttpRequest(); request.addEventListener('progress', function (evt) { self._updateProgress(evt); }, false); request.open('GET', this.url, true); request.responseType = 'arraybuffer'; request.onload = function () { if (request.status == 200) { // on sucess loading file: ac.decodeAudioData(request.response, // success decoding buffer: function (buff) { self.buffer = buff; self.panner.inputChannels(buff.numberOfChannels); if (callback) { callback(self); } }, // error decoding buffer. "e" is undefined in Chrome 11/22/2015 function (e) { var err = new CustomError('decodeAudioData', errorTrace, self.url); var msg = 'AudioContext error at decodeAudioData for ' + self.url; if (errorCallback) { err.msg = msg; errorCallback(err); } else { console.error(msg + '\n The error stack trace includes: \n' + err.stack); } }); } else { var err = new CustomError('loadSound', errorTrace, self.url); var msg = 'Unable to load ' + self.url + '. The request status was: ' + request.status + ' (' + request.statusText + ')'; if (errorCallback) { err.message = msg; errorCallback(err); } else { console.error(msg + '\n The error stack trace includes: \n' + err.stack); } } }; // if there is another error, aside from 404... request.onerror = function (e) { var err = new CustomError('loadSound', errorTrace, self.url); var msg = 'There was no response from the server at ' + self.url + '. Check the url and internet connectivity.'; if (errorCallback) { err.message = msg; errorCallback(err); } else { console.error(msg + '\n The error stack trace includes: \n' + err.stack); } }; request.send(); } else if (this.file != undefined) { var reader = new FileReader(); var self = this; reader.onload = function () { ac.decodeAudioData(reader.result, function (buff) { self.buffer = buff; self.panner.inputChannels(buff.numberOfChannels); if (callback) { callback(self); } }); }; reader.onerror = function (e) { if (onerror) onerror(e); }; reader.readAsArrayBuffer(this.file); } }; // TO DO: use this method to create a loading bar that shows progress during file upload/decode. p5.SoundFile.prototype._updateProgress = function (evt) { if (evt.lengthComputable) { var percentComplete = Math.log(evt.loaded / evt.total * 9.9); this._whileLoading(percentComplete); } else { // Unable to compute progress information since the total size is unknown this._whileLoading('size unknown'); } }; /** * Returns true if the sound file finished loading successfully. * * @method isLoaded * @return {Boolean} */ p5.SoundFile.prototype.isLoaded = function () { if (this.buffer) { return true; } else { return false; } }; /** * Play the p5.SoundFile * * @method play * @param {Number} [startTime] (optional) schedule playback to start (in seconds from now). * @param {Number} [rate] (optional) playback rate * @param {Number} [amp] (optional) amplitude (volume) * of playback * @param {Number} [cueStart] (optional) cue start time in seconds * @param {Number} [duration] (optional) duration of playback in seconds */ p5.SoundFile.prototype.play = function (time, rate, amp, _cueStart, duration) { var self = this; var now = p5sound.audiocontext.currentTime; var cueStart, cueEnd; var time = time || 0; if (time < 0) { time = 0; } time = time + now; // TO DO: if already playing, create array of buffers for easy stop() if (this.buffer) { // reset the pause time (if it was paused) this._pauseTime = 0; // handle restart playmode if (this.mode === 'restart' && this.buffer && this.bufferSourceNode) { var now = p5sound.audiocontext.currentTime; this.bufferSourceNode.stop(time); this._counterNode.stop(time); } // make a new source and counter. They are automatically assigned playbackRate and buffer this.bufferSourceNode = this._initSourceNode(); // garbage collect counterNode and create a new one if (this._counterNode) this._counterNode = undefined; this._counterNode = this._initCounterNode(); if (_cueStart) { if (_cueStart >= 0 && _cueStart < this.buffer.duration) { // this.startTime = cueStart; cueStart = _cueStart; } else { throw 'start time out of range'; } } else { cueStart = 0; } if (duration) { // if duration is greater than buffer.duration, just play entire file anyway rather than throw an error duration = duration <= this.buffer.duration - cueStart ? duration : this.buffer.duration; } else { duration = this.buffer.duration - cueStart; } // TO DO: Fix this. It broke in Safari // // method of controlling gain for individual bufferSourceNodes, without resetting overall soundfile volume // if (typeof(this.bufferSourceNode.gain === 'undefined' ) ) { // this.bufferSourceNode.gain = p5sound.audiocontext.createGain(); // } // this.bufferSourceNode.connect(this.bufferSourceNode.gain); // set local amp if provided, otherwise 1 var a = amp || 1; // this.bufferSourceNode.gain.gain.setValueAtTime(a, p5sound.audiocontext.currentTime); // this.bufferSourceNode.gain.connect(this.output); this.bufferSourceNode.connect(this.output); this.output.gain.value = a; // not necessary with _initBufferSource ? // this.bufferSourceNode.playbackRate.cancelScheduledValues(now); rate = rate || Math.abs(this.playbackRate); this.bufferSourceNode.playbackRate.setValueAtTime(rate, now); // if it was paused, play at the pause position if (this._paused) { this.bufferSourceNode.start(time, this.pauseTime, duration); this._counterNode.start(time, this.pauseTime, duration); } else { this.bufferSourceNode.start(time, cueStart, duration); this._counterNode.start(time, cueStart, duration); } this._playing = true; this._paused = false; // add source to sources array, which is used in stopAll() this.bufferSourceNodes.push(this.bufferSourceNode); this.bufferSourceNode._arrayIndex = this.bufferSourceNodes.length - 1; // delete this.bufferSourceNode from the sources array when it is done playing: var clearOnEnd = function (e) { this._playing = false; this.removeEventListener('ended', clearOnEnd, false); // call the onended callback self._onended(self); self.bufferSourceNodes.forEach(function (n, i) { if (n._playing === false) { self.bufferSourceNodes.splice(i); } }); if (self.bufferSourceNodes.length === 0) { self._playing = false; } }; this.bufferSourceNode.onended = clearOnEnd; } else { throw 'not ready to play file, buffer has yet to load. Try preload()'; } // if looping, will restart at original time this.bufferSourceNode.loop = this._looping; this._counterNode.loop = this._looping; if (this._looping === true) { var cueEnd = cueStart + duration; this.bufferSourceNode.loopStart = cueStart; this.bufferSourceNode.loopEnd = cueEnd; this._counterNode.loopStart = cueStart; this._counterNode.loopEnd = cueEnd; } }; /** * p5.SoundFile has two play modes: <code>restart</code> and * <code>sustain</code>. Play Mode determines what happens to a * p5.SoundFile if it is triggered while in the middle of playback. * In sustain mode, playback will continue simultaneous to the * new playback. In restart mode, play() will stop playback * and start over. Sustain is the default mode. * * @method playMode * @param {String} str 'restart' or 'sustain' * @example * <div><code> * function setup(){ * mySound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * function mouseClicked() { * mySound.playMode('sustain'); * mySound.play(); * } * function keyPressed() { * mySound.playMode('restart'); * mySound.play(); * } * * </code></div> */ p5.SoundFile.prototype.playMode = function (str) { var s = str.toLowerCase(); // if restart, stop all other sounds from playing if (s === 'restart' && this.buffer && this.bufferSourceNode) { for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { var now = p5sound.audiocontext.currentTime; this.bufferSourceNodes[i].stop(now); } } // set play mode to effect future playback if (s === 'restart' || s === 'sustain') { this.mode = s; } else { throw 'Invalid play mode. Must be either "restart" or "sustain"'; } }; /** * Pauses a file that is currently playing. If the file is not * playing, then nothing will happen. * * After pausing, .play() will resume from the paused * position. * If p5.SoundFile had been set to loop before it was paused, * it will continue to loop after it is unpaused with .play(). * * @method pause * @param {Number} [startTime] (optional) schedule event to occur * seconds from now * @example * <div><code> * var soundFile; * * function preload() { * soundFormats('ogg', 'mp3'); * soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3'); * } * function setup() { * background(0, 255, 0); * soundFile.setVolume(0.1); * soundFile.loop(); * } * function keyTyped() { * if (key == 'p') { * soundFile.pause(); * background(255, 0, 0); * } * } * * function keyReleased() { * if (key == 'p') { * soundFile.play(); * background(0, 255, 0); * } * </code> * </div> */ p5.SoundFile.prototype.pause = function (time) { var now = p5sound.audiocontext.currentTime; var time = time || 0; var pTime = time + now; if (this.isPlaying() && this.buffer && this.bufferSourceNode) { this.pauseTime = this.currentTime(); this.bufferSourceNode.stop(pTime); this._counterNode.stop(pTime); this._paused = true; this._playing = false; this._pauseTime = this.currentTime(); } else { this._pauseTime = 0; } }; /** * Loop the p5.SoundFile. Accepts optional parameters to set the * playback rate, playback volume, loopStart, loopEnd. * * @method loop * @param {Number} [startTime] (optional) schedule event to occur * seconds from now * @param {Number} [rate] (optional) playback rate * @param {Number} [amp] (optional) playback volume * @param {Number} [cueLoopStart](optional) startTime in seconds * @param {Number} [duration] (optional) loop duration in seconds */ p5.SoundFile.prototype.loop = function (startTime, rate, amp, loopStart, duration) { this._looping = true; this.play(startTime, rate, amp, loopStart, duration); }; /** * Set a p5.SoundFile's looping flag to true or false. If the sound * is currently playing, this change will take effect when it * reaches the end of the current playback. * * @param {Boolean} Boolean set looping to true or false */ p5.SoundFile.prototype.setLoop = function (bool) { if (bool === true) { this._looping = true; } else if (bool === false) { this._looping = false; } else { throw 'Error: setLoop accepts either true or false'; } if (this.bufferSourceNode) { this.bufferSourceNode.loop = this._looping; this._counterNode.loop = this._looping; } }; /** * Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not. * * @return {Boolean} */ p5.SoundFile.prototype.isLooping = function () { if (!this.bufferSourceNode) { return false; } if (this._looping === true && this.isPlaying() === true) { return true; } return false; }; /** * Returns true if a p5.SoundFile is playing, false if not (i.e. * paused or stopped). * * @method isPlaying * @return {Boolean} */ p5.SoundFile.prototype.isPlaying = function () { return this._playing; }; /** * Returns true if a p5.SoundFile is paused, false if not (i.e. * playing or stopped). * * @method isPaused * @return {Boolean} */ p5.SoundFile.prototype.isPaused = function () { return this._paused; }; /** * Stop soundfile playback. * * @method stop * @param {Number} [startTime] (optional) schedule event to occur * in seconds from now */ p5.SoundFile.prototype.stop = function (timeFromNow) { var time = timeFromNow || 0; if (this.mode == 'sustain') { this.stopAll(time); this._playing = false; this.pauseTime = 0; this._paused = false; } else if (this.buffer && this.bufferSourceNode) { var now = p5sound.audiocontext.currentTime; var t = time || 0; this.pauseTime = 0; this.bufferSourceNode.stop(now + t); this._counterNode.stop(now + t); this._playing = false; this._paused = false; } }; /** * Stop playback on all of this soundfile's sources. * @private */ p5.SoundFile.prototype.stopAll = function (_time) { var now = p5sound.audiocontext.currentTime; var time = _time || 0; if (this.buffer && this.bufferSourceNode) { for (var i = 0; i < this.bufferSourceNodes.length; i++) { if (typeof this.bufferSourceNodes[i] != undefined) { try { this.bufferSourceNodes[i].onended = function () { }; this.bufferSourceNodes[i].stop(now + time); } catch (e) { } } } this._counterNode.stop(now + time); this._onended(this); } }; /** * Multiply the output volume (amplitude) of a sound file * between 0.0 (silence) and 1.0 (full volume). * 1.0 is the maximum amplitude of a digital sound, so multiplying * by greater than 1.0 may cause digital distortion. To * fade, provide a <code>rampTime</code> parameter. For more * complex fades, see the Env class. * * Alternately, you can pass in a signal source such as an * oscillator to modulate the amplitude with an audio signal. * * @method setVolume * @param {Number|Object} volume Volume (amplitude) between 0.0 * and 1.0 or modulating signal/oscillator * @param {Number} [rampTime] Fade for t seconds * @param {Number} [timeFromNow] Schedule this event to happen at * t seconds in the future */ p5.SoundFile.prototype.setVolume = function (vol, rampTime, tFromNow) { if (typeof vol === 'number') { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now + tFromNow); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); } else if (vol) { vol.connect(this.output.gain); } else { // return the Gain Node return this.output.gain; } }; // same as setVolume, to match Processing Sound p5.SoundFile.prototype.amp = p5.SoundFile.prototype.setVolume; // these are the same thing p5.SoundFile.prototype.fade = p5.SoundFile.prototype.setVolume; p5.SoundFile.prototype.getVolume = function () { return this.output.gain.value; }; /** * Set the stereo panning of a p5.sound object to * a floating point number between -1.0 (left) and 1.0 (right). * Default is 0.0 (center). * * @method pan * @param {Number} [panValue] Set the stereo panner * @param {Number} timeFromNow schedule this event to happen * seconds from now * @example * <div><code> * * var ball = {}; * var soundFile; * * function setup() { * soundFormats('ogg', 'mp3'); * soundFile = loadSound('assets/beatbox.mp3'); * } * * function draw() { * background(0); * ball.x = constrain(mouseX, 0, width); * ellipse(ball.x, height/2, 20, 20) * } * * function mousePressed(){ * // map the ball's x location to a panning degree * // between -1.0 (left) and 1.0 (right) * var panning = map(ball.x, 0., width,-1.0, 1.0); * soundFile.pan(panning); * soundFile.play(); * } * </div></code> */ p5.SoundFile.prototype.pan = function (pval, tFromNow) { this.panPosition = pval; this.panner.pan(pval, tFromNow); }; /** * Returns the current stereo pan position (-1.0 to 1.0) * * @return {Number} Returns the stereo pan setting of the Oscillator * as a number between -1.0 (left) and 1.0 (right). * 0.0 is center and default. */ p5.SoundFile.prototype.getPan = function () { return this.panPosition; }; /** * Set the playback rate of a sound file. Will change the speed and the pitch. * Values less than zero will reverse the audio buffer. * * @method rate * @param {Number} [playbackRate] Set the playback rate. 1.0 is normal, * .5 is half-speed, 2.0 is twice as fast. * Must be greater than zero. * @example * <div><code> * var song; * * function preload() { * song = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * song.loop(); * } * * function draw() { * background(200); * * // Set the rate to a range between 0.1 and 4 * // Changing the rate also alters the pitch * var speed = map(mouseY, 0.1, height, 0, 2); * speed = constrain(speed, 0.01, 4); * song.rate(speed); * * // Draw a circle to show what is going on * stroke(0); * fill(51, 100); * ellipse(mouseX, 100, 48, 48); * } * * </code> * </div> * */ p5.SoundFile.prototype.rate = function (playbackRate) { if (this.playbackRate === playbackRate && this.bufferSourceNode) { if (this.bufferSourceNode.playbackRate.value === playbackRate) { return; } } this.playbackRate = playbackRate; var rate = playbackRate; if (this.playbackRate === 0 && this._playing) { this.pause(); } if (this.playbackRate < 0 && !this.reversed) { var cPos = this.currentTime(); var cRate = this.bufferSourceNode.playbackRate.value; // this.pause(); this.reverseBuffer(); rate = Math.abs(playbackRate); var newPos = (cPos - this.duration()) / rate; this.pauseTime = newPos; } else if (this.playbackRate > 0 && this.reversed) { this.reverseBuffer(); } if (this.bufferSourceNode) { var now = p5sound.audiocontext.currentTime; this.bufferSourceNode.playbackRate.cancelScheduledValues(now); this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(rate), now); this._counterNode.playbackRate.cancelScheduledValues(now); this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(rate), now); } }; // TO DO: document this p5.SoundFile.prototype.setPitch = function (num) { var newPlaybackRate = midiToFreq(num) / midiToFreq(60); this.rate(newPlaybackRate); }; p5.SoundFile.prototype.getPlaybackRate = function () { return this.playbackRate; }; /** * Returns the duration of a sound file in seconds. * * @method duration * @return {Number} The duration of the soundFile in seconds. */ p5.SoundFile.prototype.duration = function () { // Return Duration if (this.buffer) { return this.buffer.duration; } else { return 0; } }; /** * Return the current position of the p5.SoundFile playhead, in seconds. * Note that if you change the playbackRate while the p5.SoundFile is * playing, the results may not be accurate. * * @method currentTime * @return {Number} currentTime of the soundFile in seconds. */ p5.SoundFile.prototype.currentTime = function () { // TO DO --> make reverse() flip these values appropriately if (this._pauseTime > 0) { return this._pauseTime; } else { return this._lastPos / ac.sampleRate; } }; /** * Move the playhead of the song to a position, in seconds. Start * and Stop time. If none are given, will reset the file to play * entire duration from start to finish. * * @method jump * @param {Number} cueTime cueTime of the soundFile in seconds. * @param {Number} uuration duration in seconds. */ p5.SoundFile.prototype.jump = function (cueTime, duration) { if (cueTime < 0 || cueTime > this.buffer.duration) { throw 'jump time out of range'; } if (duration > this.buffer.duration - cueTime) { throw 'end time out of range'; } var cTime = cueTime || 0; var eTime = duration || this.buffer.duration - cueTime; if (this.isPlaying()) { this.stop(); } this.play(0, this.playbackRate, this.output.gain.value, cTime, eTime); }; /** * Return the number of channels in a sound file. * For example, Mono = 1, Stereo = 2. * * @method channels * @return {Number} [channels] */ p5.SoundFile.prototype.channels = function () { return this.buffer.numberOfChannels; }; /** * Return the sample rate of the sound file. * * @method sampleRate * @return {Number} [sampleRate] */ p5.SoundFile.prototype.sampleRate = function () { return this.buffer.sampleRate; }; /** * Return the number of samples in a sound file. * Equal to sampleRate * duration. * * @method frames * @return {Number} [sampleCount] */ p5.SoundFile.prototype.frames = function () { return this.buffer.length; }; /** * Returns an array of amplitude peaks in a p5.SoundFile that can be * used to draw a static waveform. Scans through the p5.SoundFile's * audio buffer to find the greatest amplitudes. Accepts one * parameter, 'length', which determines size of the array. * Larger arrays result in more precise waveform visualizations. * * Inspired by Wavesurfer.js. * * @method getPeaks * @params {Number} [length] length is the size of the returned array. * Larger length results in more precision. * Defaults to 5*width of the browser window. * @returns {Float32Array} Array of peaks. */ p5.SoundFile.prototype.getPeaks = function (length) { if (this.buffer) { // set length to window's width if no length is provided if (!length) { length = window.width * 5; } if (this.buffer) { var buffer = this.buffer; var sampleSize = buffer.length / length; var sampleStep = ~~(sampleSize / 10) || 1; var channels = buffer.numberOfChannels; var peaks = new Float32Array(Math.round(length)); for (var c = 0; c < channels; c++) { var chan = buffer.getChannelData(c); for (var i = 0; i < length; i++) { var start = ~~(i * sampleSize); var end = ~~(start + sampleSize); var max = 0; for (var j = start; j < end; j += sampleStep) { var value = chan[j]; if (value > max) { max = value; } else if (-value > max) { max = value; } } if (c === 0 || Math.abs(max) > peaks[i]) { peaks[i] = max; } } } return peaks; } } else { throw 'Cannot load peaks yet, buffer is not loaded'; } }; /** * Reverses the p5.SoundFile's buffer source. * Playback must be handled separately (see example). * * @method reverseBuffer * @example * <div><code> * var drum; * * function preload() { * drum = loadSound('assets/drum.mp3'); * } * * function setup() { * drum.reverseBuffer(); * drum.play(); * } * * </code> * </div> */ p5.SoundFile.prototype.reverseBuffer = function () { var curVol = this.getVolume(); this.setVolume(0, 0.01, 0); this.pause(); if (this.buffer) { for (var i = 0; i < this.buffer.numberOfChannels; i++) { Array.prototype.reverse.call(this.buffer.getChannelData(i)); } // set reversed flag this.reversed = !this.reversed; } else { throw 'SoundFile is not done loading'; } this.setVolume(curVol, 0.01, 0.0101); this.play(); }; /** * Schedule an event to be called when the soundfile * reaches the end of a buffer. If the soundfile is * playing through once, this will be called when it * ends. If it is looping, it will be called when * stop is called. * * @method onended * @param {Function} callback function to call when the * soundfile has ended. */ p5.SoundFile.prototype.onended = function (callback) { this._onended = callback; return this; }; p5.SoundFile.prototype.add = function () { }; p5.SoundFile.prototype.dispose = function () { var now = p5sound.audiocontext.currentTime; // remove reference to soundfile var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this.stop(now); if (this.buffer && this.bufferSourceNode) { for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { if (this.bufferSourceNodes[i] !== null) { this.bufferSourceNodes[i].disconnect(); try { this.bufferSourceNodes[i].stop(now); } catch (e) { } this.bufferSourceNodes[i] = null; } } if (this.isPlaying()) { try { this._counterNode.stop(now); } catch (e) { console.log(e); } this._counterNode = null; } } if (this.output) { this.output.disconnect(); this.output = null; } if (this.panner) { this.panner.disconnect(); this.panner = null; } }; /** * Connects the output of a p5sound object to input of another * p5.sound object. For example, you may connect a p5.SoundFile to an * FFT or an Effect. If no parameter is given, it will connect to * the master output. Most p5sound objects connect to the master * output when they are created. * * @method connect * @param {Object} [object] Audio object that accepts an input */ p5.SoundFile.prototype.connect = function (unit) { if (!unit) { this.panner.connect(p5sound.input); } else { if (unit.hasOwnProperty('input')) { this.panner.connect(unit.input); } else { this.panner.connect(unit); } } }; /** * Disconnects the output of this p5sound object. * * @method disconnect */ p5.SoundFile.prototype.disconnect = function (unit) { this.panner.disconnect(unit); }; /** */ p5.SoundFile.prototype.getLevel = function (smoothing) { console.warn('p5.SoundFile.getLevel has been removed from the library. Use p5.Amplitude instead'); }; /** * Reset the source for this SoundFile to a * new path (URL). * * @method setPath * @param {String} path path to audio file * @param {Function} callback Callback */ p5.SoundFile.prototype.setPath = function (p, callback) { var path = p5.prototype._checkFileFormats(p); this.url = path; this.load(callback); }; /** * Replace the current Audio Buffer with a new Buffer. * * @param {Array} buf Array of Float32 Array(s). 2 Float32 Arrays * will create a stereo source. 1 will create * a mono source. */ p5.SoundFile.prototype.setBuffer = function (buf) { var numChannels = buf.length; var size = buf[0].length; var newBuffer = ac.createBuffer(numChannels, size, ac.sampleRate); if (!buf[0] instanceof Float32Array) { buf[0] = new Float32Array(buf[0]); } for (var channelNum = 0; channelNum < numChannels; channelNum++) { var channel = newBuffer.getChannelData(channelNum); channel.set(buf[channelNum]); } this.buffer = newBuffer; // set numbers of channels on input to the panner this.panner.inputChannels(numChannels); }; ////////////////////////////////////////////////// // script processor node with an empty buffer to help // keep a sample-accurate position in playback buffer. // Inspired by Chinmay Pendharkar's technique for Sonoport --> http://bit.ly/1HwdCsV // Copyright [2015] [Sonoport (Asia) Pte. Ltd.], // Licensed under the Apache License http://apache.org/licenses/LICENSE-2.0 //////////////////////////////////////////////////////////////////////////////////// // initialize counterNode, set its initial buffer and playbackRate p5.SoundFile.prototype._initCounterNode = function () { var self = this; var now = ac.currentTime; var cNode = ac.createBufferSource(); // dispose of scope node if it already exists if (self._scopeNode) { self._scopeNode.disconnect(); self._scopeNode.onaudioprocess = undefined; self._scopeNode = null; } self._scopeNode = ac.createScriptProcessor(256, 1, 1); // create counter buffer of the same length as self.buffer cNode.buffer = _createCounterBuffer(self.buffer); cNode.playbackRate.setValueAtTime(self.playbackRate, now); cNode.connect(self._scopeNode); self._scopeNode.connect(p5.soundOut._silentNode); self._scopeNode.onaudioprocess = function (processEvent) { var inputBuffer = processEvent.inputBuffer.getChannelData(0); // update the lastPos self._lastPos = inputBuffer[inputBuffer.length - 1] || 0; // do any callbacks that have been scheduled self._onTimeUpdate(self._lastPos); }; return cNode; }; // initialize sourceNode, set its initial buffer and playbackRate p5.SoundFile.prototype._initSourceNode = function () { var self = this; var now = ac.currentTime; var bufferSourceNode = ac.createBufferSource(); bufferSourceNode.buffer = self.buffer; bufferSourceNode.playbackRate.setValueAtTime(self.playbackRate, now); return bufferSourceNode; }; var _createCounterBuffer = function (buffer) { var array = new Float32Array(buffer.length); var audioBuf = ac.createBuffer(1, buffer.length, 44100); for (var index = 0; index < buffer.length; index++) { array[index] = index; } audioBuf.getChannelData(0).set(array); return audioBuf; }; /** * processPeaks returns an array of timestamps where it thinks there is a beat. * * This is an asynchronous function that processes the soundfile in an offline audio context, * and sends the results to your callback function. * * The process involves running the soundfile through a lowpass filter, and finding all of the * peaks above the initial threshold. If the total number of peaks are below the minimum number of peaks, * it decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached. * * @method processPeaks * @param {Function} callback a function to call once this data is returned * @param {Number} [initThreshold] initial threshold defaults to 0.9 * @param {Number} [minThreshold] minimum threshold defaults to 0.22 * @param {Number} [minPeaks] minimum number of peaks defaults to 200 * @return {Array} Array of timestamped peaks */ p5.SoundFile.prototype.processPeaks = function (callback, _initThreshold, _minThreshold, _minPeaks) { var bufLen = this.buffer.length; var sampleRate = this.buffer.sampleRate; var buffer = this.buffer; var initialThreshold = _initThreshold || 0.9, threshold = initialThreshold, minThreshold = _minThreshold || 0.22, minPeaks = _minPeaks || 200; // Create offline context var offlineContext = new OfflineAudioContext(1, bufLen, sampleRate); // create buffer source var source = offlineContext.createBufferSource(); source.buffer = buffer; // Create filter. TO DO: allow custom setting of filter var filter = offlineContext.createBiquadFilter(); filter.type = 'lowpass'; source.connect(filter); filter.connect(offlineContext.destination); // start playing at time:0 source.start(0); offlineContext.startRendering(); // Render the song // act on the result offlineContext.oncomplete = function (e) { var data = {}; var filteredBuffer = e.renderedBuffer; var bufferData = filteredBuffer.getChannelData(0); // step 1: // create Peak instances, add them to array, with strength and sampleIndex do { allPeaks = getPeaksAtThreshold(bufferData, threshold); threshold -= 0.005; } while (Object.keys(allPeaks).length < minPeaks && threshold >= minThreshold); // step 2: // find intervals for each peak in the sampleIndex, add tempos array var intervalCounts = countIntervalsBetweenNearbyPeaks(allPeaks); // step 3: find top tempos var groups = groupNeighborsByTempo(intervalCounts, filteredBuffer.sampleRate); // sort top intervals var topTempos = groups.sort(function (intA, intB) { return intB.count - intA.count; }).splice(0, 5); // set this SoundFile's tempo to the top tempo ?? this.tempo = topTempos[0].tempo; // step 4: // new array of peaks at top tempo within a bpmVariance var bpmVariance = 5; var tempoPeaks = getPeaksAtTopTempo(allPeaks, topTempos[0].tempo, filteredBuffer.sampleRate, bpmVariance); callback(tempoPeaks); }; }; // process peaks var Peak = function (amp, i) { this.sampleIndex = i; this.amplitude = amp; this.tempos = []; this.intervals = []; }; var allPeaks = []; // 1. for processPeaks() Function to identify peaks above a threshold // returns an array of peak indexes as frames (samples) of the original soundfile function getPeaksAtThreshold(data, threshold) { var peaksObj = {}; var length = data.length; for (var i = 0; i < length; i++) { if (data[i] > threshold) { var amp = data[i]; var peak = new Peak(amp, i); peaksObj[i] = peak; // Skip forward ~ 1/8s to get past this peak. i += 6000; } i++; } return peaksObj; } // 2. for processPeaks() function countIntervalsBetweenNearbyPeaks(peaksObj) { var intervalCounts = []; var peaksArray = Object.keys(peaksObj).sort(); for (var index = 0; index < peaksArray.length; index++) { // find intervals in comparison to nearby peaks for (var i = 0; i < 10; i++) { var startPeak = peaksObj[peaksArray[index]]; var endPeak = peaksObj[peaksArray[index + i]]; if (startPeak && endPeak) { var startPos = startPeak.sampleIndex; var endPos = endPeak.sampleIndex; var interval = endPos - startPos; // add a sample interval to the startPeek in the allPeaks array if (interval > 0) { startPeak.intervals.push(interval); } // tally the intervals and return interval counts var foundInterval = intervalCounts.some(function (intervalCount, p) { if (intervalCount.interval === interval) { intervalCount.count++; return intervalCount; } }); // store with JSON like formatting if (!foundInterval) { intervalCounts.push({ interval: interval, count: 1 }); } } } } return intervalCounts; } // 3. for processPeaks --> find tempo function groupNeighborsByTempo(intervalCounts, sampleRate) { var tempoCounts = []; intervalCounts.forEach(function (intervalCount, i) { try { // Convert an interval to tempo var theoreticalTempo = Math.abs(60 / (intervalCount.interval / sampleRate)); theoreticalTempo = mapTempo(theoreticalTempo); var foundTempo = tempoCounts.some(function (tempoCount) { if (tempoCount.tempo === theoreticalTempo) return tempoCount.count += intervalCount.count; }); if (!foundTempo) { if (isNaN(theoreticalTempo)) { return; } tempoCounts.push({ tempo: Math.round(theoreticalTempo), count: intervalCount.count }); } } catch (e) { throw e; } }); return tempoCounts; } // 4. for processPeaks - get peaks at top tempo function getPeaksAtTopTempo(peaksObj, tempo, sampleRate, bpmVariance) { var peaksAtTopTempo = []; var peaksArray = Object.keys(peaksObj).sort(); // TO DO: filter out peaks that have the tempo and return for (var i = 0; i < peaksArray.length; i++) { var key = peaksArray[i]; var peak = peaksObj[key]; for (var j = 0; j < peak.intervals.length; j++) { var intervalBPM = Math.round(Math.abs(60 / (peak.intervals[j] / sampleRate))); intervalBPM = mapTempo(intervalBPM); var dif = intervalBPM - tempo; if (Math.abs(intervalBPM - tempo) < bpmVariance) { // convert sampleIndex to seconds peaksAtTopTempo.push(peak.sampleIndex / 44100); } } } // filter out peaks that are very close to each other peaksAtTopTempo = peaksAtTopTempo.filter(function (peakTime, index, arr) { var dif = arr[index + 1] - peakTime; if (dif > 0.01) { return true; } }); return peaksAtTopTempo; } // helper function for processPeaks function mapTempo(theoreticalTempo) { // these scenarios create infinite while loop if (!isFinite(theoreticalTempo) || theoreticalTempo == 0) { return; } // Adjust the tempo to fit within the 90-180 BPM range while (theoreticalTempo < 90) theoreticalTempo *= 2; while (theoreticalTempo > 180 && theoreticalTempo > 90) theoreticalTempo /= 2; return theoreticalTempo; } /*** SCHEDULE EVENTS ***/ /** * Schedule events to trigger every time a MediaElement * (audio/video) reaches a playback cue point. * * Accepts a callback function, a time (in seconds) at which to trigger * the callback, and an optional parameter for the callback. * * Time will be passed as the first parameter to the callback function, * and param will be the second parameter. * * * @method addCue * @param {Number} time Time in seconds, relative to this media * element's playback. For example, to trigger * an event every time playback reaches two * seconds, pass in the number 2. This will be * passed as the first parameter to * the callback function. * @param {Function} callback Name of a function that will be * called at the given time. The callback will * receive time and (optionally) param as its * two parameters. * @param {Object} [value] An object to be passed as the * second parameter to the * callback function. * @return {Number} id ID of this cue, * useful for removeCue(id) * @example * <div><code> * function setup() { * background(0); * noStroke(); * fill(255); * textAlign(CENTER); * text('click to play', width/2, height/2); * * mySound = loadSound('assets/beat.mp3'); * * // schedule calls to changeText * mySound.addCue(0.50, changeText, "hello" ); * mySound.addCue(1.00, changeText, "p5" ); * mySound.addCue(1.50, changeText, "what" ); * mySound.addCue(2.00, changeText, "do" ); * mySound.addCue(2.50, changeText, "you" ); * mySound.addCue(3.00, changeText, "want" ); * mySound.addCue(4.00, changeText, "to" ); * mySound.addCue(5.00, changeText, "make" ); * mySound.addCue(6.00, changeText, "?" ); * } * * function changeText(val) { * background(0); * text(val, width/2, height/2); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * if (mySound.isPlaying() ) { * mySound.stop(); * } else { * mySound.play(); * } * } * } * </code></div> */ p5.SoundFile.prototype.addCue = function (time, callback, val) { var id = this._cueIDCounter++; var cue = new Cue(callback, time, id, val); this._cues.push(cue); // if (!this.elt.ontimeupdate) { // this.elt.ontimeupdate = this._onTimeUpdate.bind(this); // } return id; }; /** * Remove a callback based on its ID. The ID is returned by the * addCue method. * * @method removeCue * @param {Number} id ID of the cue, as returned by addCue */ p5.SoundFile.prototype.removeCue = function (id) { var cueLength = this._cues.length; for (var i = 0; i < cueLength; i++) { var cue = this._cues[i]; if (cue.id === id) { this.cues.splice(i, 1); } } if (this._cues.length === 0) { } }; /** * Remove all of the callbacks that had originally been scheduled * via the addCue method. * * @method clearCues */ p5.SoundFile.prototype.clearCues = function () { this._cues = []; }; // private method that checks for cues to be fired if events // have been scheduled using addCue(callback, time). p5.SoundFile.prototype._onTimeUpdate = function (position) { var playbackTime = position / this.buffer.sampleRate; var cueLength = this._cues.length; for (var i = 0; i < cueLength; i++) { var cue = this._cues[i]; var callbackTime = cue.time; var val = cue.val; if (this._prevTime < callbackTime && callbackTime <= playbackTime) { // pass the scheduled callbackTime as parameter to the callback cue.callback(val); } } this._prevTime = playbackTime; }; // Cue inspired by JavaScript setTimeout, and the // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org var Cue = function (callback, time, id, val) { this.callback = callback; this.time = time; this.id = id; this.val = val; }; }(sndcore, errorHandler, master); var amplitude; amplitude = function () { 'use strict'; var p5sound = master; /** * Amplitude measures volume between 0.0 and 1.0. * Listens to all p5sound by default, or use setInput() * to listen to a specific sound source. Accepts an optional * smoothing value, which defaults to 0. * * @class p5.Amplitude * @constructor * @param {Number} [smoothing] between 0.0 and .999 to smooth * amplitude readings (defaults to 0) * @return {Object} Amplitude Object * @example * <div><code> * var sound, amplitude, cnv; * * function preload(){ * sound = loadSound('assets/beat.mp3'); * } * function setup() { * cnv = createCanvas(100,100); * amplitude = new p5.Amplitude(); * * // start / stop the sound when canvas is clicked * cnv.mouseClicked(function() { * if (sound.isPlaying() ){ * sound.stop(); * } else { * sound.play(); * } * }); * } * function draw() { * background(0); * fill(255); * var level = amplitude.getLevel(); * var size = map(level, 0, 1, 0, 200); * ellipse(width/2, height/2, size, size); * } * * </code></div> */ p5.Amplitude = function (smoothing) { // Set to 2048 for now. In future iterations, this should be inherited or parsed from p5sound's default this.bufferSize = 2048; // set audio context this.audiocontext = p5sound.audiocontext; this.processor = this.audiocontext.createScriptProcessor(this.bufferSize, 2, 1); // for connections this.input = this.processor; this.output = this.audiocontext.createGain(); // smoothing defaults to 0 this.smoothing = smoothing || 0; // the variables to return this.volume = 0; this.average = 0; this.stereoVol = [ 0, 0 ]; this.stereoAvg = [ 0, 0 ]; this.stereoVolNorm = [ 0, 0 ]; this.volMax = 0.001; this.normalize = false; this.processor.onaudioprocess = this._audioProcess.bind(this); this.processor.connect(this.output); this.output.gain.value = 0; // this may only be necessary because of a Chrome bug this.output.connect(this.audiocontext.destination); // connect to p5sound master output by default, unless set by input() p5sound.meter.connect(this.processor); // add this p5.SoundFile to the soundArray p5sound.soundArray.push(this); }; /** * Connects to the p5sound instance (master output) by default. * Optionally, you can pass in a specific source (i.e. a soundfile). * * @method setInput * @param {soundObject|undefined} [snd] set the sound source * (optional, defaults to * master output) * @param {Number|undefined} [smoothing] a range between 0.0 and 1.0 * to smooth amplitude readings * @example * <div><code> * function preload(){ * sound1 = loadSound('assets/beat.mp3'); * sound2 = loadSound('assets/drum.mp3'); * } * function setup(){ * amplitude = new p5.Amplitude(); * sound1.play(); * sound2.play(); * amplitude.setInput(sound2); * } * function draw() { * background(0); * fill(255); * var level = amplitude.getLevel(); * var size = map(level, 0, 1, 0, 200); * ellipse(width/2, height/2, size, size); * } * function mouseClicked(){ * sound1.stop(); * sound2.stop(); * } * </code></div> */ p5.Amplitude.prototype.setInput = function (source, smoothing) { p5sound.meter.disconnect(); if (smoothing) { this.smoothing = smoothing; } // connect to the master out of p5s instance if no snd is provided if (source == null) { console.log('Amplitude input source is not ready! Connecting to master output instead'); p5sound.meter.connect(this.processor); } else if (source instanceof p5.Signal) { source.output.connect(this.processor); } else if (source) { source.connect(this.processor); this.processor.disconnect(); this.processor.connect(this.output); } else { p5sound.meter.connect(this.processor); } }; p5.Amplitude.prototype.connect = function (unit) { if (unit) { if (unit.hasOwnProperty('input')) { this.output.connect(unit.input); } else { this.output.connect(unit); } } else { this.output.connect(this.panner.connect(p5sound.input)); } }; p5.Amplitude.prototype.disconnect = function (unit) { this.output.disconnect(); }; // TO DO make this stereo / dependent on # of audio channels p5.Amplitude.prototype._audioProcess = function (event) { for (var channel = 0; channel < event.inputBuffer.numberOfChannels; channel++) { var inputBuffer = event.inputBuffer.getChannelData(channel); var bufLength = inputBuffer.length; var total = 0; var sum = 0; var x; for (var i = 0; i < bufLength; i++) { x = inputBuffer[i]; if (this.normalize) { total += Math.max(Math.min(x / this.volMax, 1), -1); sum += Math.max(Math.min(x / this.volMax, 1), -1) * Math.max(Math.min(x / this.volMax, 1), -1); } else { total += x; sum += x * x; } } var average = total / bufLength; // ... then take the square root of the sum. var rms = Math.sqrt(sum / bufLength); this.stereoVol[channel] = Math.max(rms, this.stereoVol[channel] * this.smoothing); this.stereoAvg[channel] = Math.max(average, this.stereoVol[channel] * this.smoothing); this.volMax = Math.max(this.stereoVol[channel], this.volMax); } // add volume from all channels together var self = this; var volSum = this.stereoVol.reduce(function (previousValue, currentValue, index) { self.stereoVolNorm[index - 1] = Math.max(Math.min(self.stereoVol[index - 1] / self.volMax, 1), 0); self.stereoVolNorm[index] = Math.max(Math.min(self.stereoVol[index] / self.volMax, 1), 0); return previousValue + currentValue; }); // volume is average of channels this.volume = volSum / this.stereoVol.length; // normalized value this.volNorm = Math.max(Math.min(this.volume / this.volMax, 1), 0); }; /** * Returns a single Amplitude reading at the moment it is called. * For continuous readings, run in the draw loop. * * @method getLevel * @param {Number} [channel] Optionally return only channel 0 (left) or 1 (right) * @return {Number} Amplitude as a number between 0.0 and 1.0 * @example * <div><code> * function preload(){ * sound = loadSound('assets/beat.mp3'); * } * function setup() { * amplitude = new p5.Amplitude(); * sound.play(); * } * function draw() { * background(0); * fill(255); * var level = amplitude.getLevel(); * var size = map(level, 0, 1, 0, 200); * ellipse(width/2, height/2, size, size); * } * function mouseClicked(){ * sound.stop(); * } * </code></div> */ p5.Amplitude.prototype.getLevel = function (channel) { if (typeof channel !== 'undefined') { if (this.normalize) { return this.stereoVolNorm[channel]; } else { return this.stereoVol[channel]; } } else if (this.normalize) { return this.volNorm; } else { return this.volume; } }; /** * Determines whether the results of Amplitude.process() will be * Normalized. To normalize, Amplitude finds the difference the * loudest reading it has processed and the maximum amplitude of * 1.0. Amplitude adds this difference to all values to produce * results that will reliably map between 0.0 and 1.0. However, * if a louder moment occurs, the amount that Normalize adds to * all the values will change. Accepts an optional boolean parameter * (true or false). Normalizing is off by default. * * @method toggleNormalize * @param {boolean} [boolean] set normalize to true (1) or false (0) */ p5.Amplitude.prototype.toggleNormalize = function (bool) { if (typeof bool === 'boolean') { this.normalize = bool; } else { this.normalize = !this.normalize; } }; /** * Smooth Amplitude analysis by averaging with the last analysis * frame. Off by default. * * @method smooth * @param {Number} set smoothing from 0.0 <= 1 */ p5.Amplitude.prototype.smooth = function (s) { if (s >= 0 && s < 1) { this.smoothing = s; } else { console.log('Error: smoothing must be between 0 and 1'); } }; p5.Amplitude.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this.input.disconnect(); this.output.disconnect(); this.input = this.processor = undefined; this.output = undefined; }; }(master); var fft; fft = function () { 'use strict'; var p5sound = master; /** * <p>FFT (Fast Fourier Transform) is an analysis algorithm that * isolates individual * <a href="https://en.wikipedia.org/wiki/Audio_frequency"> * audio frequencies</a> within a waveform.</p> * * <p>Once instantiated, a p5.FFT object can return an array based on * two types of analyses: <br> • <code>FFT.waveform()</code> computes * amplitude values along the time domain. The array indices correspond * to samples across a brief moment in time. Each value represents * amplitude of the waveform at that sample of time.<br> * • <code>FFT.analyze() </code> computes amplitude values along the * frequency domain. The array indices correspond to frequencies (i.e. * pitches), from the lowest to the highest that humans can hear. Each * value represents amplitude at that slice of the frequency spectrum. * Use with <code>getEnergy()</code> to measure amplitude at specific * frequencies, or within a range of frequencies. </p> * * <p>FFT analyzes a very short snapshot of sound called a sample * buffer. It returns an array of amplitude measurements, referred * to as <code>bins</code>. The array is 1024 bins long by default. * You can change the bin array length, but it must be a power of 2 * between 16 and 1024 in order for the FFT algorithm to function * correctly. The actual size of the FFT buffer is twice the * number of bins, so given a standard sample rate, the buffer is * 2048/44100 seconds long.</p> * * * @class p5.FFT * @constructor * @param {Number} [smoothing] Smooth results of Freq Spectrum. * 0.0 < smoothing < 1.0. * Defaults to 0.8. * @param {Number} [bins] Length of resulting array. * Must be a power of two between * 16 and 1024. Defaults to 1024. * @return {Object} FFT Object * @example * <div><code> * function preload(){ * sound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup(){ * var cnv = createCanvas(100,100); * cnv.mouseClicked(togglePlay); * fft = new p5.FFT(); * sound.amp(0.2); * } * * function draw(){ * background(0); * * var spectrum = fft.analyze(); * noStroke(); * fill(0,255,0); // spectrum is green * for (var i = 0; i< spectrum.length; i++){ * var x = map(i, 0, spectrum.length, 0, width); * var h = -height + map(spectrum[i], 0, 255, height, 0); * rect(x, height, width / spectrum.length, h ) * } * * var waveform = fft.waveform(); * noFill(); * beginShape(); * stroke(255,0,0); // waveform is red * strokeWeight(1); * for (var i = 0; i< waveform.length; i++){ * var x = map(i, 0, waveform.length, 0, width); * var y = map( waveform[i], -1, 1, 0, height); * vertex(x,y); * } * endShape(); * * text('click to play/pause', 4, 10); * } * * // fade sound if mouse is over canvas * function togglePlay() { * if (sound.isPlaying()) { * sound.pause(); * } else { * sound.loop(); * } * } * </code></div> */ p5.FFT = function (smoothing, bins) { this.smoothing = smoothing || 0.8; this.bins = bins || 1024; var FFT_SIZE = bins * 2 || 2048; this.input = this.analyser = p5sound.audiocontext.createAnalyser(); // default connections to p5sound fftMeter p5sound.fftMeter.connect(this.analyser); this.analyser.smoothingTimeConstant = this.smoothing; this.analyser.fftSize = FFT_SIZE; this.freqDomain = new Uint8Array(this.analyser.frequencyBinCount); this.timeDomain = new Uint8Array(this.analyser.frequencyBinCount); // predefined frequency ranages, these will be tweakable this.bass = [ 20, 140 ]; this.lowMid = [ 140, 400 ]; this.mid = [ 400, 2600 ]; this.highMid = [ 2600, 5200 ]; this.treble = [ 5200, 14000 ]; // add this p5.SoundFile to the soundArray p5sound.soundArray.push(this); }; /** * Set the input source for the FFT analysis. If no source is * provided, FFT will analyze all sound in the sketch. * * @method setInput * @param {Object} [source] p5.sound object (or web audio API source node) */ p5.FFT.prototype.setInput = function (source) { if (!source) { p5sound.fftMeter.connect(this.analyser); } else { if (source.output) { source.output.connect(this.analyser); } else if (source.connect) { source.connect(this.analyser); } p5sound.fftMeter.disconnect(); } }; /** * Returns an array of amplitude values (between -1.0 and +1.0) that represent * a snapshot of amplitude readings in a single buffer. Length will be * equal to bins (defaults to 1024). Can be used to draw the waveform * of a sound. * * @method waveform * @param {Number} [bins] Must be a power of two between * 16 and 1024. Defaults to 1024. * @param {String} [precision] If any value is provided, will return results * in a Float32 Array which is more precise * than a regular array. * @return {Array} Array Array of amplitude values (-1 to 1) * over time. Array length = bins. * */ p5.FFT.prototype.waveform = function () { var bins, mode, normalArray; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === 'number') { bins = arguments[i]; this.analyser.fftSize = bins * 2; } if (typeof arguments[i] === 'string') { mode = arguments[i]; } } // getFloatFrequencyData doesnt work in Safari as of 5/2015 if (mode && !p5.prototype._isSafari()) { timeToFloat(this, this.timeDomain); this.analyser.getFloatTimeDomainData(this.timeDomain); return this.timeDomain; } else { timeToInt(this, this.timeDomain); this.analyser.getByteTimeDomainData(this.timeDomain); var normalArray = new Array(); for (var i = 0; i < this.timeDomain.length; i++) { var scaled = p5.prototype.map(this.timeDomain[i], 0, 255, -1, 1); normalArray.push(scaled); } return normalArray; } }; /** * Returns an array of amplitude values (between 0 and 255) * across the frequency spectrum. Length is equal to FFT bins * (1024 by default). The array indices correspond to frequencies * (i.e. pitches), from the lowest to the highest that humans can * hear. Each value represents amplitude at that slice of the * frequency spectrum. Must be called prior to using * <code>getEnergy()</code>. * * @method analyze * @param {Number} [bins] Must be a power of two between * 16 and 1024. Defaults to 1024. * @param {Number} [scale] If "dB," returns decibel * float measurements between * -140 and 0 (max). * Otherwise returns integers from 0-255. * @return {Array} spectrum Array of energy (amplitude/volume) * values across the frequency spectrum. * Lowest energy (silence) = 0, highest * possible is 255. * @example * <div><code> * var osc; * var fft; * * function setup(){ * createCanvas(100,100); * osc = new p5.Oscillator(); * osc.amp(0); * osc.start(); * fft = new p5.FFT(); * } * * function draw(){ * background(0); * * var freq = map(mouseX, 0, 800, 20, 15000); * freq = constrain(freq, 1, 20000); * osc.freq(freq); * * var spectrum = fft.analyze(); * noStroke(); * fill(0,255,0); // spectrum is green * for (var i = 0; i< spectrum.length; i++){ * var x = map(i, 0, spectrum.length, 0, width); * var h = -height + map(spectrum[i], 0, 255, height, 0); * rect(x, height, width / spectrum.length, h ); * } * * stroke(255); * text('Freq: ' + round(freq)+'Hz', 10, 10); * * isMouseOverCanvas(); * } * * // only play sound when mouse is over canvas * function isMouseOverCanvas() { * var mX = mouseX, mY = mouseY; * if (mX > 0 && mX < width && mY < height && mY > 0) { * osc.amp(0.5, 0.2); * } else { * osc.amp(0, 0.2); * } * } * </code></div> * * */ p5.FFT.prototype.analyze = function () { var bins, mode; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === 'number') { bins = this.bins = arguments[i]; this.analyser.fftSize = this.bins * 2; } if (typeof arguments[i] === 'string') { mode = arguments[i]; } } if (mode && mode.toLowerCase() === 'db') { freqToFloat(this); this.analyser.getFloatFrequencyData(this.freqDomain); return this.freqDomain; } else { freqToInt(this, this.freqDomain); this.analyser.getByteFrequencyData(this.freqDomain); var normalArray = Array.apply([], this.freqDomain); normalArray.length === this.analyser.fftSize; normalArray.constructor === Array; return normalArray; } }; /** * Returns the amount of energy (volume) at a specific * <a href="en.wikipedia.org/wiki/Audio_frequency" target="_blank"> * frequency</a>, or the average amount of energy between two * frequencies. Accepts Number(s) corresponding * to frequency (in Hz), or a String corresponding to predefined * frequency ranges ("bass", "lowMid", "mid", "highMid", "treble"). * Returns a range between 0 (no energy/volume at that frequency) and * 255 (maximum energy). * <em>NOTE: analyze() must be called prior to getEnergy(). Analyze() * tells the FFT to analyze frequency data, and getEnergy() uses * the results determine the value at a specific frequency or * range of frequencies.</em></p> * * @method getEnergy * @param {Number|String} frequency1 Will return a value representing * energy at this frequency. Alternately, * the strings "bass", "lowMid" "mid", * "highMid", and "treble" will return * predefined frequency ranges. * @param {Number} [frequency2] If a second frequency is given, * will return average amount of * energy that exists between the * two frequencies. * @return {Number} Energy Energy (volume/amplitude) from * 0 and 255. * */ p5.FFT.prototype.getEnergy = function (frequency1, frequency2) { var nyquist = p5sound.audiocontext.sampleRate / 2; if (frequency1 === 'bass') { frequency1 = this.bass[0]; frequency2 = this.bass[1]; } else if (frequency1 === 'lowMid') { frequency1 = this.lowMid[0]; frequency2 = this.lowMid[1]; } else if (frequency1 === 'mid') { frequency1 = this.mid[0]; frequency2 = this.mid[1]; } else if (frequency1 === 'highMid') { frequency1 = this.highMid[0]; frequency2 = this.highMid[1]; } else if (frequency1 === 'treble') { frequency1 = this.treble[0]; frequency2 = this.treble[1]; } if (typeof frequency1 !== 'number') { throw 'invalid input for getEnergy()'; } else if (!frequency2) { var index = Math.round(frequency1 / nyquist * this.freqDomain.length); return this.freqDomain[index]; } else if (frequency1 && frequency2) { // if second is higher than first if (frequency1 > frequency2) { var swap = frequency2; frequency2 = frequency1; frequency1 = swap; } var lowIndex = Math.round(frequency1 / nyquist * this.freqDomain.length); var highIndex = Math.round(frequency2 / nyquist * this.freqDomain.length); var total = 0; var numFrequencies = 0; // add up all of the values for the frequencies for (var i = lowIndex; i <= highIndex; i++) { total += this.freqDomain[i]; numFrequencies += 1; } // divide by total number of frequencies var toReturn = total / numFrequencies; return toReturn; } else { throw 'invalid input for getEnergy()'; } }; // compatability with v.012, changed to getEnergy in v.0121. Will be deprecated... p5.FFT.prototype.getFreq = function (freq1, freq2) { console.log('getFreq() is deprecated. Please use getEnergy() instead.'); var x = this.getEnergy(freq1, freq2); return x; }; /** * Returns the * <a href="http://en.wikipedia.org/wiki/Spectral_centroid" target="_blank"> * spectral centroid</a> of the input signal. * <em>NOTE: analyze() must be called prior to getCentroid(). Analyze() * tells the FFT to analyze frequency data, and getCentroid() uses * the results determine the spectral centroid.</em></p> * * @method getCentroid * @return {Number} Spectral Centroid Frequency Frequency of the spectral centroid in Hz. * * * @example * <div><code> * * *function setup(){ * cnv = createCanvas(800,400); * sound = new p5.AudioIn(); * sound.start(); * fft = new p5.FFT(); * sound.connect(fft); *} * * *function draw(){ * * var centroidplot = 0.0; * var spectralCentroid = 0; * * * background(0); * stroke(0,255,0); * var spectrum = fft.analyze(); * fill(0,255,0); // spectrum is green * * //draw the spectrum * * for (var i = 0; i< spectrum.length; i++){ * var x = map(log(i), 0, log(spectrum.length), 0, width); * var h = map(spectrum[i], 0, 255, 0, height); * var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length)); * rect(x, height, rectangle_width, -h ) * } * var nyquist = 22050; * * // get the centroid * spectralCentroid = fft.getCentroid(); * * // the mean_freq_index calculation is for the display. * var mean_freq_index = spectralCentroid/(nyquist/spectrum.length); * * centroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width); * * * stroke(255,0,0); // the line showing where the centroid is will be red * * rect(centroidplot, 0, width / spectrum.length, height) * noStroke(); * fill(255,255,255); // text is white * textSize(40); * text("centroid: "+round(spectralCentroid)+" Hz", 10, 40); *} * </code></div> */ p5.FFT.prototype.getCentroid = function () { var nyquist = p5sound.audiocontext.sampleRate / 2; var cumulative_sum = 0; var centroid_normalization = 0; for (var i = 0; i < this.freqDomain.length; i++) { cumulative_sum += i * this.freqDomain[i]; centroid_normalization += this.freqDomain[i]; } var mean_freq_index = 0; if (centroid_normalization != 0) { mean_freq_index = cumulative_sum / centroid_normalization; } var spec_centroid_freq = mean_freq_index * (nyquist / this.freqDomain.length); return spec_centroid_freq; }; /** * Smooth FFT analysis by averaging with the last analysis frame. * * @method smooth * @param {Number} smoothing 0.0 < smoothing < 1.0. * Defaults to 0.8. */ p5.FFT.prototype.smooth = function (s) { if (s) { this.smoothing = s; } this.analyser.smoothingTimeConstant = s; }; p5.FFT.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this.analyser.disconnect(); this.analyser = undefined; }; // helper methods to convert type from float (dB) to int (0-255) var freqToFloat = function (fft) { if (fft.freqDomain instanceof Float32Array === false) { fft.freqDomain = new Float32Array(fft.analyser.frequencyBinCount); } }; var freqToInt = function (fft) { if (fft.freqDomain instanceof Uint8Array === false) { fft.freqDomain = new Uint8Array(fft.analyser.frequencyBinCount); } }; var timeToFloat = function (fft) { if (fft.timeDomain instanceof Float32Array === false) { fft.timeDomain = new Float32Array(fft.analyser.frequencyBinCount); } }; var timeToInt = function (fft) { if (fft.timeDomain instanceof Uint8Array === false) { fft.timeDomain = new Uint8Array(fft.analyser.frequencyBinCount); } }; }(master); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_core_Tone; Tone_core_Tone = function () { 'use strict'; function isUndef(val) { return val === void 0; } function isFunction(val) { return typeof val === 'function'; } var audioContext; if (isUndef(window.AudioContext)) { window.AudioContext = window.webkitAudioContext; } if (isUndef(window.OfflineAudioContext)) { window.OfflineAudioContext = window.webkitOfflineAudioContext; } if (!isUndef(AudioContext)) { audioContext = new AudioContext(); } else { throw new Error('Web Audio is not supported in this browser'); } if (!isFunction(AudioContext.prototype.createGain)) { AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; } if (!isFunction(AudioContext.prototype.createDelay)) { AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; } if (!isFunction(AudioContext.prototype.createPeriodicWave)) { AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; } if (!isFunction(AudioBufferSourceNode.prototype.start)) { AudioBufferSourceNode.prototype.start = AudioBufferSourceNode.prototype.noteGrainOn; } if (!isFunction(AudioBufferSourceNode.prototype.stop)) { AudioBufferSourceNode.prototype.stop = AudioBufferSourceNode.prototype.noteOff; } if (!isFunction(OscillatorNode.prototype.start)) { OscillatorNode.prototype.start = OscillatorNode.prototype.noteOn; } if (!isFunction(OscillatorNode.prototype.stop)) { OscillatorNode.prototype.stop = OscillatorNode.prototype.noteOff; } if (!isFunction(OscillatorNode.prototype.setPeriodicWave)) { OscillatorNode.prototype.setPeriodicWave = OscillatorNode.prototype.setWaveTable; } AudioNode.prototype._nativeConnect = AudioNode.prototype.connect; AudioNode.prototype.connect = function (B, outNum, inNum) { if (B.input) { if (Array.isArray(B.input)) { if (isUndef(inNum)) { inNum = 0; } this.connect(B.input[inNum]); } else { this.connect(B.input, outNum, inNum); } } else { try { if (B instanceof AudioNode) { this._nativeConnect(B, outNum, inNum); } else { this._nativeConnect(B, outNum); } } catch (e) { throw new Error('error connecting to node: ' + B); } } }; var Tone = function (inputs, outputs) { if (isUndef(inputs) || inputs === 1) { this.input = this.context.createGain(); } else if (inputs > 1) { this.input = new Array(inputs); } if (isUndef(outputs) || outputs === 1) { this.output = this.context.createGain(); } else if (outputs > 1) { this.output = new Array(inputs); } }; Tone.prototype.set = function (params, value, rampTime) { if (this.isObject(params)) { rampTime = value; } else if (this.isString(params)) { var tmpObj = {}; tmpObj[params] = value; params = tmpObj; } for (var attr in params) { value = params[attr]; var parent = this; if (attr.indexOf('.') !== -1) { var attrSplit = attr.split('.'); for (var i = 0; i < attrSplit.length - 1; i++) { parent = parent[attrSplit[i]]; } attr = attrSplit[attrSplit.length - 1]; } var param = parent[attr]; if (isUndef(param)) { continue; } if (Tone.Signal && param instanceof Tone.Signal || Tone.Param && param instanceof Tone.Param) { if (param.value !== value) { if (isUndef(rampTime)) { param.value = value; } else { param.rampTo(value, rampTime); } } } else if (param instanceof AudioParam) { if (param.value !== value) { param.value = value; } } else if (param instanceof Tone) { param.set(value); } else if (param !== value) { parent[attr] = value; } } return this; }; Tone.prototype.get = function (params) { if (isUndef(params)) { params = this._collectDefaults(this.constructor); } else if (this.isString(params)) { params = [params]; } var ret = {}; for (var i = 0; i < params.length; i++) { var attr = params[i]; var parent = this; var subRet = ret; if (attr.indexOf('.') !== -1) { var attrSplit = attr.split('.'); for (var j = 0; j < attrSplit.length - 1; j++) { var subAttr = attrSplit[j]; subRet[subAttr] = subRet[subAttr] || {}; subRet = subRet[subAttr]; parent = parent[subAttr]; } attr = attrSplit[attrSplit.length - 1]; } var param = parent[attr]; if (this.isObject(params[attr])) { subRet[attr] = param.get(); } else if (Tone.Signal && param instanceof Tone.Signal) { subRet[attr] = param.value; } else if (Tone.Param && param instanceof Tone.Param) { subRet[attr] = param.value; } else if (param instanceof AudioParam) { subRet[attr] = param.value; } else if (param instanceof Tone) { subRet[attr] = param.get(); } else if (!isFunction(param) && !isUndef(param)) { subRet[attr] = param; } } return ret; }; Tone.prototype._collectDefaults = function (constr) { var ret = []; if (!isUndef(constr.defaults)) { ret = Object.keys(constr.defaults); } if (!isUndef(constr._super)) { var superDefs = this._collectDefaults(constr._super); for (var i = 0; i < superDefs.length; i++) { if (ret.indexOf(superDefs[i]) === -1) { ret.push(superDefs[i]); } } } return ret; }; Tone.prototype.toString = function () { for (var className in Tone) { var isLetter = className[0].match(/^[A-Z]$/); var sameConstructor = Tone[className] === this.constructor; if (isFunction(Tone[className]) && isLetter && sameConstructor) { return className; } } return 'Tone'; }; Tone.context = audioContext; Tone.prototype.context = Tone.context; Tone.prototype.bufferSize = 2048; Tone.prototype.blockTime = 128 / Tone.context.sampleRate; Tone.prototype.dispose = function () { if (!this.isUndef(this.input)) { if (this.input instanceof AudioNode) { this.input.disconnect(); } this.input = null; } if (!this.isUndef(this.output)) { if (this.output instanceof AudioNode) { this.output.disconnect(); } this.output = null; } return this; }; var _silentNode = null; Tone.prototype.noGC = function () { this.output.connect(_silentNode); return this; }; AudioNode.prototype.noGC = function () { this.connect(_silentNode); return this; }; Tone.prototype.connect = function (unit, outputNum, inputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].connect(unit, 0, inputNum); } else { this.output.connect(unit, outputNum, inputNum); } return this; }; Tone.prototype.disconnect = function (outputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].disconnect(); } else { this.output.disconnect(); } return this; }; Tone.prototype.connectSeries = function () { if (arguments.length > 1) { var currentUnit = arguments[0]; for (var i = 1; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } return this; }; Tone.prototype.connectParallel = function () { var connectFrom = arguments[0]; if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { var connectTo = arguments[i]; connectFrom.connect(connectTo); } } return this; }; Tone.prototype.chain = function () { if (arguments.length > 0) { var currentUnit = this; for (var i = 0; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } return this; }; Tone.prototype.fan = function () { if (arguments.length > 0) { for (var i = 0; i < arguments.length; i++) { this.connect(arguments[i]); } } return this; }; AudioNode.prototype.chain = Tone.prototype.chain; AudioNode.prototype.fan = Tone.prototype.fan; Tone.prototype.defaultArg = function (given, fallback) { if (this.isObject(given) && this.isObject(fallback)) { var ret = {}; for (var givenProp in given) { ret[givenProp] = this.defaultArg(fallback[givenProp], given[givenProp]); } for (var fallbackProp in fallback) { ret[fallbackProp] = this.defaultArg(given[fallbackProp], fallback[fallbackProp]); } return ret; } else { return isUndef(given) ? fallback : given; } }; Tone.prototype.optionsObject = function (values, keys, defaults) { var options = {}; if (values.length === 1 && this.isObject(values[0])) { options = values[0]; } else { for (var i = 0; i < keys.length; i++) { options[keys[i]] = values[i]; } } if (!this.isUndef(defaults)) { return this.defaultArg(options, defaults); } else { return options; } }; Tone.prototype.isUndef = isUndef; Tone.prototype.isFunction = isFunction; Tone.prototype.isNumber = function (arg) { return typeof arg === 'number'; }; Tone.prototype.isObject = function (arg) { return Object.prototype.toString.call(arg) === '[object Object]' && arg.constructor === Object; }; Tone.prototype.isBoolean = function (arg) { return typeof arg === 'boolean'; }; Tone.prototype.isArray = function (arg) { return Array.isArray(arg); }; Tone.prototype.isString = function (arg) { return typeof arg === 'string'; }; Tone.noOp = function () { }; Tone.prototype._readOnly = function (property) { if (Array.isArray(property)) { for (var i = 0; i < property.length; i++) { this._readOnly(property[i]); } } else { Object.defineProperty(this, property, { writable: false, enumerable: true }); } }; Tone.prototype._writable = function (property) { if (Array.isArray(property)) { for (var i = 0; i < property.length; i++) { this._writable(property[i]); } } else { Object.defineProperty(this, property, { writable: true }); } }; Tone.State = { Started: 'started', Stopped: 'stopped', Paused: 'paused' }; Tone.prototype.equalPowerScale = function (percent) { var piFactor = 0.5 * Math.PI; return Math.sin(percent * piFactor); }; Tone.prototype.dbToGain = function (db) { return Math.pow(2, db / 6); }; Tone.prototype.gainToDb = function (gain) { return 20 * (Math.log(gain) / Math.LN10); }; Tone.prototype.now = function () { return this.context.currentTime; }; Tone.extend = function (child, parent) { if (isUndef(parent)) { parent = Tone; } function TempConstructor() { } TempConstructor.prototype = parent.prototype; child.prototype = new TempConstructor(); child.prototype.constructor = child; child._super = parent; }; var newContextCallbacks = []; Tone._initAudioContext = function (callback) { callback(Tone.context); newContextCallbacks.push(callback); }; Tone.setContext = function (ctx) { Tone.prototype.context = ctx; Tone.context = ctx; for (var i = 0; i < newContextCallbacks.length; i++) { newContextCallbacks[i](ctx); } }; Tone.startMobile = function () { var osc = Tone.context.createOscillator(); var silent = Tone.context.createGain(); silent.gain.value = 0; osc.connect(silent); silent.connect(Tone.context.destination); var now = Tone.context.currentTime; osc.start(now); osc.stop(now + 1); }; Tone._initAudioContext(function (audioContext) { Tone.prototype.blockTime = 128 / audioContext.sampleRate; _silentNode = audioContext.createGain(); _silentNode.gain.value = 0; _silentNode.connect(audioContext.destination); }); Tone.version = 'r7-dev'; return Tone; }(); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_signal_SignalBase; Tone_signal_SignalBase = function (Tone) { 'use strict'; Tone.SignalBase = function () { }; Tone.extend(Tone.SignalBase); Tone.SignalBase.prototype.connect = function (node, outputNumber, inputNumber) { if (Tone.Signal && Tone.Signal === node.constructor || Tone.Param && Tone.Param === node.constructor || Tone.TimelineSignal && Tone.TimelineSignal === node.constructor) { node._param.cancelScheduledValues(0); node._param.value = 0; node.overridden = true; } else if (node instanceof AudioParam) { node.cancelScheduledValues(0); node.value = 0; } Tone.prototype.connect.call(this, node, outputNumber, inputNumber); return this; }; return Tone.SignalBase; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_signal_WaveShaper; Tone_signal_WaveShaper = function (Tone) { 'use strict'; Tone.WaveShaper = function (mapping, bufferLen) { this._shaper = this.input = this.output = this.context.createWaveShaper(); this._curve = null; if (Array.isArray(mapping)) { this.curve = mapping; } else if (isFinite(mapping) || this.isUndef(mapping)) { this._curve = new Float32Array(this.defaultArg(mapping, 1024)); } else if (this.isFunction(mapping)) { this._curve = new Float32Array(this.defaultArg(bufferLen, 1024)); this.setMap(mapping); } }; Tone.extend(Tone.WaveShaper, Tone.SignalBase); Tone.WaveShaper.prototype.setMap = function (mapping) { for (var i = 0, len = this._curve.length; i < len; i++) { var normalized = i / len * 2 - 1; this._curve[i] = mapping(normalized, i); } this._shaper.curve = this._curve; return this; }; Object.defineProperty(Tone.WaveShaper.prototype, 'curve', { get: function () { return this._shaper.curve; }, set: function (mapping) { this._curve = new Float32Array(mapping); this._shaper.curve = this._curve; } }); Object.defineProperty(Tone.WaveShaper.prototype, 'oversample', { get: function () { return this._shaper.oversample; }, set: function (oversampling) { if ([ 'none', '2x', '4x' ].indexOf(oversampling) !== -1) { this._shaper.oversample = oversampling; } else { throw new Error('invalid oversampling: ' + oversampling); } } }); Tone.WaveShaper.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._shaper.disconnect(); this._shaper = null; this._curve = null; return this; }; return Tone.WaveShaper; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_core_Type; Tone_core_Type = function (Tone) { 'use strict'; Tone.Type = { Default: 'number', Time: 'time', Frequency: 'frequency', NormalRange: 'normalRange', AudioRange: 'audioRange', Decibels: 'db', Interval: 'interval', BPM: 'bpm', Positive: 'positive', Cents: 'cents', Degrees: 'degrees', MIDI: 'midi', TransportTime: 'transportTime', Ticks: 'tick', Note: 'note', Milliseconds: 'milliseconds', Notation: 'notation' }; Tone.prototype.isNowRelative = function () { var nowRelative = new RegExp(/^\s*\+(.)+/i); return function (note) { return nowRelative.test(note); }; }(); Tone.prototype.isTicks = function () { var tickFormat = new RegExp(/^\d+i$/i); return function (note) { return tickFormat.test(note); }; }(); Tone.prototype.isNotation = function () { var notationFormat = new RegExp(/^[0-9]+[mnt]$/i); return function (note) { return notationFormat.test(note); }; }(); Tone.prototype.isTransportTime = function () { var transportTimeFormat = new RegExp(/^(\d+(\.\d+)?\:){1,2}(\d+(\.\d+)?)?$/i); return function (transportTime) { return transportTimeFormat.test(transportTime); }; }(); Tone.prototype.isNote = function () { var noteFormat = new RegExp(/^[a-g]{1}(b|#|x|bb)?-?[0-9]+$/i); return function (note) { return noteFormat.test(note); }; }(); Tone.prototype.isFrequency = function () { var freqFormat = new RegExp(/^\d*\.?\d+hz$/i); return function (freq) { return freqFormat.test(freq); }; }(); function getTransportBpm() { if (Tone.Transport && Tone.Transport.bpm) { return Tone.Transport.bpm.value; } else { return 120; } } function getTransportTimeSignature() { if (Tone.Transport && Tone.Transport.timeSignature) { return Tone.Transport.timeSignature; } else { return 4; } } Tone.prototype.notationToSeconds = function (notation, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var beatTime = 60 / bpm; if (notation === '1n') { notation = '1m'; } var subdivision = parseInt(notation, 10); var beats = 0; if (subdivision === 0) { beats = 0; } var lastLetter = notation.slice(-1); if (lastLetter === 't') { beats = 4 / subdivision * 2 / 3; } else if (lastLetter === 'n') { beats = 4 / subdivision; } else if (lastLetter === 'm') { beats = subdivision * timeSignature; } else { beats = 0; } return beatTime * beats; }; Tone.prototype.transportTimeToSeconds = function (transportTime, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var measures = 0; var quarters = 0; var sixteenths = 0; var split = transportTime.split(':'); if (split.length === 2) { measures = parseFloat(split[0]); quarters = parseFloat(split[1]); } else if (split.length === 1) { quarters = parseFloat(split[0]); } else if (split.length === 3) { measures = parseFloat(split[0]); quarters = parseFloat(split[1]); sixteenths = parseFloat(split[2]); } var beats = measures * timeSignature + quarters + sixteenths / 4; return beats * (60 / bpm); }; Tone.prototype.ticksToSeconds = function (ticks, bpm) { if (this.isUndef(Tone.Transport)) { return 0; } ticks = parseFloat(ticks); bpm = this.defaultArg(bpm, getTransportBpm()); var tickTime = 60 / bpm / Tone.Transport.PPQ; return tickTime * ticks; }; Tone.prototype.frequencyToSeconds = function (freq) { return 1 / parseFloat(freq); }; Tone.prototype.samplesToSeconds = function (samples) { return samples / this.context.sampleRate; }; Tone.prototype.secondsToSamples = function (seconds) { return seconds * this.context.sampleRate; }; Tone.prototype.secondsToTransportTime = function (seconds, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var quarterTime = 60 / bpm; var quarters = seconds / quarterTime; var measures = Math.floor(quarters / timeSignature); var sixteenths = quarters % 1 * 4; quarters = Math.floor(quarters) % timeSignature; var progress = [ measures, quarters, sixteenths ]; return progress.join(':'); }; Tone.prototype.secondsToFrequency = function (seconds) { return 1 / seconds; }; Tone.prototype.toTransportTime = function (time, bpm, timeSignature) { var seconds = this.toSeconds(time); return this.secondsToTransportTime(seconds, bpm, timeSignature); }; Tone.prototype.toFrequency = function (freq, now) { if (this.isFrequency(freq)) { return parseFloat(freq); } else if (this.isNotation(freq) || this.isTransportTime(freq)) { return this.secondsToFrequency(this.toSeconds(freq, now)); } else if (this.isNote(freq)) { return this.noteToFrequency(freq); } else { return freq; } }; Tone.prototype.toTicks = function (time) { if (this.isUndef(Tone.Transport)) { return 0; } var bpm = Tone.Transport.bpm.value; var plusNow = 0; if (this.isNowRelative(time)) { time = time.replace('+', ''); plusNow = Tone.Transport.ticks; } else if (this.isUndef(time)) { return Tone.Transport.ticks; } var seconds = this.toSeconds(time); var quarter = 60 / bpm; var quarters = seconds / quarter; var tickNum = quarters * Tone.Transport.PPQ; return Math.round(tickNum + plusNow); }; Tone.prototype.toSamples = function (time) { var seconds = this.toSeconds(time); return Math.round(seconds * this.context.sampleRate); }; Tone.prototype.toSeconds = function (time, now) { now = this.defaultArg(now, this.now()); if (this.isNumber(time)) { return time; } else if (this.isString(time)) { var plusTime = 0; if (this.isNowRelative(time)) { time = time.replace('+', ''); plusTime = now; } var betweenParens = time.match(/\(([^)(]+)\)/g); if (betweenParens) { for (var j = 0; j < betweenParens.length; j++) { var symbol = betweenParens[j].replace(/[\(\)]/g, ''); var symbolVal = this.toSeconds(symbol); time = time.replace(betweenParens[j], symbolVal); } } if (time.indexOf('@') !== -1) { var quantizationSplit = time.split('@'); if (!this.isUndef(Tone.Transport)) { var toQuantize = quantizationSplit[0].trim(); if (toQuantize === '') { toQuantize = undefined; } if (plusTime > 0) { toQuantize = '+' + toQuantize; plusTime = 0; } var subdivision = quantizationSplit[1].trim(); time = Tone.Transport.quantize(toQuantize, subdivision); } else { throw new Error('quantization requires Tone.Transport'); } } else { var components = time.split(/[\(\)\-\+\/\*]/); if (components.length > 1) { var originalTime = time; for (var i = 0; i < components.length; i++) { var symb = components[i].trim(); if (symb !== '') { var val = this.toSeconds(symb); time = time.replace(symb, val); } } try { time = eval(time); } catch (e) { throw new EvalError('cannot evaluate Time: ' + originalTime); } } else if (this.isNotation(time)) { time = this.notationToSeconds(time); } else if (this.isTransportTime(time)) { time = this.transportTimeToSeconds(time); } else if (this.isFrequency(time)) { time = this.frequencyToSeconds(time); } else if (this.isTicks(time)) { time = this.ticksToSeconds(time); } else { time = parseFloat(time); } } return time + plusTime; } else { return now; } }; Tone.prototype.toNotation = function (time, bpm, timeSignature) { var testNotations = [ '1m', '2n', '4n', '8n', '16n', '32n', '64n', '128n' ]; var retNotation = toNotationHelper.call(this, time, bpm, timeSignature, testNotations); var testTripletNotations = [ '1m', '2n', '2t', '4n', '4t', '8n', '8t', '16n', '16t', '32n', '32t', '64n', '64t', '128n' ]; var retTripletNotation = toNotationHelper.call(this, time, bpm, timeSignature, testTripletNotations); if (retTripletNotation.split('+').length < retNotation.split('+').length) { return retTripletNotation; } else { return retNotation; } }; function toNotationHelper(time, bpm, timeSignature, testNotations) { var seconds = this.toSeconds(time); var threshold = this.notationToSeconds(testNotations[testNotations.length - 1], bpm, timeSignature); var retNotation = ''; for (var i = 0; i < testNotations.length; i++) { var notationTime = this.notationToSeconds(testNotations[i], bpm, timeSignature); var multiple = seconds / notationTime; var floatingPointError = 0.000001; if (1 - multiple % 1 < floatingPointError) { multiple += floatingPointError; } multiple = Math.floor(multiple); if (multiple > 0) { if (multiple === 1) { retNotation += testNotations[i]; } else { retNotation += multiple.toString() + '*' + testNotations[i]; } seconds -= multiple * notationTime; if (seconds < threshold) { break; } else { retNotation += ' + '; } } } if (retNotation === '') { retNotation = '0'; } return retNotation; } Tone.prototype.fromUnits = function (val, units) { if (this.convert || this.isUndef(this.convert)) { switch (units) { case Tone.Type.Time: return this.toSeconds(val); case Tone.Type.Frequency: return this.toFrequency(val); case Tone.Type.Decibels: return this.dbToGain(val); case Tone.Type.NormalRange: return Math.min(Math.max(val, 0), 1); case Tone.Type.AudioRange: return Math.min(Math.max(val, -1), 1); case Tone.Type.Positive: return Math.max(val, 0); default: return val; } } else { return val; } }; Tone.prototype.toUnits = function (val, units) { if (this.convert || this.isUndef(this.convert)) { switch (units) { case Tone.Type.Decibels: return this.gainToDb(val); default: return val; } } else { return val; } }; var noteToScaleIndex = { 'cbb': -2, 'cb': -1, 'c': 0, 'c#': 1, 'cx': 2, 'dbb': 0, 'db': 1, 'd': 2, 'd#': 3, 'dx': 4, 'ebb': 2, 'eb': 3, 'e': 4, 'e#': 5, 'ex': 6, 'fbb': 3, 'fb': 4, 'f': 5, 'f#': 6, 'fx': 7, 'gbb': 5, 'gb': 6, 'g': 7, 'g#': 8, 'gx': 9, 'abb': 7, 'ab': 8, 'a': 9, 'a#': 10, 'ax': 11, 'bbb': 9, 'bb': 10, 'b': 11, 'b#': 12, 'bx': 13 }; var scaleIndexToNote = [ 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B' ]; Tone.A4 = 440; Tone.prototype.noteToFrequency = function (note) { var parts = note.split(/(-?\d+)/); if (parts.length === 3) { var index = noteToScaleIndex[parts[0].toLowerCase()]; var octave = parts[1]; var noteNumber = index + (parseInt(octave, 10) + 1) * 12; return this.midiToFrequency(noteNumber); } else { return 0; } }; Tone.prototype.frequencyToNote = function (freq) { var log = Math.log(freq / Tone.A4) / Math.LN2; var noteNumber = Math.round(12 * log) + 57; var octave = Math.floor(noteNumber / 12); if (octave < 0) { noteNumber += -12 * octave; } var noteName = scaleIndexToNote[noteNumber % 12]; return noteName + octave.toString(); }; Tone.prototype.intervalToFrequencyRatio = function (interval) { return Math.pow(2, interval / 12); }; Tone.prototype.midiToNote = function (midiNumber) { var octave = Math.floor(midiNumber / 12) - 1; var note = midiNumber % 12; return scaleIndexToNote[note] + octave; }; Tone.prototype.noteToMidi = function (note) { var parts = note.split(/(\d+)/); if (parts.length === 3) { var index = noteToScaleIndex[parts[0].toLowerCase()]; var octave = parts[1]; return index + (parseInt(octave, 10) + 1) * 12; } else { return 0; } }; Tone.prototype.midiToFrequency = function (midi) { return Tone.A4 * Math.pow(2, (midi - 69) / 12); }; return Tone; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_core_Param; Tone_core_Param = function (Tone) { 'use strict'; Tone.Param = function () { var options = this.optionsObject(arguments, [ 'param', 'units', 'convert' ], Tone.Param.defaults); this._param = this.input = options.param; this.units = options.units; this.convert = options.convert; this.overridden = false; if (!this.isUndef(options.value)) { this.value = options.value; } }; Tone.extend(Tone.Param); Tone.Param.defaults = { 'units': Tone.Type.Default, 'convert': true, 'param': undefined }; Object.defineProperty(Tone.Param.prototype, 'value', { get: function () { return this._toUnits(this._param.value); }, set: function (value) { var convertedVal = this._fromUnits(value); this._param.value = convertedVal; } }); Tone.Param.prototype._fromUnits = function (val) { if (this.convert || this.isUndef(this.convert)) { switch (this.units) { case Tone.Type.Time: return this.toSeconds(val); case Tone.Type.Frequency: return this.toFrequency(val); case Tone.Type.Decibels: return this.dbToGain(val); case Tone.Type.NormalRange: return Math.min(Math.max(val, 0), 1); case Tone.Type.AudioRange: return Math.min(Math.max(val, -1), 1); case Tone.Type.Positive: return Math.max(val, 0); default: return val; } } else { return val; } }; Tone.Param.prototype._toUnits = function (val) { if (this.convert || this.isUndef(this.convert)) { switch (this.units) { case Tone.Type.Decibels: return this.gainToDb(val); default: return val; } } else { return val; } }; Tone.Param.prototype._minOutput = 0.00001; Tone.Param.prototype.setValueAtTime = function (value, time) { value = this._fromUnits(value); this._param.setValueAtTime(value, this.toSeconds(time)); return this; }; Tone.Param.prototype.setRampPoint = function (now) { now = this.defaultArg(now, this.now()); var currentVal = this._param.value; this._param.setValueAtTime(currentVal, now); return this; }; Tone.Param.prototype.linearRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); this._param.linearRampToValueAtTime(value, this.toSeconds(endTime)); return this; }; Tone.Param.prototype.exponentialRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); this._param.exponentialRampToValueAtTime(value, this.toSeconds(endTime)); return this; }; Tone.Param.prototype.exponentialRampToValue = function (value, rampTime) { var now = this.now(); var currentVal = this.value; this.setValueAtTime(Math.max(currentVal, this._minOutput), now); this.exponentialRampToValueAtTime(value, now + this.toSeconds(rampTime)); return this; }; Tone.Param.prototype.linearRampToValue = function (value, rampTime) { var now = this.now(); this.setRampPoint(now); this.linearRampToValueAtTime(value, now + this.toSeconds(rampTime)); return this; }; Tone.Param.prototype.setTargetAtTime = function (value, startTime, timeConstant) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); timeConstant = Math.max(this._minOutput, timeConstant); this._param.setTargetAtTime(value, this.toSeconds(startTime), timeConstant); return this; }; Tone.Param.prototype.setValueCurveAtTime = function (values, startTime, duration) { for (var i = 0; i < values.length; i++) { values[i] = this._fromUnits(values[i]); } this._param.setValueCurveAtTime(values, this.toSeconds(startTime), this.toSeconds(duration)); return this; }; Tone.Param.prototype.cancelScheduledValues = function (startTime) { this._param.cancelScheduledValues(this.toSeconds(startTime)); return this; }; Tone.Param.prototype.rampTo = function (value, rampTime) { rampTime = this.defaultArg(rampTime, 0); if (this.units === Tone.Type.Frequency || this.units === Tone.Type.BPM) { this.exponentialRampToValue(value, rampTime); } else { this.linearRampToValue(value, rampTime); } return this; }; Tone.Param.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param = null; return this; }; return Tone.Param; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_core_Gain; Tone_core_Gain = function (Tone) { 'use strict'; Tone.Gain = function () { var options = this.optionsObject(arguments, [ 'gain', 'units' ], Tone.Gain.defaults); this.input = this.output = this._gainNode = this.context.createGain(); this.gain = new Tone.Param({ 'param': this._gainNode.gain, 'units': options.units, 'value': options.gain, 'convert': options.convert }); this._readOnly('gain'); }; Tone.extend(Tone.Gain); Tone.Gain.defaults = { 'gain': 1, 'convert': true }; Tone.Gain.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._gainNode.disconnect(); this._gainNode = null; this._writable('gain'); this.gain.dispose(); this.gain = null; }; return Tone.Gain; }(Tone_core_Tone, Tone_core_Param); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_signal_Signal; Tone_signal_Signal = function (Tone) { 'use strict'; Tone.Signal = function () { var options = this.optionsObject(arguments, [ 'value', 'units' ], Tone.Signal.defaults); this.output = this._gain = this.context.createGain(); options.param = this._gain.gain; Tone.Param.call(this, options); this.input = this._param = this._gain.gain; Tone.Signal._constant.chain(this._gain); }; Tone.extend(Tone.Signal, Tone.Param); Tone.Signal.defaults = { 'value': 0, 'units': Tone.Type.Default, 'convert': true }; Tone.Signal.prototype.connect = Tone.SignalBase.prototype.connect; Tone.Signal.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._param = null; this._gain.disconnect(); this._gain = null; return this; }; Tone.Signal._constant = null; Tone._initAudioContext(function (audioContext) { var buffer = audioContext.createBuffer(1, 128, audioContext.sampleRate); var arr = buffer.getChannelData(0); for (var i = 0; i < arr.length; i++) { arr[i] = 1; } Tone.Signal._constant = audioContext.createBufferSource(); Tone.Signal._constant.channelCount = 1; Tone.Signal._constant.channelCountMode = 'explicit'; Tone.Signal._constant.buffer = buffer; Tone.Signal._constant.loop = true; Tone.Signal._constant.start(0); Tone.Signal._constant.noGC(); }); return Tone.Signal; }(Tone_core_Tone, Tone_signal_WaveShaper, Tone_core_Type, Tone_core_Param); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_signal_Add; Tone_signal_Add = function (Tone) { 'use strict'; Tone.Add = function (value) { Tone.call(this, 2, 0); this._sum = this.input[0] = this.input[1] = this.output = this.context.createGain(); this._param = this.input[1] = new Tone.Signal(value); this._param.connect(this._sum); }; Tone.extend(Tone.Add, Tone.Signal); Tone.Add.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sum.disconnect(); this._sum = null; this._param.dispose(); this._param = null; return this; }; return Tone.Add; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_signal_Multiply; Tone_signal_Multiply = function (Tone) { 'use strict'; Tone.Multiply = function (value) { Tone.call(this, 2, 0); this._mult = this.input[0] = this.output = this.context.createGain(); this._param = this.input[1] = this.output.gain; this._param.value = this.defaultArg(value, 0); }; Tone.extend(Tone.Multiply, Tone.Signal); Tone.Multiply.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._mult.disconnect(); this._mult = null; this._param = null; return this; }; return Tone.Multiply; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_signal_Scale; Tone_signal_Scale = function (Tone) { 'use strict'; Tone.Scale = function (outputMin, outputMax) { this._outputMin = this.defaultArg(outputMin, 0); this._outputMax = this.defaultArg(outputMax, 1); this._scale = this.input = new Tone.Multiply(1); this._add = this.output = new Tone.Add(0); this._scale.connect(this._add); this._setRange(); }; Tone.extend(Tone.Scale, Tone.SignalBase); Object.defineProperty(Tone.Scale.prototype, 'min', { get: function () { return this._outputMin; }, set: function (min) { this._outputMin = min; this._setRange(); } }); Object.defineProperty(Tone.Scale.prototype, 'max', { get: function () { return this._outputMax; }, set: function (max) { this._outputMax = max; this._setRange(); } }); Tone.Scale.prototype._setRange = function () { this._add.value = this._outputMin; this._scale.value = this._outputMax - this._outputMin; }; Tone.Scale.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._add.dispose(); this._add = null; this._scale.dispose(); this._scale = null; return this; }; return Tone.Scale; }(Tone_core_Tone, Tone_signal_Add, Tone_signal_Multiply); var signal; signal = function () { 'use strict'; // Signal is built with the Tone.js signal by Yotam Mann // https://github.com/TONEnoTONE/Tone.js/ var Signal = Tone_signal_Signal; var Add = Tone_signal_Add; var Mult = Tone_signal_Multiply; var Scale = Tone_signal_Scale; var Tone = Tone_core_Tone; var p5sound = master; Tone.setContext(p5sound.audiocontext); /** * <p>p5.Signal is a constant audio-rate signal used by p5.Oscillator * and p5.Envelope for modulation math.</p> * * <p>This is necessary because Web Audio is processed on a seprate clock. * For example, the p5 draw loop runs about 60 times per second. But * the audio clock must process samples 44100 times per second. If we * want to add a value to each of those samples, we can't do it in the * draw loop, but we can do it by adding a constant-rate audio signal.</p. * * <p>This class mostly functions behind the scenes in p5.sound, and returns * a Tone.Signal from the Tone.js library by Yotam Mann. * If you want to work directly with audio signals for modular * synthesis, check out * <a href='http://bit.ly/1oIoEng' target=_'blank'>tone.js.</a></p> * * @class p5.Signal * @constructor * @return {Tone.Signal} A Signal object from the Tone.js library * @example * <div><code> * function setup() { * carrier = new p5.Oscillator('sine'); * carrier.amp(1); // set amplitude * carrier.freq(220); // set frequency * carrier.start(); // start oscillating * * modulator = new p5.Oscillator('sawtooth'); * modulator.disconnect(); * modulator.amp(1); * modulator.freq(4); * modulator.start(); * * // Modulator's default amplitude range is -1 to 1. * // Multiply it by -200, so the range is -200 to 200 * // then add 220 so the range is 20 to 420 * carrier.freq( modulator.mult(-200).add(220) ); * } * </code></div> */ p5.Signal = function (value) { var s = new Signal(value); // p5sound.soundArray.push(s); return s; }; /** * Fade to value, for smooth transitions * * @method fade * @param {Number} value Value to set this signal * @param {[Number]} secondsFromNow Length of fade, in seconds from now */ Signal.prototype.fade = Signal.prototype.linearRampToValueAtTime; Mult.prototype.fade = Signal.prototype.fade; Add.prototype.fade = Signal.prototype.fade; Scale.prototype.fade = Signal.prototype.fade; /** * Connect a p5.sound object or Web Audio node to this * p5.Signal so that its amplitude values can be scaled. * * @param {Object} input */ Signal.prototype.setInput = function (_input) { _input.connect(this); }; Mult.prototype.setInput = Signal.prototype.setInput; Add.prototype.setInput = Signal.prototype.setInput; Scale.prototype.setInput = Signal.prototype.setInput; // signals can add / mult / scale themselves /** * Add a constant value to this audio signal, * and return the resulting audio signal. Does * not change the value of the original signal, * instead it returns a new p5.SignalAdd. * * @method add * @param {Number} number * @return {p5.SignalAdd} object */ Signal.prototype.add = function (num) { var add = new Add(num); // add.setInput(this); this.connect(add); return add; }; Mult.prototype.add = Signal.prototype.add; Add.prototype.add = Signal.prototype.add; Scale.prototype.add = Signal.prototype.add; /** * Multiply this signal by a constant value, * and return the resulting audio signal. Does * not change the value of the original signal, * instead it returns a new p5.SignalMult. * * @method mult * @param {Number} number to multiply * @return {Tone.Multiply} object */ Signal.prototype.mult = function (num) { var mult = new Mult(num); // mult.setInput(this); this.connect(mult); return mult; }; Mult.prototype.mult = Signal.prototype.mult; Add.prototype.mult = Signal.prototype.mult; Scale.prototype.mult = Signal.prototype.mult; /** * Scale this signal value to a given range, * and return the result as an audio signal. Does * not change the value of the original signal, * instead it returns a new p5.SignalScale. * * @method scale * @param {Number} number to multiply * @param {Number} inMin input range minumum * @param {Number} inMax input range maximum * @param {Number} outMin input range minumum * @param {Number} outMax input range maximum * @return {p5.SignalScale} object */ Signal.prototype.scale = function (inMin, inMax, outMin, outMax) { var mapOutMin, mapOutMax; if (arguments.length === 4) { mapOutMin = p5.prototype.map(outMin, inMin, inMax, 0, 1) - 0.5; mapOutMax = p5.prototype.map(outMax, inMin, inMax, 0, 1) - 0.5; } else { mapOutMin = arguments[0]; mapOutMax = arguments[1]; } var scale = new Scale(mapOutMin, mapOutMax); this.connect(scale); return scale; }; Mult.prototype.scale = Signal.prototype.scale; Add.prototype.scale = Signal.prototype.scale; Scale.prototype.scale = Signal.prototype.scale; }(Tone_signal_Signal, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale, Tone_core_Tone, master); var oscillator; oscillator = function () { 'use strict'; var p5sound = master; var Signal = Tone_signal_Signal; var Add = Tone_signal_Add; var Mult = Tone_signal_Multiply; var Scale = Tone_signal_Scale; /** * <p>Creates a signal that oscillates between -1.0 and 1.0. * By default, the oscillation takes the form of a sinusoidal * shape ('sine'). Additional types include 'triangle', * 'sawtooth' and 'square'. The frequency defaults to * 440 oscillations per second (440Hz, equal to the pitch of an * 'A' note).</p> * * <p>Set the type of oscillation with setType(), or by creating a * specific oscillator.</p> For example: * <code>new p5.SinOsc(freq)</code> * <code>new p5.TriOsc(freq)</code> * <code>new p5.SqrOsc(freq)</code> * <code>new p5.SawOsc(freq)</code>. * </p> * * @class p5.Oscillator * @constructor * @param {Number} [freq] frequency defaults to 440Hz * @param {String} [type] type of oscillator. Options: * 'sine' (default), 'triangle', * 'sawtooth', 'square' * @return {Object} Oscillator object * @example * <div><code> * var osc; * var playing = false; * * function setup() { * backgroundColor = color(255,0,255); * textAlign(CENTER); * * osc = new p5.Oscillator(); * osc.setType('sine'); * osc.freq(240); * osc.amp(0); * osc.start(); * } * * function draw() { * background(backgroundColor) * text('click to play', width/2, height/2); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) { * if (!playing) { * // ramp amplitude to 0.5 over 0.1 seconds * osc.amp(0.5, 0.05); * playing = true; * backgroundColor = color(0,255,255); * } else { * // ramp amplitude to 0 over 0.5 seconds * osc.amp(0, 0.5); * playing = false; * backgroundColor = color(255,0,255); * } * } * } * </code> </div> */ p5.Oscillator = function (freq, type) { if (typeof freq === 'string') { var f = type; type = freq; freq = f; } if (typeof type === 'number') { var f = type; type = freq; freq = f; } this.started = false; // components this.phaseAmount = undefined; this.oscillator = p5sound.audiocontext.createOscillator(); this.f = freq || 440; // frequency this.oscillator.frequency.setValueAtTime(this.f, p5sound.audiocontext.currentTime); this.oscillator.type = type || 'sine'; var o = this.oscillator; // connections this.input = p5sound.audiocontext.createGain(); this.output = p5sound.audiocontext.createGain(); this._freqMods = []; // modulators connected to this oscillator's frequency // set default output gain to 0.5 this.output.gain.value = 0.5; this.output.gain.setValueAtTime(0.5, p5sound.audiocontext.currentTime); this.oscillator.connect(this.output); // stereo panning this.panPosition = 0; this.connection = p5sound.input; // connect to p5sound by default this.panner = new p5.Panner(this.output, this.connection, 1); //array of math operation signal chaining this.mathOps = [this.output]; // add to the soundArray so we can dispose of the osc later p5sound.soundArray.push(this); }; /** * Start an oscillator. Accepts an optional parameter to * determine how long (in seconds from now) until the * oscillator starts. * * @method start * @param {Number} [time] startTime in seconds from now. * @param {Number} [frequency] frequency in Hz. */ p5.Oscillator.prototype.start = function (time, f) { if (this.started) { var now = p5sound.audiocontext.currentTime; this.stop(now); } if (!this.started) { var freq = f || this.f; var type = this.oscillator.type; // var detune = this.oscillator.frequency.value; this.oscillator = p5sound.audiocontext.createOscillator(); this.oscillator.frequency.exponentialRampToValueAtTime(Math.abs(freq), p5sound.audiocontext.currentTime); this.oscillator.type = type; // this.oscillator.detune.value = detune; this.oscillator.connect(this.output); time = time || 0; this.oscillator.start(time + p5sound.audiocontext.currentTime); this.freqNode = this.oscillator.frequency; // if other oscillators are already connected to this osc's freq for (var i in this._freqMods) { if (typeof this._freqMods[i].connect !== 'undefined') { this._freqMods[i].connect(this.oscillator.frequency); } } this.started = true; } }; /** * Stop an oscillator. Accepts an optional parameter * to determine how long (in seconds from now) until the * oscillator stops. * * @method stop * @param {Number} secondsFromNow Time, in seconds from now. */ p5.Oscillator.prototype.stop = function (time) { if (this.started) { var t = time || 0; var now = p5sound.audiocontext.currentTime; this.oscillator.stop(t + now); this.started = false; } }; /** * Set the amplitude between 0 and 1.0. Or, pass in an object * such as an oscillator to modulate amplitude with an audio signal. * * @method amp * @param {Number|Object} vol between 0 and 1.0 * or a modulating signal/oscillator * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now * @return {AudioParam} gain If no value is provided, * returns the Web Audio API * AudioParam that controls * this oscillator's * gain/amplitude/volume) */ p5.Oscillator.prototype.amp = function (vol, rampTime, tFromNow) { var self = this; if (typeof vol === 'number') { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); } else if (vol) { vol.connect(self.output.gain); } else { // return the Gain Node return this.output.gain; } }; // these are now the same thing p5.Oscillator.prototype.fade = p5.Oscillator.prototype.amp; p5.Oscillator.prototype.getAmp = function () { return this.output.gain.value; }; /** * Set frequency of an oscillator to a value. Or, pass in an object * such as an oscillator to modulate the frequency with an audio signal. * * @method freq * @param {Number|Object} Frequency Frequency in Hz * or modulating signal/oscillator * @param {Number} [rampTime] Ramp time (in seconds) * @param {Number} [timeFromNow] Schedule this event to happen * at x seconds from now * @return {AudioParam} Frequency If no value is provided, * returns the Web Audio API * AudioParam that controls * this oscillator's frequency * @example * <div><code> * var osc = new p5.Oscillator(300); * osc.start(); * osc.freq(40, 10); * </code></div> */ p5.Oscillator.prototype.freq = function (val, rampTime, tFromNow) { if (typeof val === 'number' && !isNaN(val)) { this.f = val; var now = p5sound.audiocontext.currentTime; var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; // var currentFreq = this.oscillator.frequency.value; // this.oscillator.frequency.cancelScheduledValues(now); if (rampTime == 0) { this.oscillator.frequency.cancelScheduledValues(now); this.oscillator.frequency.setValueAtTime(val, tFromNow + now); } else { if (val > 0) { this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); } else { this.oscillator.frequency.linearRampToValueAtTime(val, tFromNow + rampTime + now); } } // reset phase if oscillator has a phase if (this.phaseAmount) { this.phase(this.phaseAmount); } } else if (val) { if (val.output) { val = val.output; } val.connect(this.oscillator.frequency); // keep track of what is modulating this param // so it can be re-connected if this._freqMods.push(val); } else { // return the Frequency Node return this.oscillator.frequency; } }; p5.Oscillator.prototype.getFreq = function () { return this.oscillator.frequency.value; }; /** * Set type to 'sine', 'triangle', 'sawtooth' or 'square'. * * @method setType * @param {String} type 'sine', 'triangle', 'sawtooth' or 'square'. */ p5.Oscillator.prototype.setType = function (type) { this.oscillator.type = type; }; p5.Oscillator.prototype.getType = function () { return this.oscillator.type; }; /** * Connect to a p5.sound / Web Audio object. * * @method connect * @param {Object} unit A p5.sound or Web Audio object */ p5.Oscillator.prototype.connect = function (unit) { if (!unit) { this.panner.connect(p5sound.input); } else if (unit.hasOwnProperty('input')) { this.panner.connect(unit.input); this.connection = unit.input; } else { this.panner.connect(unit); this.connection = unit; } }; /** * Disconnect all outputs * * @method disconnect */ p5.Oscillator.prototype.disconnect = function (unit) { this.output.disconnect(); this.panner.disconnect(); this.output.connect(this.panner); this.oscMods = []; }; /** * Pan between Left (-1) and Right (1) * * @method pan * @param {Number} panning Number between -1 and 1 * @param {Number} timeFromNow schedule this event to happen * seconds from now */ p5.Oscillator.prototype.pan = function (pval, tFromNow) { this.panPosition = pval; this.panner.pan(pval, tFromNow); }; p5.Oscillator.prototype.getPan = function () { return this.panPosition; }; // get rid of the oscillator p5.Oscillator.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); if (this.oscillator) { var now = p5sound.audiocontext.currentTime; this.stop(now); this.disconnect(); this.oscillator.disconnect(); this.panner = null; this.oscillator = null; } // if it is a Pulse if (this.osc2) { this.osc2.dispose(); } }; /** * Set the phase of an oscillator between 0.0 and 1.0. * In this implementation, phase is a delay time * based on the oscillator's current frequency. * * @method phase * @param {Number} phase float between 0.0 and 1.0 */ p5.Oscillator.prototype.phase = function (p) { var delayAmt = p5.prototype.map(p, 0, 1, 0, 1 / this.f); var now = p5sound.audiocontext.currentTime; this.phaseAmount = p; if (!this.dNode) { // create a delay node this.dNode = p5sound.audiocontext.createDelay(); // put the delay node in between output and panner this.oscillator.disconnect(); this.oscillator.connect(this.dNode); this.dNode.connect(this.output); } // set delay time to match phase: this.dNode.delayTime.setValueAtTime(delayAmt, now); }; // ========================== // // SIGNAL MATH FOR MODULATION // // ========================== // // return sigChain(this, scale, thisChain, nextChain, Scale); var sigChain = function (o, mathObj, thisChain, nextChain, type) { var chainSource = o.oscillator; // if this type of math already exists in the chain, replace it for (var i in o.mathOps) { if (o.mathOps[i] instanceof type) { chainSource.disconnect(); o.mathOps[i].dispose(); thisChain = i; // assume nextChain is output gain node unless... if (thisChain < o.mathOps.length - 2) { nextChain = o.mathOps[i + 1]; } } } if (thisChain == o.mathOps.length - 1) { o.mathOps.push(nextChain); } // assume source is the oscillator unless i > 0 if (i > 0) { chainSource = o.mathOps[i - 1]; } chainSource.disconnect(); chainSource.connect(mathObj); mathObj.connect(nextChain); o.mathOps[thisChain] = mathObj; return o; }; /** * Add a value to the p5.Oscillator's output amplitude, * and return the oscillator. Calling this method again * will override the initial add() with a new value. * * @method add * @param {Number} number Constant number to add * @return {p5.Oscillator} Oscillator Returns this oscillator * with scaled output * */ p5.Oscillator.prototype.add = function (num) { var add = new Add(num); var thisChain = this.mathOps.length - 1; var nextChain = this.output; return sigChain(this, add, thisChain, nextChain, Add); }; /** * Multiply the p5.Oscillator's output amplitude * by a fixed value (i.e. turn it up!). Calling this method * again will override the initial mult() with a new value. * * @method mult * @param {Number} number Constant number to multiply * @return {p5.Oscillator} Oscillator Returns this oscillator * with multiplied output */ p5.Oscillator.prototype.mult = function (num) { var mult = new Mult(num); var thisChain = this.mathOps.length - 1; var nextChain = this.output; return sigChain(this, mult, thisChain, nextChain, Mult); }; /** * Scale this oscillator's amplitude values to a given * range, and return the oscillator. Calling this method * again will override the initial scale() with new values. * * @method scale * @param {Number} inMin input range minumum * @param {Number} inMax input range maximum * @param {Number} outMin input range minumum * @param {Number} outMax input range maximum * @return {p5.Oscillator} Oscillator Returns this oscillator * with scaled output */ p5.Oscillator.prototype.scale = function (inMin, inMax, outMin, outMax) { var mapOutMin, mapOutMax; if (arguments.length === 4) { mapOutMin = p5.prototype.map(outMin, inMin, inMax, 0, 1) - 0.5; mapOutMax = p5.prototype.map(outMax, inMin, inMax, 0, 1) - 0.5; } else { mapOutMin = arguments[0]; mapOutMax = arguments[1]; } var scale = new Scale(mapOutMin, mapOutMax); var thisChain = this.mathOps.length - 1; var nextChain = this.output; return sigChain(this, scale, thisChain, nextChain, Scale); }; // ============================== // // SinOsc, TriOsc, SqrOsc, SawOsc // // ============================== // /** * Constructor: <code>new p5.SinOsc()</code>. * This creates a Sine Wave Oscillator and is * equivalent to <code> new p5.Oscillator('sine') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('sine')</code>. * See p5.Oscillator for methods. * * @method p5.SinOsc * @param {[Number]} freq Set the frequency */ p5.SinOsc = function (freq) { p5.Oscillator.call(this, freq, 'sine'); }; p5.SinOsc.prototype = Object.create(p5.Oscillator.prototype); /** * Constructor: <code>new p5.TriOsc()</code>. * This creates a Triangle Wave Oscillator and is * equivalent to <code>new p5.Oscillator('triangle') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('triangle')</code>. * See p5.Oscillator for methods. * * @method p5.TriOsc * @param {[Number]} freq Set the frequency */ p5.TriOsc = function (freq) { p5.Oscillator.call(this, freq, 'triangle'); }; p5.TriOsc.prototype = Object.create(p5.Oscillator.prototype); /** * Constructor: <code>new p5.SawOsc()</code>. * This creates a SawTooth Wave Oscillator and is * equivalent to <code> new p5.Oscillator('sawtooth') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('sawtooth')</code>. * See p5.Oscillator for methods. * * @method p5.SawOsc * @param {[Number]} freq Set the frequency */ p5.SawOsc = function (freq) { p5.Oscillator.call(this, freq, 'sawtooth'); }; p5.SawOsc.prototype = Object.create(p5.Oscillator.prototype); /** * Constructor: <code>new p5.SqrOsc()</code>. * This creates a Square Wave Oscillator and is * equivalent to <code> new p5.Oscillator('square') * </code> or creating a p5.Oscillator and then calling * its method <code>setType('square')</code>. * See p5.Oscillator for methods. * * @method p5.SqrOsc * @param {[Number]} freq Set the frequency */ p5.SqrOsc = function (freq) { p5.Oscillator.call(this, freq, 'square'); }; p5.SqrOsc.prototype = Object.create(p5.Oscillator.prototype); }(master, Tone_signal_Signal, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_core_Timeline; Tone_core_Timeline = function (Tone) { 'use strict'; Tone.Timeline = function () { var options = this.optionsObject(arguments, ['memory'], Tone.Timeline.defaults); this._timeline = []; this._toRemove = []; this._iterating = false; this.memory = options.memory; }; Tone.extend(Tone.Timeline); Tone.Timeline.defaults = { 'memory': Infinity }; Object.defineProperty(Tone.Timeline.prototype, 'length', { get: function () { return this._timeline.length; } }); Tone.Timeline.prototype.addEvent = function (event) { if (this.isUndef(event.time)) { throw new Error('events must have a time attribute'); } event.time = this.toSeconds(event.time); if (this._timeline.length) { var index = this._search(event.time); this._timeline.splice(index + 1, 0, event); } else { this._timeline.push(event); } if (this.length > this.memory) { var diff = this.length - this.memory; this._timeline.splice(0, diff); } return this; }; Tone.Timeline.prototype.removeEvent = function (event) { if (this._iterating) { this._toRemove.push(event); } else { var index = this._timeline.indexOf(event); if (index !== -1) { this._timeline.splice(index, 1); } } return this; }; Tone.Timeline.prototype.getEvent = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index !== -1) { return this._timeline[index]; } else { return null; } }; Tone.Timeline.prototype.getEventAfter = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index + 1 < this._timeline.length) { return this._timeline[index + 1]; } else { return null; } }; Tone.Timeline.prototype.getEventBefore = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index - 1 >= 0) { return this._timeline[index - 1]; } else { return null; } }; Tone.Timeline.prototype.cancel = function (after) { if (this._timeline.length > 1) { after = this.toSeconds(after); var index = this._search(after); if (index >= 0) { this._timeline = this._timeline.slice(0, index); } else { this._timeline = []; } } else if (this._timeline.length === 1) { if (this._timeline[0].time >= after) { this._timeline = []; } } return this; }; Tone.Timeline.prototype.cancelBefore = function (time) { if (this._timeline.length) { time = this.toSeconds(time); var index = this._search(time); if (index >= 0) { this._timeline = this._timeline.slice(index + 1); } } return this; }; Tone.Timeline.prototype._search = function (time) { var beginning = 0; var len = this._timeline.length; var end = len; while (beginning <= end && beginning < len) { var midPoint = Math.floor(beginning + (end - beginning) / 2); var event = this._timeline[midPoint]; if (event.time === time) { for (var i = midPoint; i < this._timeline.length; i++) { var testEvent = this._timeline[i]; if (testEvent.time === time) { midPoint = i; } } return midPoint; } else if (event.time > time) { end = midPoint - 1; } else if (event.time < time) { beginning = midPoint + 1; } } return beginning - 1; }; Tone.Timeline.prototype._iterate = function (callback, lowerBound, upperBound) { this._iterating = true; lowerBound = this.defaultArg(lowerBound, 0); upperBound = this.defaultArg(upperBound, this._timeline.length - 1); for (var i = lowerBound; i <= upperBound; i++) { callback(this._timeline[i]); } this._iterating = false; if (this._toRemove.length > 0) { for (var j = 0; j < this._toRemove.length; j++) { var index = this._timeline.indexOf(this._toRemove[j]); if (index !== -1) { this._timeline.splice(index, 1); } } this._toRemove = []; } }; Tone.Timeline.prototype.forEach = function (callback) { this._iterate(callback); return this; }; Tone.Timeline.prototype.forEachBefore = function (time, callback) { time = this.toSeconds(time); var upperBound = this._search(time); if (upperBound !== -1) { this._iterate(callback, 0, upperBound); } return this; }; Tone.Timeline.prototype.forEachAfter = function (time, callback) { time = this.toSeconds(time); var lowerBound = this._search(time); this._iterate(callback, lowerBound + 1); return this; }; Tone.Timeline.prototype.forEachFrom = function (time, callback) { time = this.toSeconds(time); var lowerBound = this._search(time); while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) { lowerBound--; } this._iterate(callback, lowerBound + 1); return this; }; Tone.Timeline.prototype.forEachAtTime = function (time, callback) { time = this.toSeconds(time); var upperBound = this._search(time); if (upperBound !== -1) { this._iterate(function (event) { if (event.time === time) { callback(event); } }, 0, upperBound); } return this; }; Tone.Timeline.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._timeline = null; this._toRemove = null; }; return Tone.Timeline; }(Tone_core_Tone); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_signal_TimelineSignal; Tone_signal_TimelineSignal = function (Tone) { 'use strict'; Tone.TimelineSignal = function () { var options = this.optionsObject(arguments, [ 'value', 'units' ], Tone.Signal.defaults); Tone.Signal.apply(this, options); options.param = this._param; Tone.Param.call(this, options); this._events = new Tone.Timeline(10); this._initial = this._fromUnits(this._param.value); }; Tone.extend(Tone.TimelineSignal, Tone.Param); Tone.TimelineSignal.Type = { Linear: 'linear', Exponential: 'exponential', Target: 'target', Set: 'set' }; Object.defineProperty(Tone.TimelineSignal.prototype, 'value', { get: function () { return this._toUnits(this._param.value); }, set: function (value) { var convertedVal = this._fromUnits(value); this._initial = convertedVal; this._param.value = convertedVal; } }); Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) { value = this._fromUnits(value); startTime = this.toSeconds(startTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Set, 'value': value, 'time': startTime }); this._param.setValueAtTime(value, startTime); return this; }; Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); endTime = this.toSeconds(endTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Linear, 'value': value, 'time': endTime }); this._param.linearRampToValueAtTime(value, endTime); return this; }; Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); endTime = this.toSeconds(endTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Exponential, 'value': value, 'time': endTime }); this._param.exponentialRampToValueAtTime(value, endTime); return this; }; Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); timeConstant = Math.max(this._minOutput, timeConstant); startTime = this.toSeconds(startTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Target, 'value': value, 'time': startTime, 'constant': timeConstant }); this._param.setTargetAtTime(value, startTime, timeConstant); return this; }; Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) { this._events.cancel(after); this._param.cancelScheduledValues(this.toSeconds(after)); return this; }; Tone.TimelineSignal.prototype.setRampPoint = function (time) { time = this.toSeconds(time); var val = this.getValueAtTime(time); var after = this._searchAfter(time); if (after) { this.cancelScheduledValues(time); if (after.type === Tone.TimelineSignal.Type.Linear) { this.linearRampToValueAtTime(val, time); } else if (after.type === Tone.TimelineSignal.Type.Exponential) { this.exponentialRampToValueAtTime(val, time); } } this.setValueAtTime(val, time); return this; }; Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) { this.setRampPoint(start); this.linearRampToValueAtTime(value, finish); return this; }; Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) { this.setRampPoint(start); this.exponentialRampToValueAtTime(value, finish); return this; }; Tone.TimelineSignal.prototype._searchBefore = function (time) { return this._events.getEvent(time); }; Tone.TimelineSignal.prototype._searchAfter = function (time) { return this._events.getEventAfter(time); }; Tone.TimelineSignal.prototype.getValueAtTime = function (time) { var after = this._searchAfter(time); var before = this._searchBefore(time); var value = this._initial; if (before === null) { value = this._initial; } else if (before.type === Tone.TimelineSignal.Type.Target) { var previous = this._events.getEventBefore(before.time); var previouVal; if (previous === null) { previouVal = this._initial; } else { previouVal = previous.value; } value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time); } else if (after === null) { value = before.value; } else if (after.type === Tone.TimelineSignal.Type.Linear) { value = this._linearInterpolate(before.time, before.value, after.time, after.value, time); } else if (after.type === Tone.TimelineSignal.Type.Exponential) { value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time); } else { value = before.value; } return value; }; Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect; Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) { return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant); }; Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) { return v0 + (v1 - v0) * ((t - t0) / (t1 - t0)); }; Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) { v0 = Math.max(this._minOutput, v0); return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0)); }; Tone.TimelineSignal.prototype.dispose = function () { Tone.Signal.prototype.dispose.call(this); Tone.Param.prototype.dispose.call(this); this._events.dispose(); this._events = null; }; return Tone.TimelineSignal; }(Tone_core_Tone, Tone_signal_Signal); var env; env = function () { 'use strict'; var p5sound = master; var Add = Tone_signal_Add; var Mult = Tone_signal_Multiply; var Scale = Tone_signal_Scale; var TimelineSignal = Tone_signal_TimelineSignal; var Tone = Tone_core_Tone; Tone.setContext(p5sound.audiocontext); /** * <p>Envelopes are pre-defined amplitude distribution over time. * Typically, envelopes are used to control the output volume * of an object, a series of fades referred to as Attack, Decay, * Sustain and Release ( * <a href="https://upload.wikimedia.org/wikipedia/commons/e/ea/ADSR_parameter.svg">ADSR</a> * ). Envelopes can also control other Web Audio Parameters—for example, a p5.Env can * control an Oscillator's frequency like this: <code>osc.freq(env)</code>.</p> * <p>Use <code><a href="#/p5.Env/setRange">setRange</a></code> to change the attack/release level. * Use <code><a href="#/p5.Env/setADSR">setADSR</a></code> to change attackTime, decayTime, sustainPercent and releaseTime.</p> * <p>Use the <code><a href="#/p5.Env/play">play</a></code> method to play the entire envelope, * the <code><a href="#/p5.Env/ramp">ramp</a></code> method for a pingable trigger, * or <code><a href="#/p5.Env/triggerAttack">triggerAttack</a></code>/ * <code><a href="#/p5.Env/triggerRelease">triggerRelease</a></code> to trigger noteOn/noteOff.</p> * * @class p5.Env * @constructor * @example * <div><code> * var attackLevel = 1.0; * var releaseLevel = 0; * * var attackTime = 0.001 * var decayTime = 0.2; * var susPercent = 0.2; * var releaseTime = 0.5; * * var env, triOsc; * * function setup() { * var cnv = createCanvas(100, 100); * * textAlign(CENTER); * text('click to play', width/2, height/2); * * env = new p5.Env(); * env.setADSR(attackTime, decayTime, susPercent, releaseTime); * env.setRange(attackLevel, releaseLevel); * * triOsc = new p5.Oscillator('triangle'); * triOsc.amp(env); * triOsc.start(); * triOsc.freq(220); * * cnv.mousePressed(playEnv); * } * * function playEnv(){ * env.play(); * } * </code></div> */ p5.Env = function (t1, l1, t2, l2, t3, l3) { var now = p5sound.audiocontext.currentTime; /** * Time until envelope reaches attackLevel * @property attackTime */ this.aTime = t1 || 0.1; /** * Level once attack is complete. * @property attackLevel */ this.aLevel = l1 || 1; /** * Time until envelope reaches decayLevel. * @property decayTime */ this.dTime = t2 || 0.5; /** * Level after decay. The envelope will sustain here until it is released. * @property decayLevel */ this.dLevel = l2 || 0; /** * Duration of the release portion of the envelope. * @property releaseTime */ this.rTime = t3 || 0; /** * Level at the end of the release. * @property releaseLevel */ this.rLevel = l3 || 0; this._rampHighPercentage = 0.98; this._rampLowPercentage = 0.02; this.output = p5sound.audiocontext.createGain(); this.control = new TimelineSignal(); this._init(); // this makes sure the envelope starts at zero this.control.connect(this.output); // connect to the output this.connection = null; // store connection //array of math operation signal chaining this.mathOps = [this.control]; //whether envelope should be linear or exponential curve this.isExponential = false; // oscillator or buffer source to clear on env complete // to save resources if/when it is retriggered this.sourceToClear = null; // set to true if attack is set, then false on release this.wasTriggered = false; // add to the soundArray so we can dispose of the env later p5sound.soundArray.push(this); }; // this init function just smooths the starting value to zero and gives a start point for the timeline // - it was necessary to remove glitches at the beginning. p5.Env.prototype._init = function () { var now = p5sound.audiocontext.currentTime; var t = now; this.control.setTargetAtTime(0.00001, t, 0.001); //also, compute the correct time constants this._setRampAD(this.aTime, this.dTime); }; /** * Reset the envelope with a series of time/value pairs. * * @method set * @param {Number} attackTime Time (in seconds) before level * reaches attackLevel * @param {Number} attackLevel Typically an amplitude between * 0.0 and 1.0 * @param {Number} decayTime Time * @param {Number} decayLevel Amplitude (In a standard ADSR envelope, * decayLevel = sustainLevel) * @param {Number} releaseTime Release Time (in seconds) * @param {Number} releaseLevel Amplitude */ p5.Env.prototype.set = function (t1, l1, t2, l2, t3, l3) { this.aTime = t1; this.aLevel = l1; this.dTime = t2 || 0; this.dLevel = l2 || 0; this.rTime = t4 || 0; this.rLevel = l4 || 0; // set time constants for ramp this._setRampAD(t1, t2); }; /** * Set values like a traditional * <a href="https://en.wikipedia.org/wiki/Synthesizer#/media/File:ADSR_parameter.svg"> * ADSR envelope * </a>. * * @method setADSR * @param {Number} attackTime Time (in seconds before envelope * reaches Attack Level * @param {Number} [decayTime] Time (in seconds) before envelope * reaches Decay/Sustain Level * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, * where 1.0 = attackLevel, 0.0 = releaseLevel. * The susRatio determines the decayLevel and the level at which the * sustain portion of the envelope will sustain. * For example, if attackLevel is 0.4, releaseLevel is 0, * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is * increased to 1.0 (using <code>setRange</code>), * then decayLevel would increase proportionally, to become 0.5. * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) * @example * <div><code> * var attackLevel = 1.0; * var releaseLevel = 0; * * var attackTime = 0.001 * var decayTime = 0.2; * var susPercent = 0.2; * var releaseTime = 0.5; * * var env, triOsc; * * function setup() { * var cnv = createCanvas(100, 100); * * textAlign(CENTER); * text('click to play', width/2, height/2); * * env = new p5.Env(); * env.setADSR(attackTime, decayTime, susPercent, releaseTime); * env.setRange(attackLevel, releaseLevel); * * triOsc = new p5.Oscillator('triangle'); * triOsc.amp(env); * triOsc.start(); * triOsc.freq(220); * * cnv.mousePressed(playEnv); * } * * function playEnv(){ * env.play(); * } * </code></div> */ p5.Env.prototype.setADSR = function (aTime, dTime, sPercent, rTime) { this.aTime = aTime; this.dTime = dTime || 0; // lerp this.sPercent = sPercent || 0; this.dLevel = typeof sPercent !== 'undefined' ? sPercent * (this.aLevel - this.rLevel) + this.rLevel : 0; this.rTime = rTime || 0; // also set time constants for ramp this._setRampAD(aTime, dTime); }; /** * Set max (attackLevel) and min (releaseLevel) of envelope. * * @method setRange * @param {Number} aLevel attack level (defaults to 1) * @param {Number} rLevel release level (defaults to 0) * @example * <div><code> * var attackLevel = 1.0; * var releaseLevel = 0; * * var attackTime = 0.001 * var decayTime = 0.2; * var susPercent = 0.2; * var releaseTime = 0.5; * * var env, triOsc; * * function setup() { * var cnv = createCanvas(100, 100); * * textAlign(CENTER); * text('click to play', width/2, height/2); * * env = new p5.Env(); * env.setADSR(attackTime, decayTime, susPercent, releaseTime); * env.setRange(attackLevel, releaseLevel); * * triOsc = new p5.Oscillator('triangle'); * triOsc.amp(env); * triOsc.start(); * triOsc.freq(220); * * cnv.mousePressed(playEnv); * } * * function playEnv(){ * env.play(); * } * </code></div> */ p5.Env.prototype.setRange = function (aLevel, rLevel) { this.aLevel = aLevel || 1; this.rLevel = rLevel || 0; }; // private (undocumented) method called when ADSR is set to set time constants for ramp // // Set the <a href="https://en.wikipedia.org/wiki/RC_time_constant"> // time constants</a> for simple exponential ramps. // The larger the time constant value, the slower the // transition will be. // // method _setRampAD // param {Number} attackTimeConstant attack time constant // param {Number} decayTimeConstant decay time constant // p5.Env.prototype._setRampAD = function (t1, t2) { this._rampAttackTime = this.checkExpInput(t1); this._rampDecayTime = this.checkExpInput(t2); var TCDenominator = 1; /// Aatish Bhatia's calculation for time constant for rise(to adjust 1/1-e calculation to any percentage) TCDenominator = Math.log(1 / this.checkExpInput(1 - this._rampHighPercentage)); this._rampAttackTC = t1 / this.checkExpInput(TCDenominator); TCDenominator = Math.log(1 / this._rampLowPercentage); this._rampDecayTC = t2 / this.checkExpInput(TCDenominator); }; // private method p5.Env.prototype.setRampPercentages = function (p1, p2) { //set the percentages that the simple exponential ramps go to this._rampHighPercentage = this.checkExpInput(p1); this._rampLowPercentage = this.checkExpInput(p2); var TCDenominator = 1; //now re-compute the time constants based on those percentages /// Aatish Bhatia's calculation for time constant for rise(to adjust 1/1-e calculation to any percentage) TCDenominator = Math.log(1 / this.checkExpInput(1 - this._rampHighPercentage)); this._rampAttackTC = this._rampAttackTime / this.checkExpInput(TCDenominator); TCDenominator = Math.log(1 / this._rampLowPercentage); this._rampDecayTC = this._rampDecayTime / this.checkExpInput(TCDenominator); }; /** * Assign a parameter to be controlled by this envelope. * If a p5.Sound object is given, then the p5.Env will control its * output gain. If multiple inputs are provided, the env will * control all of them. * * @method setInput * @param {Object} unit A p5.sound object or * Web Audio Param. */ p5.Env.prototype.setInput = function (unit) { for (var i = 0; i < arguments.length; i++) { this.connect(arguments[i]); } }; /** * Set whether the envelope ramp is linear (default) or exponential. * Exponential ramps can be useful because we perceive amplitude * and frequency logarithmically. * * @method setExp * @param {Boolean} isExp true is exponential, false is linear */ p5.Env.prototype.setExp = function (isExp) { this.isExponential = isExp; }; //helper method to protect against zero values being sent to exponential functions p5.Env.prototype.checkExpInput = function (value) { if (value <= 0) { value = 0.0001; } return value; }; /** * Play tells the envelope to start acting on a given input. * If the input is a p5.sound object (i.e. AudioIn, Oscillator, * SoundFile), then Env will control its output volume. * Envelopes can also be used to control any <a href=" * http://docs.webplatform.org/wiki/apis/webaudio/AudioParam"> * Web Audio Audio Param.</a> * * @method play * @param {Object} unit A p5.sound object or * Web Audio Param. * @param {Number} [startTime] time from now (in seconds) at which to play * @param {Number} [sustainTime] time to sustain before releasing the envelope * @example * <div><code> * var attackLevel = 1.0; * var releaseLevel = 0; * * var attackTime = 0.001 * var decayTime = 0.2; * var susPercent = 0.2; * var releaseTime = 0.5; * * var env, triOsc; * * function setup() { * var cnv = createCanvas(100, 100); * * textAlign(CENTER); * text('click to play', width/2, height/2); * * env = new p5.Env(); * env.setADSR(attackTime, decayTime, susPercent, releaseTime); * env.setRange(attackLevel, releaseLevel); * * triOsc = new p5.Oscillator('triangle'); * triOsc.amp(env); * triOsc.start(); * triOsc.freq(220); * * cnv.mousePressed(playEnv); * } * * function playEnv(){ * // trigger env on triOsc, 0 seconds from now * // After decay, sustain for 0.2 seconds before release * env.play(triOsc, 0, 0.2); * } * </code></div> */ p5.Env.prototype.play = function (unit, secondsFromNow, susTime) { var now = p5sound.audiocontext.currentTime; var tFromNow = secondsFromNow || 0; var susTime = susTime || 0; if (unit) { if (this.connection !== unit) { this.connect(unit); } } this.triggerAttack(unit, tFromNow); this.triggerRelease(unit, tFromNow + this.aTime + this.dTime + susTime); }; /** * Trigger the Attack, and Decay portion of the Envelope. * Similar to holding down a key on a piano, but it will * hold the sustain level until you let go. Input can be * any p5.sound object, or a <a href=" * http://docs.webplatform.org/wiki/apis/webaudio/AudioParam"> * Web Audio Param</a>. * * @method triggerAttack * @param {Object} unit p5.sound Object or Web Audio Param * @param {Number} secondsFromNow time from now (in seconds) * @example * <div><code> * * var attackLevel = 1.0; * var releaseLevel = 0; * * var attackTime = 0.001 * var decayTime = 0.3; * var susPercent = 0.4; * var releaseTime = 0.5; * * var env, triOsc; * * function setup() { * var cnv = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('click to play', width/2, height/2); * * env = new p5.Env(); * env.setADSR(attackTime, decayTime, susPercent, releaseTime); * env.setRange(attackLevel, releaseLevel); * * triOsc = new p5.Oscillator('triangle'); * triOsc.amp(env); * triOsc.start(); * triOsc.freq(220); * * cnv.mousePressed(envAttack); * } * * function envAttack(){ * console.log('trigger attack'); * env.triggerAttack(); * * background(0,255,0); * text('attack!', width/2, height/2); * } * * function mouseReleased() { * env.triggerRelease(); * * background(200); * text('click to play', width/2, height/2); * } * </code></div> */ p5.Env.prototype.triggerAttack = function (unit, secondsFromNow) { var now = p5sound.audiocontext.currentTime; var tFromNow = secondsFromNow || 0; var t = now + tFromNow; this.lastAttack = t; this.wasTriggered = true; if (unit) { if (this.connection !== unit) { this.connect(unit); } } // get and set value (with linear ramp) to anchor automation var valToSet = this.control.getValueAtTime(t); this.control.cancelScheduledValues(t); // not sure if this is necessary if (this.isExponential == true) { this.control.exponentialRampToValueAtTime(this.checkExpInput(valToSet), t); } else { this.control.linearRampToValueAtTime(valToSet, t); } // after each ramp completes, cancel scheduled values // (so they can be overridden in case env has been re-triggered) // then, set current value (with linearRamp to avoid click) // then, schedule the next automation... // attack t += this.aTime; if (this.isExponential == true) { this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel), t); valToSet = this.checkExpInput(this.control.getValueAtTime(t)); this.control.cancelScheduledValues(t); this.control.exponentialRampToValueAtTime(valToSet, t); } else { this.control.linearRampToValueAtTime(this.aLevel, t); valToSet = this.control.getValueAtTime(t); this.control.cancelScheduledValues(t); this.control.linearRampToValueAtTime(valToSet, t); } // decay to decay level (if using ADSR, then decay level == sustain level) t += this.dTime; if (this.isExponential == true) { this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel), t); valToSet = this.checkExpInput(this.control.getValueAtTime(t)); this.control.cancelScheduledValues(t); this.control.exponentialRampToValueAtTime(valToSet, t); } else { this.control.linearRampToValueAtTime(this.dLevel, t); valToSet = this.control.getValueAtTime(t); this.control.cancelScheduledValues(t); this.control.linearRampToValueAtTime(valToSet, t); } }; /** * Trigger the Release of the Envelope. This is similar to releasing * the key on a piano and letting the sound fade according to the * release level and release time. * * @method triggerRelease * @param {Object} unit p5.sound Object or Web Audio Param * @param {Number} secondsFromNow time to trigger the release * @example * <div><code> * * var attackLevel = 1.0; * var releaseLevel = 0; * * var attackTime = 0.001 * var decayTime = 0.3; * var susPercent = 0.4; * var releaseTime = 0.5; * * var env, triOsc; * * function setup() { * var cnv = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('click to play', width/2, height/2); * * env = new p5.Env(); * env.setADSR(attackTime, decayTime, susPercent, releaseTime); * env.setRange(attackLevel, releaseLevel); * * triOsc = new p5.Oscillator('triangle'); * triOsc.amp(env); * triOsc.start(); * triOsc.freq(220); * * cnv.mousePressed(envAttack); * } * * function envAttack(){ * console.log('trigger attack'); * env.triggerAttack(); * * background(0,255,0); * text('attack!', width/2, height/2); * } * * function mouseReleased() { * env.triggerRelease(); * * background(200); * text('click to play', width/2, height/2); * } * </code></div> */ p5.Env.prototype.triggerRelease = function (unit, secondsFromNow) { // only trigger a release if an attack was triggered if (!this.wasTriggered) { // this currently causes a bit of trouble: // if a later release has been scheduled (via the play function) // a new earlier release won't interrupt it, because // this.wasTriggered has already been set to false. // If we want new earlier releases to override, then we need to // keep track of the last release time, and if the new release time is // earlier, then use it. return; } var now = p5sound.audiocontext.currentTime; var tFromNow = secondsFromNow || 0; var t = now + tFromNow; if (unit) { if (this.connection !== unit) { this.connect(unit); } } // get and set value (with linear or exponential ramp) to anchor automation var valToSet = this.control.getValueAtTime(t); this.control.cancelScheduledValues(t); // not sure if this is necessary if (this.isExponential == true) { this.control.exponentialRampToValueAtTime(this.checkExpInput(valToSet), t); } else { this.control.linearRampToValueAtTime(valToSet, t); } // release t += this.rTime; if (this.isExponential == true) { this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel), t); valToSet = this.checkExpInput(this.control.getValueAtTime(t)); this.control.cancelScheduledValues(t); this.control.exponentialRampToValueAtTime(valToSet, t); } else { this.control.linearRampToValueAtTime(this.rLevel, t); valToSet = this.control.getValueAtTime(t); this.control.cancelScheduledValues(t); this.control.linearRampToValueAtTime(valToSet, t); } this.wasTriggered = false; }; /** * Exponentially ramp to a value using the first two * values from <code><a href="#/p5.Env/setADSR">setADSR(attackTime, decayTime)</a></code> * as <a href="https://en.wikipedia.org/wiki/RC_time_constant"> * time constants</a> for simple exponential ramps. * If the value is higher than current value, it uses attackTime, * while a decrease uses decayTime. * * @method ramp * @param {Object} unit p5.sound Object or Web Audio Param * @param {Number} secondsFromNow When to trigger the ramp * @param {Number} v Target value * @param {Number} [v2] Second target value (optional) * @example * <div><code> * var env, osc, amp, cnv; * * var attackTime = 0.001; * var decayTime = 0.2; * var attackLevel = 1; * var decayLevel = 0; * * function setup() { * cnv = createCanvas(100, 100); * fill(0,255,0); * noStroke(); * * env = new p5.Env(); * env.setADSR(attackTime, decayTime); * * osc = new p5.Oscillator(); * osc.amp(env); * osc.start(); * * amp = new p5.Amplitude(); * * cnv.mousePressed(triggerRamp); * } * * function triggerRamp() { * env.ramp(osc, 0, attackLevel, decayLevel); * } * * function draw() { * background(20,20,20); * text('click me', 10, 20); * var h = map(amp.getLevel(), 0, 0.4, 0, height);; * * rect(0, height, width, -h); * } * </code></div> */ p5.Env.prototype.ramp = function (unit, secondsFromNow, v1, v2) { var now = p5sound.audiocontext.currentTime; var tFromNow = secondsFromNow || 0; var t = now + tFromNow; var destination1 = this.checkExpInput(v1); var destination2 = typeof v2 !== 'undefined' ? this.checkExpInput(v2) : undefined; // connect env to unit if not already connected if (unit) { if (this.connection !== unit) { this.connect(unit); } } //get current value var currentVal = this.checkExpInput(this.control.getValueAtTime(t)); this.control.cancelScheduledValues(t); //if it's going up if (destination1 > currentVal) { this.control.setTargetAtTime(destination1, t, this._rampAttackTC); t += this._rampAttackTime; } else if (destination1 < currentVal) { this.control.setTargetAtTime(destination1, t, this._rampDecayTC); t += this._rampDecayTime; } // Now the second part of envelope begins if (destination2 === undefined) return; //if it's going up if (destination2 > destination1) { this.control.setTargetAtTime(destination2, t, this._rampAttackTC); } else if (destination2 < destination1) { this.control.setTargetAtTime(destination2, t, this._rampDecayTC); } }; p5.Env.prototype.connect = function (unit) { this.connection = unit; // assume we're talking about output gain // unless given a different audio param if (unit instanceof p5.Oscillator || unit instanceof p5.SoundFile || unit instanceof p5.AudioIn || unit instanceof p5.Reverb || unit instanceof p5.Noise || unit instanceof p5.Filter || unit instanceof p5.Delay) { unit = unit.output.gain; } if (unit instanceof AudioParam) { //set the initial value unit.setValueAtTime(0, p5sound.audiocontext.currentTime); } if (unit instanceof p5.Signal) { unit.setValue(0); } this.output.connect(unit); }; p5.Env.prototype.disconnect = function (unit) { this.output.disconnect(); }; // Signal Math /** * Add a value to the p5.Oscillator's output amplitude, * and return the oscillator. Calling this method * again will override the initial add() with new values. * * @method add * @param {Number} number Constant number to add * @return {p5.Env} Envelope Returns this envelope * with scaled output */ p5.Env.prototype.add = function (num) { var add = new Add(num); var thisChain = this.mathOps.length; var nextChain = this.output; return p5.prototype._mathChain(this, add, thisChain, nextChain, Add); }; /** * Multiply the p5.Env's output amplitude * by a fixed value. Calling this method * again will override the initial mult() with new values. * * @method mult * @param {Number} number Constant number to multiply * @return {p5.Env} Envelope Returns this envelope * with scaled output */ p5.Env.prototype.mult = function (num) { var mult = new Mult(num); var thisChain = this.mathOps.length; var nextChain = this.output; return p5.prototype._mathChain(this, mult, thisChain, nextChain, Mult); }; /** * Scale this envelope's amplitude values to a given * range, and return the envelope. Calling this method * again will override the initial scale() with new values. * * @method scale * @param {Number} inMin input range minumum * @param {Number} inMax input range maximum * @param {Number} outMin input range minumum * @param {Number} outMax input range maximum * @return {p5.Env} Envelope Returns this envelope * with scaled output */ p5.Env.prototype.scale = function (inMin, inMax, outMin, outMax) { var scale = new Scale(inMin, inMax, outMin, outMax); var thisChain = this.mathOps.length; var nextChain = this.output; return p5.prototype._mathChain(this, scale, thisChain, nextChain, Scale); }; // get rid of the oscillator p5.Env.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); var now = p5sound.audiocontext.currentTime; this.disconnect(); try { this.control.dispose(); this.control = null; } catch (e) { } for (var i = 1; i < this.mathOps.length; i++) { mathOps[i].dispose(); } }; }(master, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale, Tone_signal_TimelineSignal, Tone_core_Tone); var pulse; pulse = function () { 'use strict'; var p5sound = master; /** * Creates a Pulse object, an oscillator that implements * Pulse Width Modulation. * The pulse is created with two oscillators. * Accepts a parameter for frequency, and to set the * width between the pulses. See <a href=" * http://p5js.org/reference/#/p5.Oscillator"> * <code>p5.Oscillator</code> for a full list of methods. * * @class p5.Pulse * @constructor * @param {Number} [freq] Frequency in oscillations per second (Hz) * @param {Number} [w] Width between the pulses (0 to 1.0, * defaults to 0) * @example * <div><code> * var pulse; * function setup() { * background(0); * * // Create and start the pulse wave oscillator * pulse = new p5.Pulse(); * pulse.amp(0.5); * pulse.freq(220); * pulse.start(); * } * * function draw() { * var w = map(mouseX, 0, width, 0, 1); * w = constrain(w, 0, 1); * pulse.width(w) * } * </code></div> */ p5.Pulse = function (freq, w) { p5.Oscillator.call(this, freq, 'sawtooth'); // width of PWM, should be betw 0 to 1.0 this.w = w || 0; // create a second oscillator with inverse frequency this.osc2 = new p5.SawOsc(freq); // create a delay node this.dNode = p5sound.audiocontext.createDelay(); // dc offset this.dcOffset = createDCOffset(); this.dcGain = p5sound.audiocontext.createGain(); this.dcOffset.connect(this.dcGain); this.dcGain.connect(this.output); // set delay time based on PWM width this.f = freq || 440; var mW = this.w / this.oscillator.frequency.value; this.dNode.delayTime.value = mW; this.dcGain.gain.value = 1.7 * (0.5 - this.w); // disconnect osc2 and connect it to delay, which is connected to output this.osc2.disconnect(); this.osc2.panner.disconnect(); this.osc2.amp(-1); // inverted amplitude this.osc2.output.connect(this.dNode); this.dNode.connect(this.output); this.output.gain.value = 1; this.output.connect(this.panner); }; p5.Pulse.prototype = Object.create(p5.Oscillator.prototype); /** * Set the width of a Pulse object (an oscillator that implements * Pulse Width Modulation). * * @method width * @param {Number} [width] Width between the pulses (0 to 1.0, * defaults to 0) */ p5.Pulse.prototype.width = function (w) { if (typeof w === 'number') { if (w <= 1 && w >= 0) { this.w = w; // set delay time based on PWM width // var mW = map(this.w, 0, 1.0, 0, 1/this.f); var mW = this.w / this.oscillator.frequency.value; this.dNode.delayTime.value = mW; } this.dcGain.gain.value = 1.7 * (0.5 - this.w); } else { w.connect(this.dNode.delayTime); var sig = new p5.SignalAdd(-0.5); sig.setInput(w); sig = sig.mult(-1); sig = sig.mult(1.7); sig.connect(this.dcGain.gain); } }; p5.Pulse.prototype.start = function (f, time) { var now = p5sound.audiocontext.currentTime; var t = time || 0; if (!this.started) { var freq = f || this.f; var type = this.oscillator.type; this.oscillator = p5sound.audiocontext.createOscillator(); this.oscillator.frequency.setValueAtTime(freq, now); this.oscillator.type = type; this.oscillator.connect(this.output); this.oscillator.start(t + now); // set up osc2 this.osc2.oscillator = p5sound.audiocontext.createOscillator(); this.osc2.oscillator.frequency.setValueAtTime(freq, t + now); this.osc2.oscillator.type = type; this.osc2.oscillator.connect(this.osc2.output); this.osc2.start(t + now); this.freqNode = [ this.oscillator.frequency, this.osc2.oscillator.frequency ]; // start dcOffset, too this.dcOffset = createDCOffset(); this.dcOffset.connect(this.dcGain); this.dcOffset.start(t + now); // if LFO connections depend on these oscillators if (this.mods !== undefined && this.mods.frequency !== undefined) { this.mods.frequency.connect(this.freqNode[0]); this.mods.frequency.connect(this.freqNode[1]); } this.started = true; this.osc2.started = true; } }; p5.Pulse.prototype.stop = function (time) { if (this.started) { var t = time || 0; var now = p5sound.audiocontext.currentTime; this.oscillator.stop(t + now); this.osc2.oscillator.stop(t + now); this.dcOffset.stop(t + now); this.started = false; this.osc2.started = false; } }; p5.Pulse.prototype.freq = function (val, rampTime, tFromNow) { if (typeof val === 'number') { this.f = val; var now = p5sound.audiocontext.currentTime; var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var currentFreq = this.oscillator.frequency.value; this.oscillator.frequency.cancelScheduledValues(now); this.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); this.osc2.oscillator.frequency.cancelScheduledValues(now); this.osc2.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); this.osc2.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); if (this.freqMod) { this.freqMod.output.disconnect(); this.freqMod = null; } } else if (val.output) { val.output.disconnect(); val.output.connect(this.oscillator.frequency); val.output.connect(this.osc2.oscillator.frequency); this.freqMod = val; } }; // inspiration: http://webaudiodemos.appspot.com/oscilloscope/ function createDCOffset() { var ac = p5sound.audiocontext; var buffer = ac.createBuffer(1, 2048, ac.sampleRate); var data = buffer.getChannelData(0); for (var i = 0; i < 2048; i++) data[i] = 1; var bufferSource = ac.createBufferSource(); bufferSource.buffer = buffer; bufferSource.loop = true; return bufferSource; } }(master, oscillator); var noise; noise = function () { 'use strict'; var p5sound = master; /** * Noise is a type of oscillator that generates a buffer with random values. * * @class p5.Noise * @constructor * @param {String} type Type of noise can be 'white' (default), * 'brown' or 'pink'. * @return {Object} Noise Object */ p5.Noise = function (type) { p5.Oscillator.call(this); delete this.f; delete this.freq; delete this.oscillator; this.buffer = _whiteNoise; }; p5.Noise.prototype = Object.create(p5.Oscillator.prototype); // generate noise buffers var _whiteNoise = function () { var bufferSize = 2 * p5sound.audiocontext.sampleRate; var whiteBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); var noiseData = whiteBuffer.getChannelData(0); for (var i = 0; i < bufferSize; i++) { noiseData[i] = Math.random() * 2 - 1; } whiteBuffer.type = 'white'; return whiteBuffer; }(); var _pinkNoise = function () { var bufferSize = 2 * p5sound.audiocontext.sampleRate; var pinkBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); var noiseData = pinkBuffer.getChannelData(0); var b0, b1, b2, b3, b4, b5, b6; b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0; for (var i = 0; i < bufferSize; i++) { var white = Math.random() * 2 - 1; b0 = 0.99886 * b0 + white * 0.0555179; b1 = 0.99332 * b1 + white * 0.0750759; b2 = 0.969 * b2 + white * 0.153852; b3 = 0.8665 * b3 + white * 0.3104856; b4 = 0.55 * b4 + white * 0.5329522; b5 = -0.7616 * b5 - white * 0.016898; noiseData[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; noiseData[i] *= 0.11; // (roughly) compensate for gain b6 = white * 0.115926; } pinkBuffer.type = 'pink'; return pinkBuffer; }(); var _brownNoise = function () { var bufferSize = 2 * p5sound.audiocontext.sampleRate; var brownBuffer = p5sound.audiocontext.createBuffer(1, bufferSize, p5sound.audiocontext.sampleRate); var noiseData = brownBuffer.getChannelData(0); var lastOut = 0; for (var i = 0; i < bufferSize; i++) { var white = Math.random() * 2 - 1; noiseData[i] = (lastOut + 0.02 * white) / 1.02; lastOut = noiseData[i]; noiseData[i] *= 3.5; } brownBuffer.type = 'brown'; return brownBuffer; }(); /** * Set type of noise to 'white', 'pink' or 'brown'. * White is the default. * * @method setType * @param {String} [type] 'white', 'pink' or 'brown' */ p5.Noise.prototype.setType = function (type) { switch (type) { case 'white': this.buffer = _whiteNoise; break; case 'pink': this.buffer = _pinkNoise; break; case 'brown': this.buffer = _brownNoise; break; default: this.buffer = _whiteNoise; } if (this.started) { var now = p5sound.audiocontext.currentTime; this.stop(now); this.start(now + 0.01); } }; p5.Noise.prototype.getType = function () { return this.buffer.type; }; /** * Start the noise * * @method start */ p5.Noise.prototype.start = function () { if (this.started) { this.stop(); } this.noise = p5sound.audiocontext.createBufferSource(); this.noise.buffer = this.buffer; this.noise.loop = true; this.noise.connect(this.output); var now = p5sound.audiocontext.currentTime; this.noise.start(now); this.started = true; }; /** * Stop the noise. * * @method stop */ p5.Noise.prototype.stop = function () { var now = p5sound.audiocontext.currentTime; if (this.noise) { this.noise.stop(now); this.started = false; } }; /** * Pan the noise. * * @method pan * @param {Number} panning Number between -1 (left) * and 1 (right) * @param {Number} timeFromNow schedule this event to happen * seconds from now */ /** * Set the amplitude of the noise between 0 and 1.0. Or, * modulate amplitude with an audio signal such as an oscillator. * * @param {Number|Object} volume amplitude between 0 and 1.0 * or modulating signal/oscillator * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ /** * Disconnect all output. * * @method disconnect */ p5.Noise.prototype.dispose = function () { var now = p5sound.audiocontext.currentTime; // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); if (this.noise) { this.noise.disconnect(); this.stop(now); } if (this.output) { this.output.disconnect(); } if (this.panner) { this.panner.disconnect(); } this.output = null; this.panner = null; this.buffer = null; this.noise = null; }; }(master); var audioin; audioin = function () { 'use strict'; var p5sound = master; var CustomError = errorHandler; /** * <p>Get audio from an input, i.e. your computer's microphone.</p> * * <p>Turn the mic on/off with the start() and stop() methods. When the mic * is on, its volume can be measured with getLevel or by connecting an * FFT object.</p> * * <p>If you want to hear the AudioIn, use the .connect() method. * AudioIn does not connect to p5.sound output by default to prevent * feedback.</p> * * <p><em>Note: This uses the <a href="http://caniuse.com/stream">getUserMedia/ * Stream</a> API, which is not supported by certain browsers.</em></p> * * @class p5.AudioIn * @constructor * @return {Object} AudioIn * @example * <div><code> * var mic; * function setup(){ * mic = new p5.AudioIn() * mic.start(); * } * function draw(){ * background(0); * micLevel = mic.getLevel(); * ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10); * } * </code></div> */ p5.AudioIn = function () { // set up audio input this.input = p5sound.audiocontext.createGain(); this.output = p5sound.audiocontext.createGain(); this.stream = null; this.mediaStream = null; this.currentSource = 0; /** * Client must allow browser to access their microphone / audioin source. * Default: false. Will become true when the client enables acces. * * @property {Boolean} enabled */ this.enabled = false; // create an amplitude, connect to it by default but not to master out this.amplitude = new p5.Amplitude(); this.output.connect(this.amplitude.input); // Some browsers let developer determine their input sources if (typeof window.MediaStreamTrack === 'undefined') { window.alert('This browser does not support MediaStreamTrack'); } else if (typeof window.MediaStreamTrack.getSources === 'function') { // Chrome supports getSources to list inputs. Dev picks default window.MediaStreamTrack.getSources(this._gotSources); } else { } // add to soundArray so we can dispose on close p5sound.soundArray.push(this); }; /** * Start processing audio input. This enables the use of other * AudioIn methods like getLevel(). Note that by default, AudioIn * is not connected to p5.sound's output. So you won't hear * anything unless you use the connect() method.<br/> * * @method start * @param {Function} successCallback Name of a function to call on * success. * @param {Function} errorCallback Name of a function to call if * there was an error. For example, * some browsers do not support * getUserMedia. */ p5.AudioIn.prototype.start = function (successCallback, errorCallback) { var self = this; // if _gotSources() i.e. developers determine which source to use if (p5sound.inputSources[self.currentSource]) { // set the audio source var audioSource = p5sound.inputSources[self.currentSource].id; var constraints = { audio: { optional: [{ sourceId: audioSource }] } }; window.navigator.getUserMedia(constraints, this._onStream = function (stream) { self.stream = stream; self.enabled = true; // Wrap a MediaStreamSourceNode around the live input self.mediaStream = p5sound.audiocontext.createMediaStreamSource(stream); self.mediaStream.connect(self.output); if (successCallback) successCallback(); // only send to the Amplitude reader, so we can see it but not hear it. self.amplitude.setInput(self.output); }, this._onStreamError = function (e) { if (errorCallback) errorCallback(e); else console.error(e); }); } else { // if Firefox where users select their source via browser // if (typeof MediaStreamTrack.getSources === 'undefined') { // Only get the audio stream. window.navigator.getUserMedia({ 'audio': true }, this._onStream = function (stream) { self.stream = stream; self.enabled = true; // Wrap a MediaStreamSourceNode around the live input self.mediaStream = p5sound.audiocontext.createMediaStreamSource(stream); self.mediaStream.connect(self.output); // only send to the Amplitude reader, so we can see it but not hear it. self.amplitude.setInput(self.output); if (successCallback) successCallback(); }, this._onStreamError = function (e) { if (errorCallback) errorCallback(e); else console.error(e); }); } }; /** * Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().<br/> * * @method stop */ p5.AudioIn.prototype.stop = function () { if (this.stream) { this.stream.stop(); } }; /** * Connect to an audio unit. If no parameter is provided, will * connect to the master output (i.e. your speakers).<br/> * * @method connect * @param {Object} [unit] An object that accepts audio input, * such as an FFT */ p5.AudioIn.prototype.connect = function (unit) { if (unit) { if (unit.hasOwnProperty('input')) { this.output.connect(unit.input); } else if (unit.hasOwnProperty('analyser')) { this.output.connect(unit.analyser); } else { this.output.connect(unit); } } else { this.output.connect(p5sound.input); } }; /** * Disconnect the AudioIn from all audio units. For example, if * connect() had been called, disconnect() will stop sending * signal to your speakers.<br/> * * @method disconnect */ p5.AudioIn.prototype.disconnect = function (unit) { this.output.disconnect(unit); // stay connected to amplitude even if not outputting to p5 this.output.connect(this.amplitude.input); }; /** * Read the Amplitude (volume level) of an AudioIn. The AudioIn * class contains its own instance of the Amplitude class to help * make it easy to get a microphone's volume level. Accepts an * optional smoothing value (0.0 < 1.0). <em>NOTE: AudioIn must * .start() before using .getLevel().</em><br/> * * @method getLevel * @param {Number} [smoothing] Smoothing is 0.0 by default. * Smooths values based on previous values. * @return {Number} Volume level (between 0.0 and 1.0) */ p5.AudioIn.prototype.getLevel = function (smoothing) { if (smoothing) { this.amplitude.smoothing = smoothing; } return this.amplitude.getLevel(); }; /** * Add input sources to the list of available sources. * * @private */ p5.AudioIn.prototype._gotSources = function (sourceInfos) { for (var i = 0; i < sourceInfos.length; i++) { var sourceInfo = sourceInfos[i]; if (sourceInfo.kind === 'audio') { // add the inputs to inputSources //p5sound.inputSources.push(sourceInfo); return sourceInfo; } } }; /** * Set amplitude (volume) of a mic input between 0 and 1.0. <br/> * * @method amp * @param {Number} vol between 0 and 1.0 * @param {Number} [time] ramp time (optional) */ p5.AudioIn.prototype.amp = function (vol, t) { if (t) { var rampTime = t || 0; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(p5sound.audiocontext.currentTime); this.output.gain.setValueAtTime(currentVol, p5sound.audiocontext.currentTime); this.output.gain.linearRampToValueAtTime(vol, rampTime + p5sound.audiocontext.currentTime); } else { this.output.gain.cancelScheduledValues(p5sound.audiocontext.currentTime); this.output.gain.setValueAtTime(vol, p5sound.audiocontext.currentTime); } }; p5.AudioIn.prototype.listSources = function () { console.log('listSources is deprecated - please use AudioIn.getSources'); console.log('input sources: '); if (p5sound.inputSources.length > 0) { return p5sound.inputSources; } else { return 'This browser does not support MediaStreamTrack.getSources()'; } }; /** * Chrome only. Returns a list of available input sources * and allows the user to set the media source. Firefox allows * the user to choose from input sources in the permissions dialogue * instead of enumerating available sources and selecting one. * Note: in order to have descriptive media names your page must be * served over a secure (HTTPS) connection and the page should * request user media before enumerating devices. Otherwise device * ID will be a long device ID number and does not specify device * type. For example see * https://simpl.info/getusermedia/sources/index.html vs. * http://simpl.info/getusermedia/sources/index.html * * @method getSources * @param {Function} callback a callback to handle the sources * when they have been enumerated * @example * <div><code> * var audiograb; * * function setup(){ * //new audioIn * audioGrab = new p5.AudioIn(); * * audioGrab.getSources(function(sourceList) { * //print out the array of available sources * console.log(sourceList); * //set the source to the first item in the inputSources array * audioGrab.setSource(0); * }); * } * </code></div> */ p5.AudioIn.prototype.getSources = function (callback) { if (typeof window.MediaStreamTrack.getSources === 'function') { window.MediaStreamTrack.getSources(function (data) { for (var i = 0, max = data.length; i < max; i++) { var sourceInfo = data[i]; if (sourceInfo.kind === 'audio') { // add the inputs to inputSources p5sound.inputSources.push(sourceInfo); } } callback(p5sound.inputSources); }); } else { console.log('This browser does not support MediaStreamTrack.getSources()'); } }; /** * Set the input source. Accepts a number representing a * position in the array returned by listSources(). * This is only available in browsers that support * MediaStreamTrack.getSources(). Instead, some browsers * give users the option to set their own media source.<br/> * * @method setSource * @param {number} num position of input source in the array */ p5.AudioIn.prototype.setSource = function (num) { // TO DO - set input by string or # (array position) var self = this; if (p5sound.inputSources.length > 0 && num < p5sound.inputSources.length) { // set the current source self.currentSource = num; console.log('set source to ' + p5sound.inputSources[self.currentSource].id); } else { console.log('unable to set input source'); } }; // private method p5.AudioIn.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this.stop(); if (this.output) { this.output.disconnect(); } if (this.amplitude) { this.amplitude.disconnect(); } this.amplitude = null; this.output = null; }; }(master, errorHandler); var filter; filter = function () { 'use strict'; var p5sound = master; /** * A p5.Filter uses a Web Audio Biquad Filter to filter * the frequency response of an input source. Inheriting * classes include:<br/> * * <code>p5.LowPass</code> - allows frequencies below * the cutoff frequency to pass through, and attenuates * frequencies above the cutoff.<br/> * * <code>p5.HighPass</code> - the opposite of a lowpass * filter. <br/> * * <code>p5.BandPass</code> - allows a range of * frequencies to pass through and attenuates the frequencies * below and above this frequency range.<br/> * * The <code>.res()</code> method controls either width of the * bandpass, or resonance of the low/highpass cutoff frequency. * * @class p5.Filter * @constructor * @param {[String]} type 'lowpass' (default), 'highpass', 'bandpass' * @return {Object} p5.Filter * @example * <div><code> * var fft, noise, filter; * * function setup() { * fill(255, 40, 255); * * filter = new p5.BandPass(); * * noise = new p5.Noise(); * // disconnect unfiltered noise, * // and connect to filter * noise.disconnect(); * noise.connect(filter); * noise.start(); * * fft = new p5.FFT(); * } * * function draw() { * background(30); * * // set the BandPass frequency based on mouseX * var freq = map(mouseX, 0, width, 20, 10000); * filter.freq(freq); * // give the filter a narrow band (lower res = wider bandpass) * filter.res(50); * * // draw filtered spectrum * var spectrum = fft.analyze(); * noStroke(); * for (var i = 0; i < spectrum.length; i++) { * var x = map(i, 0, spectrum.length, 0, width); * var h = -height + map(spectrum[i], 0, 255, height, 0); * rect(x, height, width/spectrum.length, h); * } * * isMouseOverCanvas(); * } * * function isMouseOverCanvas() { * var mX = mouseX, mY = mouseY; * if (mX > 0 && mX < width && mY < height && mY > 0) { * noise.amp(0.5, 0.2); * } else { * noise.amp(0, 0.2); * } * } * </code></div> */ p5.Filter = function (type) { this.ac = p5sound.audiocontext; this.input = this.ac.createGain(); this.output = this.ac.createGain(); /** * The p5.Filter is built with a * <a href="http://www.w3.org/TR/webaudio/#BiquadFilterNode"> * Web Audio BiquadFilter Node</a>. * * @property biquadFilter * @type {Object} Web Audio Delay Node */ this.biquad = this.ac.createBiquadFilter(); this.input.connect(this.biquad); this.biquad.connect(this.output); this.connect(); if (type) { this.setType(type); } // add to the soundArray p5sound.soundArray.push(this); }; /** * Filter an audio signal according to a set * of filter parameters. * * @method process * @param {Object} Signal An object that outputs audio * @param {[Number]} freq Frequency in Hz, from 10 to 22050 * @param {[Number]} res Resonance/Width of the filter frequency * from 0.001 to 1000 */ p5.Filter.prototype.process = function (src, freq, res) { src.connect(this.input); this.set(freq, res); }; /** * Set the frequency and the resonance of the filter. * * @method set * @param {Number} freq Frequency in Hz, from 10 to 22050 * @param {Number} res Resonance (Q) from 0.001 to 1000 * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Filter.prototype.set = function (freq, res, time) { if (freq) { this.freq(freq, time); } if (res) { this.res(res, time); } }; /** * Set the filter frequency, in Hz, from 10 to 22050 (the range of * human hearing, although in reality most people hear in a narrower * range). * * @method freq * @param {Number} freq Filter Frequency * @param {Number} [timeFromNow] schedule this event to happen * seconds from now * @return {Number} value Returns the current frequency value */ p5.Filter.prototype.freq = function (freq, time) { var self = this; var t = time || 0; if (freq <= 0) { freq = 1; } if (typeof freq === 'number') { self.biquad.frequency.value = freq; self.biquad.frequency.cancelScheduledValues(this.ac.currentTime + 0.01 + t); self.biquad.frequency.exponentialRampToValueAtTime(freq, this.ac.currentTime + 0.02 + t); } else if (freq) { freq.connect(this.biquad.frequency); } return self.biquad.frequency.value; }; /** * Controls either width of a bandpass frequency, * or the resonance of a low/highpass cutoff frequency. * * @method res * @param {Number} res Resonance/Width of filter freq * from 0.001 to 1000 * @param {Number} [timeFromNow] schedule this event to happen * seconds from now * @return {Number} value Returns the current res value */ p5.Filter.prototype.res = function (res, time) { var self = this; var t = time || 0; if (typeof res == 'number') { self.biquad.Q.value = res; self.biquad.Q.cancelScheduledValues(self.ac.currentTime + 0.01 + t); self.biquad.Q.linearRampToValueAtTime(res, self.ac.currentTime + 0.02 + t); } else if (res) { freq.connect(this.biquad.Q); } return self.biquad.Q.value; }; /** * Set the type of a p5.Filter. Possible types include: * "lowpass" (default), "highpass", "bandpass", * "lowshelf", "highshelf", "peaking", "notch", * "allpass". * * @method setType * @param {String} */ p5.Filter.prototype.setType = function (t) { this.biquad.type = t; }; /** * Set the output level of the filter. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Filter.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow + 0.001); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Filter.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u); }; /** * Disconnect all output. * * @method disconnect */ p5.Filter.prototype.disconnect = function () { this.output.disconnect(); }; p5.Filter.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this.input.disconnect(); this.input = undefined; this.output.disconnect(); this.output = undefined; this.biquad.disconnect(); this.biquad = undefined; }; /** * Constructor: <code>new p5.LowPass()</code> Filter. * This is the same as creating a p5.Filter and then calling * its method <code>setType('lowpass')</code>. * See p5.Filter for methods. * * @method p5.LowPass */ p5.LowPass = function () { p5.Filter.call(this, 'lowpass'); }; p5.LowPass.prototype = Object.create(p5.Filter.prototype); /** * Constructor: <code>new p5.HighPass()</code> Filter. * This is the same as creating a p5.Filter and then calling * its method <code>setType('highpass')</code>. * See p5.Filter for methods. * * @method p5.HighPass */ p5.HighPass = function () { p5.Filter.call(this, 'highpass'); }; p5.HighPass.prototype = Object.create(p5.Filter.prototype); /** * Constructor: <code>new p5.BandPass()</code> Filter. * This is the same as creating a p5.Filter and then calling * its method <code>setType('bandpass')</code>. * See p5.Filter for methods. * * @method p5.BandPass */ p5.BandPass = function () { p5.Filter.call(this, 'bandpass'); }; p5.BandPass.prototype = Object.create(p5.Filter.prototype); }(master); var delay; delay = function () { 'use strict'; var p5sound = master; var Filter = filter; /** * Delay is an echo effect. It processes an existing sound source, * and outputs a delayed version of that sound. The p5.Delay can * produce different effects depending on the delayTime, feedback, * filter, and type. In the example below, a feedback of 0.5 will * produce a looping delay that decreases in volume by * 50% each repeat. A filter will cut out the high frequencies so * that the delay does not sound as piercing as the original source. * * @class p5.Delay * @constructor * @return {Object} Returns a p5.Delay object * @example * <div><code> * var noise, env, delay; * * function setup() { * background(0); * noStroke(); * fill(255); * textAlign(CENTER); * text('click to play', width/2, height/2); * * noise = new p5.Noise('brown'); * noise.amp(0); * noise.start(); * * delay = new p5.Delay(); * * // delay.process() accepts 4 parameters: * // source, delayTime, feedback, filter frequency * // play with these numbers!! * delay.process(noise, .12, .7, 2300); * * // play the noise with an envelope, * // a series of fades ( time / value pairs ) * env = new p5.Env(.01, 0.2, .2, .1); * } * * // mouseClick triggers envelope * function mouseClicked() { * // is mouse over canvas? * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * env.play(noise); * } * } * </code></div> */ p5.Delay = function () { this.ac = p5sound.audiocontext; this.input = this.ac.createGain(); this.output = this.ac.createGain(); this._split = this.ac.createChannelSplitter(2); this._merge = this.ac.createChannelMerger(2); this._leftGain = this.ac.createGain(); this._rightGain = this.ac.createGain(); /** * The p5.Delay is built with two * <a href="http://www.w3.org/TR/webaudio/#DelayNode"> * Web Audio Delay Nodes</a>, one for each stereo channel. * * @property leftDelay * @type {Object} Web Audio Delay Node */ this.leftDelay = this.ac.createDelay(); /** * The p5.Delay is built with two * <a href="http://www.w3.org/TR/webaudio/#DelayNode"> * Web Audio Delay Nodes</a>, one for each stereo channel. * * @property rightDelay * @type {Object} Web Audio Delay Node */ this.rightDelay = this.ac.createDelay(); this._leftFilter = new p5.Filter(); this._rightFilter = new p5.Filter(); this._leftFilter.disconnect(); this._rightFilter.disconnect(); this._leftFilter.biquad.frequency.setValueAtTime(1200, this.ac.currentTime); this._rightFilter.biquad.frequency.setValueAtTime(1200, this.ac.currentTime); this._leftFilter.biquad.Q.setValueAtTime(0.3, this.ac.currentTime); this._rightFilter.biquad.Q.setValueAtTime(0.3, this.ac.currentTime); // graph routing this.input.connect(this._split); this.leftDelay.connect(this._leftGain); this.rightDelay.connect(this._rightGain); this._leftGain.connect(this._leftFilter.input); this._rightGain.connect(this._rightFilter.input); this._merge.connect(this.output); this.output.connect(p5.soundOut.input); this._leftFilter.biquad.gain.setValueAtTime(1, this.ac.currentTime); this._rightFilter.biquad.gain.setValueAtTime(1, this.ac.currentTime); // default routing this.setType(0); this._maxDelay = this.leftDelay.delayTime.maxValue; // add this p5.SoundFile to the soundArray p5sound.soundArray.push(this); }; /** * Add delay to an audio signal according to a set * of delay parameters. * * @method process * @param {Object} Signal An object that outputs audio * @param {Number} [delayTime] Time (in seconds) of the delay/echo. * Some browsers limit delayTime to * 1 second. * @param {Number} [feedback] sends the delay back through itself * in a loop that decreases in volume * each time. * @param {Number} [lowPass] Cutoff frequency. Only frequencies * below the lowPass will be part of the * delay. */ p5.Delay.prototype.process = function (src, _delayTime, _feedback, _filter) { var feedback = _feedback || 0; var delayTime = _delayTime || 0; if (feedback >= 1) { throw new Error('Feedback value will force a positive feedback loop.'); } if (delayTime >= this._maxDelay) { throw new Error('Delay Time exceeds maximum delay time of ' + this._maxDelay + ' second.'); } src.connect(this.input); this.leftDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); this.rightDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); this._leftGain.gain.setValueAtTime(feedback, this.ac.currentTime); this._rightGain.gain.setValueAtTime(feedback, this.ac.currentTime); if (_filter) { this._leftFilter.freq(_filter); this._rightFilter.freq(_filter); } }; /** * Set the delay (echo) time, in seconds. Usually this value will be * a floating point number between 0.0 and 1.0. * * @method delayTime * @param {Number} delayTime Time (in seconds) of the delay */ p5.Delay.prototype.delayTime = function (t) { // if t is an audio node... if (typeof t !== 'number') { t.connect(this.leftDelay.delayTime); t.connect(this.rightDelay.delayTime); } else { this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime); this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime); this.leftDelay.delayTime.linearRampToValueAtTime(t, this.ac.currentTime); this.rightDelay.delayTime.linearRampToValueAtTime(t, this.ac.currentTime); } }; /** * Feedback occurs when Delay sends its signal back through its input * in a loop. The feedback amount determines how much signal to send each * time through the loop. A feedback greater than 1.0 is not desirable because * it will increase the overall output each time through the loop, * creating an infinite feedback loop. * * @method feedback * @param {Number|Object} feedback 0.0 to 1.0, or an object such as an * Oscillator that can be used to * modulate this param */ p5.Delay.prototype.feedback = function (f) { // if f is an audio node... if (typeof f !== 'number') { f.connect(this._leftGain.gain); f.connect(this._rightGain.gain); } else if (f >= 1) { throw new Error('Feedback value will force a positive feedback loop.'); } else { this._leftGain.gain.exponentialRampToValueAtTime(f, this.ac.currentTime); this._rightGain.gain.exponentialRampToValueAtTime(f, this.ac.currentTime); } }; /** * Set a lowpass filter frequency for the delay. A lowpass filter * will cut off any frequencies higher than the filter frequency. * * @method filter * @param {Number|Object} cutoffFreq A lowpass filter will cut off any * frequencies higher than the filter frequency. * @param {Number|Object} res Resonance of the filter frequency * cutoff, or an object (i.e. a p5.Oscillator) * that can be used to modulate this parameter. * High numbers (i.e. 15) will produce a resonance, * low numbers (i.e. .2) will produce a slope. */ p5.Delay.prototype.filter = function (freq, q) { this._leftFilter.set(freq, q); this._rightFilter.set(freq, q); }; /** * Choose a preset type of delay. 'pingPong' bounces the signal * from the left to the right channel to produce a stereo effect. * Any other parameter will revert to the default delay setting. * * @method setType * @param {String|Number} type 'pingPong' (1) or 'default' (0) */ p5.Delay.prototype.setType = function (t) { if (t === 1) { t = 'pingPong'; } this._split.disconnect(); this._leftFilter.disconnect(); this._rightFilter.disconnect(); this._split.connect(this.leftDelay, 0); this._split.connect(this.rightDelay, 1); switch (t) { case 'pingPong': this._rightFilter.setType(this._leftFilter.biquad.type); this._leftFilter.output.connect(this._merge, 0, 0); this._rightFilter.output.connect(this._merge, 0, 1); this._leftFilter.output.connect(this.rightDelay); this._rightFilter.output.connect(this.leftDelay); break; default: this._leftFilter.output.connect(this._merge, 0, 0); this._leftFilter.output.connect(this._merge, 0, 1); this._leftFilter.output.connect(this.leftDelay); this._leftFilter.output.connect(this.rightDelay); } }; /** * Set the output level of the delay effect. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Delay.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow + 0.001); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Delay.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u); }; /** * Disconnect all output. * * @method disconnect */ p5.Delay.prototype.disconnect = function () { this.output.disconnect(); }; p5.Delay.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this.input.disconnect(); this.output.disconnect(); this._split.disconnect(); this._leftFilter.disconnect(); this._rightFilter.disconnect(); this._merge.disconnect(); this._leftGain.disconnect(); this._rightGain.disconnect(); this.leftDelay.disconnect(); this.rightDelay.disconnect(); this.input = undefined; this.output = undefined; this._split = undefined; this._leftFilter = undefined; this._rightFilter = undefined; this._merge = undefined; this._leftGain = undefined; this._rightGain = undefined; this.leftDelay = undefined; this.rightDelay = undefined; }; }(master, filter); var reverb; reverb = function () { 'use strict'; var p5sound = master; var CustomError = errorHandler; /** * Reverb adds depth to a sound through a large number of decaying * echoes. It creates the perception that sound is occurring in a * physical space. The p5.Reverb has paramters for Time (how long does the * reverb last) and decayRate (how much the sound decays with each echo) * that can be set with the .set() or .process() methods. The p5.Convolver * extends p5.Reverb allowing you to recreate the sound of actual physical * spaces through convolution. * * @class p5.Reverb * @constructor * @example * <div><code> * var soundFile, reverb; * function preload() { * soundFile = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * reverb = new p5.Reverb(); * soundFile.disconnect(); // so we'll only hear reverb... * * // connect soundFile to reverb, process w/ * // 3 second reverbTime, decayRate of 2% * reverb.process(soundFile, 3, 2); * soundFile.play(); * } * </code></div> */ p5.Reverb = function () { this.ac = p5sound.audiocontext; this.convolverNode = this.ac.createConvolver(); this.input = this.ac.createGain(); this.output = this.ac.createGain(); // otherwise, Safari distorts this.input.gain.value = 0.5; this.input.connect(this.convolverNode); this.convolverNode.connect(this.output); // default params this._seconds = 3; this._decay = 2; this._reverse = false; this._buildImpulse(); this.connect(); p5sound.soundArray.push(this); }; /** * Connect a source to the reverb, and assign reverb parameters. * * @method process * @param {Object} src p5.sound / Web Audio object with a sound * output. * @param {Number} [seconds] Duration of the reverb, in seconds. * Min: 0, Max: 10. Defaults to 3. * @param {Number} [decayRate] Percentage of decay with each echo. * Min: 0, Max: 100. Defaults to 2. * @param {Boolean} [reverse] Play the reverb backwards or forwards. */ p5.Reverb.prototype.process = function (src, seconds, decayRate, reverse) { src.connect(this.input); var rebuild = false; if (seconds) { this._seconds = seconds; rebuild = true; } if (decayRate) { this._decay = decayRate; } if (reverse) { this._reverse = reverse; } if (rebuild) { this._buildImpulse(); } }; /** * Set the reverb settings. Similar to .process(), but without * assigning a new input. * * @method set * @param {Number} [seconds] Duration of the reverb, in seconds. * Min: 0, Max: 10. Defaults to 3. * @param {Number} [decayRate] Percentage of decay with each echo. * Min: 0, Max: 100. Defaults to 2. * @param {Boolean} [reverse] Play the reverb backwards or forwards. */ p5.Reverb.prototype.set = function (seconds, decayRate, reverse) { var rebuild = false; if (seconds) { this._seconds = seconds; rebuild = true; } if (decayRate) { this._decay = decayRate; } if (reverse) { this._reverse = reverse; } if (rebuild) { this._buildImpulse(); } }; /** * Set the output level of the delay effect. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Reverb.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow + 0.001); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Reverb.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u.input ? u.input : u); }; /** * Disconnect all output. * * @method disconnect */ p5.Reverb.prototype.disconnect = function () { this.output.disconnect(); }; /** * Inspired by Simple Reverb by Jordan Santell * https://github.com/web-audio-components/simple-reverb/blob/master/index.js * * Utility function for building an impulse response * based on the module parameters. * * @private */ p5.Reverb.prototype._buildImpulse = function () { var rate = this.ac.sampleRate; var length = rate * this._seconds; var decay = this._decay; var impulse = this.ac.createBuffer(2, length, rate); var impulseL = impulse.getChannelData(0); var impulseR = impulse.getChannelData(1); var n, i; for (i = 0; i < length; i++) { n = this.reverse ? length - i : i; impulseL[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); impulseR[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); } this.convolverNode.buffer = impulse; }; p5.Reverb.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); if (this.convolverNode) { this.convolverNode.buffer = null; this.convolverNode = null; } if (typeof this.output !== 'undefined') { this.output.disconnect(); this.output = null; } if (typeof this.panner !== 'undefined') { this.panner.disconnect(); this.panner = null; } }; // ======================================================================= // *** p5.Convolver *** // ======================================================================= /** * <p>p5.Convolver extends p5.Reverb. It can emulate the sound of real * physical spaces through a process called <a href=" * https://en.wikipedia.org/wiki/Convolution_reverb#Real_space_simulation"> * convolution</a>.</p> * * <p>Convolution multiplies any audio input by an "impulse response" * to simulate the dispersion of sound over time. The impulse response is * generated from an audio file that you provide. One way to * generate an impulse response is to pop a balloon in a reverberant space * and record the echo. Convolution can also be used to experiment with * sound.</p> * * <p>Use the method <code>createConvolution(path)</code> to instantiate a * p5.Convolver with a path to your impulse response audio file.</p> * * @class p5.Convolver * @constructor * @param {String} path path to a sound file * @param {Function} [callback] function to call when loading succeeds * @param {Function} [errorCallback] function to call if loading fails. * This function will receive an error or * XMLHttpRequest object with information * about what went wrong. * @example * <div><code> * var cVerb, sound; * function preload() { * // We have both MP3 and OGG versions of all sound assets * soundFormats('ogg', 'mp3'); * * // Try replacing 'bx-spring' with other soundfiles like * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' * cVerb = createConvolver('assets/bx-spring.mp3'); * * // Try replacing 'Damscray_DancingTiger' with * // 'beat', 'doorbell', lucky_dragons_-_power_melody' * sound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * // disconnect from master output... * sound.disconnect(); * * // ...and process with cVerb * // so that we only hear the convolution * cVerb.process(sound); * * sound.play(); * } * </code></div> */ p5.Convolver = function (path, callback, errorCallback) { this.ac = p5sound.audiocontext; /** * Internally, the p5.Convolver uses the a * <a href="http://www.w3.org/TR/webaudio/#ConvolverNode"> * Web Audio Convolver Node</a>. * * @property convolverNode * @type {Object} Web Audio Convolver Node */ this.convolverNode = this.ac.createConvolver(); this.input = this.ac.createGain(); this.output = this.ac.createGain(); // otherwise, Safari distorts this.input.gain.value = 0.5; this.input.connect(this.convolverNode); this.convolverNode.connect(this.output); if (path) { this.impulses = []; this._loadBuffer(path, callback, errorCallback); } else { // parameters this._seconds = 3; this._decay = 2; this._reverse = false; this._buildImpulse(); } this.connect(); p5sound.soundArray.push(this); }; p5.Convolver.prototype = Object.create(p5.Reverb.prototype); p5.prototype.registerPreloadMethod('createConvolver', p5.prototype); /** * Create a p5.Convolver. Accepts a path to a soundfile * that will be used to generate an impulse response. * * @method createConvolver * @param {String} path path to a sound file * @param {Function} [callback] function to call if loading is successful. * The object will be passed in as the argument * to the callback function. * @param {Function} [errorCallback] function to call if loading is not successful. * A custom error will be passed in as the argument * to the callback function. * @return {p5.Convolver} * @example * <div><code> * var cVerb, sound; * function preload() { * // We have both MP3 and OGG versions of all sound assets * soundFormats('ogg', 'mp3'); * * // Try replacing 'bx-spring' with other soundfiles like * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' * cVerb = createConvolver('assets/bx-spring.mp3'); * * // Try replacing 'Damscray_DancingTiger' with * // 'beat', 'doorbell', lucky_dragons_-_power_melody' * sound = loadSound('assets/Damscray_DancingTiger.mp3'); * } * * function setup() { * // disconnect from master output... * sound.disconnect(); * * // ...and process with cVerb * // so that we only hear the convolution * cVerb.process(sound); * * sound.play(); * } * </code></div> */ p5.prototype.createConvolver = function (path, callback, errorCallback) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } var cReverb = new p5.Convolver(path, callback, errorCallback); cReverb.impulses = []; return cReverb; }; /** * Private method to load a buffer as an Impulse Response, * assign it to the convolverNode, and add to the Array of .impulses. * * @param {String} path * @param {Function} callback * @param {Function} errorCallback * @private */ p5.Convolver.prototype._loadBuffer = function (path, callback, errorCallback) { var path = p5.prototype._checkFileFormats(path); var self = this; var errorTrace = new Error().stack; var ac = p5.prototype.getAudioContext(); var request = new XMLHttpRequest(); request.open('GET', path, true); request.responseType = 'arraybuffer'; request.onload = function () { if (request.status == 200) { // on success loading file: ac.decodeAudioData(request.response, function (buff) { var buffer = {}; var chunks = path.split('/'); buffer.name = chunks[chunks.length - 1]; buffer.audioBuffer = buff; self.impulses.push(buffer); self.convolverNode.buffer = buffer.audioBuffer; if (callback) { callback(buffer); } }, // error decoding buffer. "e" is undefined in Chrome 11/22/2015 function (e) { var err = new CustomError('decodeAudioData', errorTrace, self.url); var msg = 'AudioContext error at decodeAudioData for ' + self.url; if (errorCallback) { err.msg = msg; errorCallback(err); } else { console.error(msg + '\n The error stack trace includes: \n' + err.stack); } }); } else { var err = new CustomError('loadConvolver', errorTrace, self.url); var msg = 'Unable to load ' + self.url + '. The request status was: ' + request.status + ' (' + request.statusText + ')'; if (errorCallback) { err.message = msg; errorCallback(err); } else { console.error(msg + '\n The error stack trace includes: \n' + err.stack); } } }; // if there is another error, aside from 404... request.onerror = function (e) { var err = new CustomError('loadConvolver', errorTrace, self.url); var msg = 'There was no response from the server at ' + self.url + '. Check the url and internet connectivity.'; if (errorCallback) { err.message = msg; errorCallback(err); } else { console.error(msg + '\n The error stack trace includes: \n' + err.stack); } }; request.send(); }; p5.Convolver.prototype.set = null; /** * Connect a source to the reverb, and assign reverb parameters. * * @method process * @param {Object} src p5.sound / Web Audio object with a sound * output. * @example * <div><code> * var cVerb, sound; * function preload() { * soundFormats('ogg', 'mp3'); * * cVerb = createConvolver('assets/concrete-tunnel.mp3'); * * sound = loadSound('assets/beat.mp3'); * } * * function setup() { * // disconnect from master output... * sound.disconnect(); * * // ...and process with (i.e. connect to) cVerb * // so that we only hear the convolution * cVerb.process(sound); * * sound.play(); * } * </code></div> */ p5.Convolver.prototype.process = function (src) { src.connect(this.input); }; /** * If you load multiple impulse files using the .addImpulse method, * they will be stored as Objects in this Array. Toggle between them * with the <code>toggleImpulse(id)</code> method. * * @property impulses * @type {Array} Array of Web Audio Buffers */ p5.Convolver.prototype.impulses = []; /** * Load and assign a new Impulse Response to the p5.Convolver. * The impulse is added to the <code>.impulses</code> array. Previous * impulses can be accessed with the <code>.toggleImpulse(id)</code> * method. * * @method addImpulse * @param {String} path path to a sound file * @param {Function} callback function (optional) * @param {Function} errorCallback function (optional) */ p5.Convolver.prototype.addImpulse = function (path, callback, errorCallback) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } this._loadBuffer(path, callback, errorCallback); }; /** * Similar to .addImpulse, except that the <code>.impulses</code> * Array is reset to save memory. A new <code>.impulses</code> * array is created with this impulse as the only item. * * @method resetImpulse * @param {String} path path to a sound file * @param {Function} callback function (optional) * @param {Function} errorCallback function (optional) */ p5.Convolver.prototype.resetImpulse = function (path, callback, errorCallback) { // if loading locally without a server if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); } this.impulses = []; this._loadBuffer(path, callback, errorCallback); }; /** * If you have used <code>.addImpulse()</code> to add multiple impulses * to a p5.Convolver, then you can use this method to toggle between * the items in the <code>.impulses</code> Array. Accepts a parameter * to identify which impulse you wish to use, identified either by its * original filename (String) or by its position in the <code>.impulses * </code> Array (Number).<br/> * You can access the objects in the .impulses Array directly. Each * Object has two attributes: an <code>.audioBuffer</code> (type: * Web Audio <a href=" * http://webaudio.github.io/web-audio-api/#the-audiobuffer-interface"> * AudioBuffer)</a> and a <code>.name</code>, a String that corresponds * with the original filename. * * @method toggleImpulse * @param {String|Number} id Identify the impulse by its original filename * (String), or by its position in the * <code>.impulses</code> Array (Number). */ p5.Convolver.prototype.toggleImpulse = function (id) { if (typeof id === 'number' && id < this.impulses.length) { this.convolverNode.buffer = this.impulses[id].audioBuffer; } if (typeof id === 'string') { for (var i = 0; i < this.impulses.length; i++) { if (this.impulses[i].name === id) { this.convolverNode.buffer = this.impulses[i].audioBuffer; break; } } } }; p5.Convolver.prototype.dispose = function () { // remove all the Impulse Response buffers for (var i in this.impulses) { this.impulses[i] = null; } this.convolverNode.disconnect(); this.concolverNode = null; if (typeof this.output !== 'undefined') { this.output.disconnect(); this.output = null; } if (typeof this.panner !== 'undefined') { this.panner.disconnect(); this.panner = null; } }; }(master, errorHandler, sndcore); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_core_TimelineState; Tone_core_TimelineState = function (Tone) { 'use strict'; Tone.TimelineState = function (initial) { Tone.Timeline.call(this); this._initial = initial; }; Tone.extend(Tone.TimelineState, Tone.Timeline); Tone.TimelineState.prototype.getStateAtTime = function (time) { var event = this.getEvent(time); if (event !== null) { return event.state; } else { return this._initial; } }; Tone.TimelineState.prototype.setStateAtTime = function (state, time) { this.addEvent({ 'state': state, 'time': this.toSeconds(time) }); }; return Tone.TimelineState; }(Tone_core_Tone, Tone_core_Timeline); /** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/ var Tone_core_Clock; Tone_core_Clock = function (Tone) { 'use strict'; Tone.Clock = function () { var options = this.optionsObject(arguments, [ 'callback', 'frequency' ], Tone.Clock.defaults); this.callback = options.callback; this._lookAhead = 'auto'; this._computedLookAhead = 1 / 60; this._threshold = 0.5; this._nextTick = -1; this._lastUpdate = 0; this._loopID = -1; this.frequency = new Tone.TimelineSignal(options.frequency, Tone.Type.Frequency); this.ticks = 0; this._state = new Tone.TimelineState(Tone.State.Stopped); this._boundLoop = this._loop.bind(this); this._readOnly('frequency'); this._loop(); }; Tone.extend(Tone.Clock); Tone.Clock.defaults = { 'callback': Tone.noOp, 'frequency': 1, 'lookAhead': 'auto' }; Object.defineProperty(Tone.Clock.prototype, 'state', { get: function () { return this._state.getStateAtTime(this.now()); } }); Object.defineProperty(Tone.Clock.prototype, 'lookAhead', { get: function () { return this._lookAhead; }, set: function (val) { if (val === 'auto') { this._lookAhead = 'auto'; } else { this._lookAhead = this.toSeconds(val); } } }); Tone.Clock.prototype.start = function (time, offset) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Started) { this._state.addEvent({ 'state': Tone.State.Started, 'time': time, 'offset': offset }); } return this; }; Tone.Clock.prototype.stop = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Stopped) { this._state.setStateAtTime(Tone.State.Stopped, time); } return this; }; Tone.Clock.prototype.pause = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Paused, time); } return this; }; Tone.Clock.prototype._loop = function (time) { this._loopID = requestAnimationFrame(this._boundLoop); if (this._lookAhead === 'auto') { if (!this.isUndef(time)) { var diff = (time - this._lastUpdate) / 1000; this._lastUpdate = time; if (diff < this._threshold) { this._computedLookAhead = (9 * this._computedLookAhead + diff) / 10; } } } else { this._computedLookAhead = this._lookAhead; } var now = this.now(); var lookAhead = this._computedLookAhead * 2; var event = this._state.getEvent(now + lookAhead); var state = Tone.State.Stopped; if (event) { state = event.state; if (this._nextTick === -1 && state === Tone.State.Started) { this._nextTick = event.time; if (!this.isUndef(event.offset)) { this.ticks = event.offset; } } } if (state === Tone.State.Started) { while (now + lookAhead > this._nextTick) { if (now > this._nextTick + this._threshold) { this._nextTick = now; } var tickTime = this._nextTick; this._nextTick += 1 / this.frequency.getValueAtTime(this._nextTick); this.callback(tickTime); this.ticks++; } } else if (state === Tone.State.Stopped) { this._nextTick = -1; this.ticks = 0; } }; Tone.Clock.prototype.getStateAtTime = function (time) { return this._state.getStateAtTime(time); }; Tone.Clock.prototype.dispose = function () { cancelAnimationFrame(this._loopID); Tone.TimelineState.prototype.dispose.call(this); this._writable('frequency'); this.frequency.dispose(); this.frequency = null; this._boundLoop = Tone.noOp; this._nextTick = Infinity; this.callback = null; this._state.dispose(); this._state = null; }; return Tone.Clock; }(Tone_core_Tone, Tone_signal_TimelineSignal); var metro; metro = function () { 'use strict'; var p5sound = master; // requires the Tone.js library's Clock (MIT license, Yotam Mann) // https://github.com/TONEnoTONE/Tone.js/ var Clock = Tone_core_Clock; var ac = p5sound.audiocontext; // var upTick = false; p5.Metro = function () { this.clock = new Clock({ 'callback': this.ontick.bind(this) }); this.syncedParts = []; this.bpm = 120; // gets overridden by p5.Part this._init(); this.tickCallback = function () { }; }; var prevTick = 0; var tatumTime = 0; p5.Metro.prototype.ontick = function (tickTime) { var elapsedTime = tickTime - prevTick; var secondsFromNow = tickTime - p5sound.audiocontext.currentTime; if (elapsedTime - tatumTime <= -0.02) { return; } else { prevTick = tickTime; // for all of the active things on the metro: for (var i in this.syncedParts) { var thisPart = this.syncedParts[i]; thisPart.incrementStep(secondsFromNow); // each synced source keeps track of its own beat number for (var j in thisPart.phrases) { var thisPhrase = thisPart.phrases[j]; var phraseArray = thisPhrase.sequence; var bNum = this.metroTicks % phraseArray.length; if (phraseArray[bNum] !== 0 && (this.metroTicks < phraseArray.length || !thisPhrase.looping)) { thisPhrase.callback(secondsFromNow, phraseArray[bNum]); } } } this.metroTicks += 1; this.tickCallback(secondsFromNow); } }; p5.Metro.prototype.setBPM = function (bpm, rampTime) { var beatTime = 60 / (bpm * this.tatums); var now = p5sound.audiocontext.currentTime; tatumTime = beatTime; var rampTime = rampTime || 0; this.clock.frequency.setValueAtTime(this.clock.frequency.value, now); this.clock.frequency.linearRampToValueAtTime(bpm, now + rampTime); this.bpm = bpm; }; p5.Metro.prototype.getBPM = function (tempo) { return this.clock.getRate() / this.tatums * 60; }; p5.Metro.prototype._init = function () { this.metroTicks = 0; }; // clear existing synced parts, add only this one p5.Metro.prototype.resetSync = function (part) { this.syncedParts = [part]; }; // push a new synced part to the array p5.Metro.prototype.pushSync = function (part) { this.syncedParts.push(part); }; p5.Metro.prototype.start = function (timeFromNow) { var t = timeFromNow || 0; var now = p5sound.audiocontext.currentTime; this.clock.start(now + t); this.setBPM(this.bpm); }; p5.Metro.prototype.stop = function (timeFromNow) { var t = timeFromNow || 0; var now = p5sound.audiocontext.currentTime; if (this.clock._oscillator) { this.clock.stop(now + t); } }; p5.Metro.prototype.beatLength = function (tatums) { this.tatums = 1 / tatums / 4; }; }(master, Tone_core_Clock); var looper; looper = function () { 'use strict'; var p5sound = master; var bpm = 120; /** * Set the global tempo, in beats per minute, for all * p5.Parts. This method will impact all active p5.Parts. * * @param {Number} BPM Beats Per Minute * @param {Number} rampTime Seconds from now */ p5.prototype.setBPM = function (BPM, rampTime) { bpm = BPM; for (var i in p5sound.parts) { p5sound.parts[i].setBPM(bpm, rampTime); } }; /** * <p>A phrase is a pattern of musical events over time, i.e. * a series of notes and rests.</p> * * <p>Phrases must be added to a p5.Part for playback, and * each part can play multiple phrases at the same time. * For example, one Phrase might be a kick drum, another * could be a snare, and another could be the bassline.</p> * * <p>The first parameter is a name so that the phrase can be * modified or deleted later. The callback is a a function that * this phrase will call at every step—for example it might be * called <code>playNote(value){}</code>. The array determines * which value is passed into the callback at each step of the * phrase. It can be numbers, an object with multiple numbers, * or a zero (0) indicates a rest so the callback won't be called).</p> * * @class p5.Phrase * @constructor * @param {String} name Name so that you can access the Phrase. * @param {Function} callback The name of a function that this phrase * will call. Typically it will play a sound, * and accept two parameters: a time at which * to play the sound (in seconds from now), * and a value from the sequence array. The * time should be passed into the play() or * start() method to ensure precision. * @param {Array} sequence Array of values to pass into the callback * at each step of the phrase. * @example * <div><code> * var mySound, myPhrase, myPart; * var pattern = [1,0,0,2,0,2,0,0]; * var msg = 'click to play'; * * function preload() { * mySound = loadSound('assets/beatbox.mp3'); * } * * function setup() { * noStroke(); * fill(255); * textAlign(CENTER); * masterVolume(0.1); * * myPhrase = new p5.Phrase('bbox', makeSound, pattern); * myPart = new p5.Part(); * myPart.addPhrase(myPhrase); * myPart.setBPM(60); * } * * function draw() { * background(0); * text(msg, width/2, height/2); * } * * function makeSound(time, playbackRate) { * mySound.rate(playbackRate); * mySound.play(time); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * myPart.start(); * msg = 'playing pattern'; * } * } * * </code></div> */ p5.Phrase = function (name, callback, sequence) { this.phraseStep = 0; this.name = name; this.callback = callback; /** * Array of values to pass into the callback * at each step of the phrase. Depending on the callback * function's requirements, these values may be numbers, * strings, or an object with multiple parameters. * Zero (0) indicates a rest. * * @property sequence * @type {Array} */ this.sequence = sequence; }; /** * <p>A p5.Part plays back one or more p5.Phrases. Instantiate a part * with steps and tatums. By default, each step represents 1/16th note.</p> * * <p>See p5.Phrase for more about musical timing.</p> * * @class p5.Part * @constructor * @param {Number} [steps] Steps in the part * @param {Number} [tatums] Divisions of a beat (default is 1/16, a quarter note) * @example * <div><code> * var box, drum, myPart; * var boxPat = [1,0,0,2,0,2,0,0]; * var drumPat = [0,1,1,0,2,0,1,0]; * var msg = 'click to play'; * * function preload() { * box = loadSound('assets/beatbox.mp3'); * drum = loadSound('assets/drum.mp3'); * } * * function setup() { * noStroke(); * fill(255); * textAlign(CENTER); * masterVolume(0.1); * * var boxPhrase = new p5.Phrase('box', playBox, boxPat); * var drumPhrase = new p5.Phrase('drum', playDrum, drumPat); * myPart = new p5.Part(); * myPart.addPhrase(boxPhrase); * myPart.addPhrase(drumPhrase); * myPart.setBPM(60); * masterVolume(0.1); * } * * function draw() { * background(0); * text(msg, width/2, height/2); * } * * function playBox(time, playbackRate) { * box.rate(playbackRate); * box.play(time); * } * * function playDrum(time, playbackRate) { * drum.rate(playbackRate); * drum.play(time); * } * * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * myPart.start(); * msg = 'playing part'; * } * } * </code></div> */ p5.Part = function (steps, bLength) { this.length = steps || 0; // how many beats this.partStep = 0; this.phrases = []; this.looping = false; this.isPlaying = false; // what does this looper do when it gets to the last step? this.onended = function () { this.stop(); }; this.tatums = bLength || 0.0625; // defaults to quarter note this.metro = new p5.Metro(); this.metro._init(); this.metro.beatLength(this.tatums); this.metro.setBPM(bpm); p5sound.parts.push(this); this.callback = function () { }; }; /** * Set the tempo of this part, in Beats Per Minute. * * @method setBPM * @param {Number} BPM Beats Per Minute * @param {Number} [rampTime] Seconds from now */ p5.Part.prototype.setBPM = function (tempo, rampTime) { this.metro.setBPM(tempo, rampTime); }; /** * Returns the Beats Per Minute of this currently part. * * @method getBPM * @return {Number} */ p5.Part.prototype.getBPM = function () { return this.metro.getBPM(); }; /** * Start playback of this part. It will play * through all of its phrases at a speed * determined by setBPM. * * @method start * @param {Number} [time] seconds from now */ p5.Part.prototype.start = function (time) { if (!this.isPlaying) { this.isPlaying = true; this.metro.resetSync(this); var t = time || 0; this.metro.start(t); } }; /** * Loop playback of this part. It will begin * looping through all of its phrases at a speed * determined by setBPM. * * @method loop * @param {Number} [time] seconds from now */ p5.Part.prototype.loop = function (time) { this.looping = true; // rest onended function this.onended = function () { this.partStep = 0; }; var t = time || 0; this.start(t); }; /** * Tell the part to stop looping. * * @method noLoop */ p5.Part.prototype.noLoop = function () { this.looping = false; // rest onended function this.onended = function () { this.stop(); }; }; /** * Stop the part and cue it to step 0. * * @method stop * @param {Number} [time] seconds from now */ p5.Part.prototype.stop = function (time) { this.partStep = 0; this.pause(time); }; /** * Pause the part. Playback will resume * from the current step. * * @method pause * @param {Number} time seconds from now */ p5.Part.prototype.pause = function (time) { this.isPlaying = false; var t = time || 0; this.metro.stop(t); }; /** * Add a p5.Phrase to this Part. * * @method addPhrase * @param {p5.Phrase} phrase reference to a p5.Phrase */ p5.Part.prototype.addPhrase = function (name, callback, array) { var p; if (arguments.length === 3) { p = new p5.Phrase(name, callback, array); } else if (arguments[0] instanceof p5.Phrase) { p = arguments[0]; } else { throw 'invalid input. addPhrase accepts name, callback, array or a p5.Phrase'; } this.phrases.push(p); // reset the length if phrase is longer than part's existing length if (p.sequence.length > this.length) { this.length = p.sequence.length; } }; /** * Remove a phrase from this part, based on the name it was * given when it was created. * * @method removePhrase * @param {String} phraseName */ p5.Part.prototype.removePhrase = function (name) { for (var i in this.phrases) { if (this.phrases[i].name === name) { this.phrases.split(i, 1); } } }; /** * Get a phrase from this part, based on the name it was * given when it was created. Now you can modify its array. * * @method getPhrase * @param {String} phraseName */ p5.Part.prototype.getPhrase = function (name) { for (var i in this.phrases) { if (this.phrases[i].name === name) { return this.phrases[i]; } } }; /** * Get a phrase from this part, based on the name it was * given when it was created. Now you can modify its array. * * @method replaceSequence * @param {String} phraseName * @param {Array} sequence Array of values to pass into the callback * at each step of the phrase. */ p5.Part.prototype.replaceSequence = function (name, array) { for (var i in this.phrases) { if (this.phrases[i].name === name) { this.phrases[i].sequence = array; } } }; p5.Part.prototype.incrementStep = function (time) { if (this.partStep < this.length - 1) { this.callback(time); this.partStep += 1; } else { if (this.looping) { this.callback(time); } this.onended(); this.partStep = 0; } }; /** * Fire a callback function at every step. * * @method onStep * @param {Function} callback The name of the callback * you want to fire * on every beat/tatum. */ p5.Part.prototype.onStep = function (callback) { this.callback = callback; }; // =============== // p5.Score // =============== /** * A Score consists of a series of Parts. The parts will * be played back in order. For example, you could have an * A part, a B part, and a C part, and play them back in this order * <code>new p5.Score(a, a, b, a, c)</code> * * @class p5.Score * @constructor * @param {p5.Part} part(s) One or multiple parts, to be played in sequence. * @return {p5.Score} */ p5.Score = function () { // for all of the arguments this.parts = []; this.currentPart = 0; var thisScore = this; for (var i in arguments) { this.parts[i] = arguments[i]; this.parts[i].nextPart = this.parts[i + 1]; this.parts[i].onended = function () { thisScore.resetPart(i); playNextPart(thisScore); }; } this.looping = false; }; p5.Score.prototype.onended = function () { if (this.looping) { // this.resetParts(); this.parts[0].start(); } else { this.parts[this.parts.length - 1].onended = function () { this.stop(); this.resetParts(); }; } this.currentPart = 0; }; /** * Start playback of the score. * * @method start */ p5.Score.prototype.start = function () { this.parts[this.currentPart].start(); this.scoreStep = 0; }; /** * Stop playback of the score. * * @method stop */ p5.Score.prototype.stop = function () { this.parts[this.currentPart].stop(); this.currentPart = 0; this.scoreStep = 0; }; /** * Pause playback of the score. * * @method pause */ p5.Score.prototype.pause = function () { this.parts[this.currentPart].stop(); }; /** * Loop playback of the score. * * @method loop */ p5.Score.prototype.loop = function () { this.looping = true; this.start(); }; /** * Stop looping playback of the score. If it * is currently playing, this will go into effect * after the current round of playback completes. * * @method noLoop */ p5.Score.prototype.noLoop = function () { this.looping = false; }; p5.Score.prototype.resetParts = function () { for (var i in this.parts) { this.resetPart(i); } }; p5.Score.prototype.resetPart = function (i) { this.parts[i].stop(); this.parts[i].partStep = 0; for (var p in this.parts[i].phrases) { this.parts[i].phrases[p].phraseStep = 0; } }; /** * Set the tempo for all parts in the score * * @param {Number} BPM Beats Per Minute * @param {Number} rampTime Seconds from now */ p5.Score.prototype.setBPM = function (bpm, rampTime) { for (var i in this.parts) { this.parts[i].setBPM(bpm, rampTime); } }; function playNextPart(aScore) { aScore.currentPart++; if (aScore.currentPart >= aScore.parts.length) { aScore.scoreStep = 0; aScore.onended(); } else { aScore.scoreStep = 0; aScore.parts[aScore.currentPart - 1].stop(); aScore.parts[aScore.currentPart].start(); } } }(master); var soundRecorder; soundRecorder = function () { 'use strict'; var p5sound = master; var ac = p5sound.audiocontext; /** * <p>Record sounds for playback and/or to save as a .wav file. * The p5.SoundRecorder records all sound output from your sketch, * or can be assigned a specific source with setInput().</p> * <p>The record() method accepts a p5.SoundFile as a parameter. * When playback is stopped (either after the given amount of time, * or with the stop() method), the p5.SoundRecorder will send its * recording to that p5.SoundFile for playback.</p> * * @class p5.SoundRecorder * @constructor * @example * <div><code> * var mic, recorder, soundFile; * var state = 0; * * function setup() { * background(200); * // create an audio in * mic = new p5.AudioIn(); * * // prompts user to enable their browser mic * mic.start(); * * // create a sound recorder * recorder = new p5.SoundRecorder(); * * // connect the mic to the recorder * recorder.setInput(mic); * * // this sound file will be used to * // playback & save the recording * soundFile = new p5.SoundFile(); * * text('keyPress to record', 20, 20); * } * * function keyPressed() { * // make sure user enabled the mic * if (state === 0 && mic.enabled) { * * // record to our p5.SoundFile * recorder.record(soundFile); * * background(255,0,0); * text('Recording!', 20, 20); * state++; * } * else if (state === 1) { * background(0,255,0); * * // stop recorder and * // send result to soundFile * recorder.stop(); * * text('Stopped', 20, 20); * state++; * } * * else if (state === 2) { * soundFile.play(); // play the result! * save(soundFile, 'mySound.wav'); * state++; * } * } * </div></code> */ p5.SoundRecorder = function () { this.input = ac.createGain(); this.output = ac.createGain(); this.recording = false; this.bufferSize = 1024; this._channels = 2; // stereo (default) this._clear(); // initialize variables this._jsNode = ac.createScriptProcessor(this.bufferSize, this._channels, 2); this._jsNode.onaudioprocess = this._audioprocess.bind(this); /** * callback invoked when the recording is over * @private * @type {function(Float32Array)} */ this._callback = function () { }; // connections this._jsNode.connect(p5.soundOut._silentNode); this.setInput(); // add this p5.SoundFile to the soundArray p5sound.soundArray.push(this); }; /** * Connect a specific device to the p5.SoundRecorder. * If no parameter is given, p5.SoundRecorer will record * all audible p5.sound from your sketch. * * @method setInput * @param {Object} [unit] p5.sound object or a web audio unit * that outputs sound */ p5.SoundRecorder.prototype.setInput = function (unit) { this.input.disconnect(); this.input = null; this.input = ac.createGain(); this.input.connect(this._jsNode); this.input.connect(this.output); if (unit) { unit.connect(this.input); } else { p5.soundOut.output.connect(this.input); } }; /** * Start recording. To access the recording, provide * a p5.SoundFile as the first parameter. The p5.SoundRecorder * will send its recording to that p5.SoundFile for playback once * recording is complete. Optional parameters include duration * (in seconds) of the recording, and a callback function that * will be called once the complete recording has been * transfered to the p5.SoundFile. * * @method record * @param {p5.SoundFile} soundFile p5.SoundFile * @param {Number} [duration] Time (in seconds) * @param {Function} [callback] The name of a function that will be * called once the recording completes */ p5.SoundRecorder.prototype.record = function (sFile, duration, callback) { this.recording = true; if (duration) { this.sampleLimit = Math.round(duration * ac.sampleRate); } if (sFile && callback) { this._callback = function () { this.buffer = this._getBuffer(); sFile.setBuffer(this.buffer); callback(); }; } else if (sFile) { this._callback = function () { this.buffer = this._getBuffer(); sFile.setBuffer(this.buffer); }; } }; /** * Stop the recording. Once the recording is stopped, * the results will be sent to the p5.SoundFile that * was given on .record(), and if a callback function * was provided on record, that function will be called. * * @method stop */ p5.SoundRecorder.prototype.stop = function () { this.recording = false; this._callback(); this._clear(); }; p5.SoundRecorder.prototype._clear = function () { this._leftBuffers = []; this._rightBuffers = []; this.recordedSamples = 0; this.sampleLimit = null; }; /** * internal method called on audio process * * @private * @param {AudioProcessorEvent} event */ p5.SoundRecorder.prototype._audioprocess = function (event) { if (this.recording === false) { return; } else if (this.recording === true) { // if we are past the duration, then stop... else: if (this.sampleLimit && this.recordedSamples >= this.sampleLimit) { this.stop(); } else { // get channel data var left = event.inputBuffer.getChannelData(0); var right = event.inputBuffer.getChannelData(1); // clone the samples this._leftBuffers.push(new Float32Array(left)); this._rightBuffers.push(new Float32Array(right)); this.recordedSamples += this.bufferSize; } } }; p5.SoundRecorder.prototype._getBuffer = function () { var buffers = []; buffers.push(this._mergeBuffers(this._leftBuffers)); buffers.push(this._mergeBuffers(this._rightBuffers)); return buffers; }; p5.SoundRecorder.prototype._mergeBuffers = function (channelBuffer) { var result = new Float32Array(this.recordedSamples); var offset = 0; var lng = channelBuffer.length; for (var i = 0; i < lng; i++) { var buffer = channelBuffer[i]; result.set(buffer, offset); offset += buffer.length; } return result; }; p5.SoundRecorder.prototype.dispose = function () { this._clear(); // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this._callback = function () { }; if (this.input) { this.input.disconnect(); } this.input = null; this._jsNode = null; }; /** * Save a p5.SoundFile as a .wav audio file. * * @method saveSound * @param {p5.SoundFile} soundFile p5.SoundFile that you wish to save * @param {String} name name of the resulting .wav file. */ p5.prototype.saveSound = function (soundFile, name) { var leftChannel = soundFile.buffer.getChannelData(0); var rightChannel = soundFile.buffer.getChannelData(1); var interleaved = interleave(leftChannel, rightChannel); // create the buffer and view to create the .WAV file var buffer = new ArrayBuffer(44 + interleaved.length * 2); var view = new DataView(buffer); // write the WAV container, // check spec at: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ // RIFF chunk descriptor writeUTFBytes(view, 0, 'RIFF'); view.setUint32(4, 44 + interleaved.length * 2, true); writeUTFBytes(view, 8, 'WAVE'); // FMT sub-chunk writeUTFBytes(view, 12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); // stereo (2 channels) view.setUint16(22, 2, true); view.setUint32(24, 44100, true); view.setUint32(28, 44100 * 4, true); view.setUint16(32, 4, true); view.setUint16(34, 16, true); // data sub-chunk writeUTFBytes(view, 36, 'data'); view.setUint32(40, interleaved.length * 2, true); // write the PCM samples var lng = interleaved.length; var index = 44; var volume = 1; for (var i = 0; i < lng; i++) { view.setInt16(index, interleaved[i] * (32767 * volume), true); index += 2; } p5.prototype.writeFile([view], name, 'wav'); }; // helper methods to save waves function interleave(leftChannel, rightChannel) { var length = leftChannel.length + rightChannel.length; var result = new Float32Array(length); var inputIndex = 0; for (var index = 0; index < length;) { result[index++] = leftChannel[inputIndex]; result[index++] = rightChannel[inputIndex]; inputIndex++; } return result; } function writeUTFBytes(view, offset, string) { var lng = string.length; for (var i = 0; i < lng; i++) { view.setUint8(offset + i, string.charCodeAt(i)); } } }(sndcore, master); var peakdetect; peakdetect = function () { 'use strict'; var p5sound = master; /** * <p>PeakDetect works in conjunction with p5.FFT to * look for onsets in some or all of the frequency spectrum. * </p> * <p> * To use p5.PeakDetect, call <code>update</code> in the draw loop * and pass in a p5.FFT object. * </p> * <p> * You can listen for a specific part of the frequency spectrum by * setting the range between <code>freq1</code> and <code>freq2</code>. * </p> * * <p><code>threshold</code> is the threshold for detecting a peak, * scaled between 0 and 1. It is logarithmic, so 0.1 is half as loud * as 1.0.</p> * * <p> * The update method is meant to be run in the draw loop, and * <b>frames</b> determines how many loops must pass before * another peak can be detected. * For example, if the frameRate() = 60, you could detect the beat of a * 120 beat-per-minute song with this equation: * <code> framesPerPeak = 60 / (estimatedBPM / 60 );</code> * </p> * * <p> * Based on example contribtued by @b2renger, and a simple beat detection * explanation by <a * href="http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/" * target="_blank">Felix Turner</a>. * </p> * * @class p5.PeakDetect * @constructor * @param {Number} [freq1] lowFrequency - defaults to 20Hz * @param {Number} [freq2] highFrequency - defaults to 20000 Hz * @param {Number} [threshold] Threshold for detecting a beat between 0 and 1 * scaled logarithmically where 0.1 is 1/2 the loudness * of 1.0. Defaults to 0.35. * @param {Number} [framesPerPeak] Defaults to 20. * @example * <div><code> * * var cnv, soundFile, fft, peakDetect; * var ellipseWidth = 10; * * function setup() { * background(0); * noStroke(); * fill(255); * textAlign(CENTER); * * soundFile = loadSound('assets/beat.mp3'); * * // p5.PeakDetect requires a p5.FFT * fft = new p5.FFT(); * peakDetect = new p5.PeakDetect(); * * } * * function draw() { * background(0); * text('click to play/pause', width/2, height/2); * * // peakDetect accepts an fft post-analysis * fft.analyze(); * peakDetect.update(fft); * * if ( peakDetect.isDetected ) { * ellipseWidth = 50; * } else { * ellipseWidth *= 0.95; * } * * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); * } * * // toggle play/stop when canvas is clicked * function mouseClicked() { * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { * if (soundFile.isPlaying() ) { * soundFile.stop(); * } else { * soundFile.play(); * } * } * } * </code></div> */ p5.PeakDetect = function (freq1, freq2, threshold, _framesPerPeak) { var framesPerPeak; // framesPerPeak determines how often to look for a beat. // If a beat is provided, try to look for a beat based on bpm this.framesPerPeak = _framesPerPeak || 20; this.framesSinceLastPeak = 0; this.decayRate = 0.95; this.threshold = threshold || 0.35; this.cutoff = 0; // how much to increase the cutoff // TO DO: document this / figure out how to make it accessible this.cutoffMult = 1.5; this.energy = 0; this.penergy = 0; // TO DO: document this property / figure out how to make it accessible this.currentValue = 0; /** * isDetected is set to true when a peak is detected. * * @attribute isDetected * @type {Boolean} * @default false */ this.isDetected = false; this.f1 = freq1 || 40; this.f2 = freq2 || 20000; // function to call when a peak is detected this._onPeak = function () { }; }; /** * The update method is run in the draw loop. * * Accepts an FFT object. You must call .analyze() * on the FFT object prior to updating the peakDetect * because it relies on a completed FFT analysis. * * @method update * @param {p5.FFT} fftObject A p5.FFT object */ p5.PeakDetect.prototype.update = function (fftObject) { var nrg = this.energy = fftObject.getEnergy(this.f1, this.f2) / 255; if (nrg > this.cutoff && nrg > this.threshold && nrg - this.penergy > 0) { // trigger callback this._onPeak(); this.isDetected = true; // debounce this.cutoff = nrg * this.cutoffMult; this.framesSinceLastPeak = 0; } else { this.isDetected = false; if (this.framesSinceLastPeak <= this.framesPerPeak) { this.framesSinceLastPeak++; } else { this.cutoff *= this.decayRate; this.cutoff = Math.max(this.cutoff, this.threshold); } } this.currentValue = nrg; this.penergy = nrg; }; /** * onPeak accepts two arguments: a function to call when * a peak is detected. The value of the peak, * between 0.0 and 1.0, is passed to the callback. * * @method onPeak * @param {Function} callback Name of a function that will * be called when a peak is * detected. * @param {Object} [val] Optional value to pass * into the function when * a peak is detected. * @example * <div><code> * var cnv, soundFile, fft, peakDetect; * var ellipseWidth = 0; * * function setup() { * cnv = createCanvas(100,100); * textAlign(CENTER); * * soundFile = loadSound('assets/beat.mp3'); * fft = new p5.FFT(); * peakDetect = new p5.PeakDetect(); * * setupSound(); * * // when a beat is detected, call triggerBeat() * peakDetect.onPeak(triggerBeat); * } * * function draw() { * background(0); * fill(255); * text('click to play', width/2, height/2); * * fft.analyze(); * peakDetect.update(fft); * * ellipseWidth *= 0.95; * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); * } * * // this function is called by peakDetect.onPeak * function triggerBeat() { * ellipseWidth = 50; * } * * // mouseclick starts/stops sound * function setupSound() { * cnv.mouseClicked( function() { * if (soundFile.isPlaying() ) { * soundFile.stop(); * } else { * soundFile.play(); * } * }); * } * </code></div> */ p5.PeakDetect.prototype.onPeak = function (callback, val) { var self = this; self._onPeak = function () { callback(self.energy, val); }; }; }(master); var gain; gain = function () { 'use strict'; var p5sound = master; /** * A gain node is usefull to set the relative volume of sound. * It's typically used to build mixers. * * @class p5.Gain * @constructor * @example * <div><code> * * // load two soundfile and crossfade beetween them * var sound1,sound2; * var gain1, gain2, gain3; * * function preload(){ * soundFormats('ogg', 'mp3'); * sound1 = loadSound('../_files/Damscray_-_Dancing_Tiger_01'); * sound2 = loadSound('../_files/beat.mp3'); * } * * function setup() { * createCanvas(400,200); * * // create a 'master' gain to which we will connect both soundfiles * gain3 = new p5.Gain(); * gain3.connect(); * * // setup first sound for playing * sound1.rate(1); * sound1.loop(); * sound1.disconnect(); // diconnect from p5 output * * gain1 = new p5.Gain(); // setup a gain node * gain1.setInput(sound1); // connect the first sound to its input * gain1.connect(gain3); // connect its output to the 'master' * * sound2.rate(1); * sound2.disconnect(); * sound2.loop(); * * gain2 = new p5.Gain(); * gain2.setInput(sound2); * gain2.connect(gain3); * * } * * function draw(){ * background(180); * * // calculate the horizontal distance beetween the mouse and the right of the screen * var d = dist(mouseX,0,width,0); * * // map the horizontal position of the mouse to values useable for volume control of sound1 * var vol1 = map(mouseX,0,width,0,1); * var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa * * gain1.amp(vol1,0.5,0); * gain2.amp(vol2,0.5,0); * * // map the vertical position of the mouse to values useable for 'master volume control' * var vol3 = map(mouseY,0,height,0,1); * gain3.amp(vol3,0.5,0); * } *</code></div> * */ p5.Gain = function () { this.ac = p5sound.audiocontext; this.input = this.ac.createGain(); this.output = this.ac.createGain(); // otherwise, Safari distorts this.input.gain.value = 0.5; this.input.connect(this.output); // add to the soundArray p5sound.soundArray.push(this); }; /** * Connect a source to the gain node. * * @method setInput * @param {Object} src p5.sound / Web Audio object with a sound * output. */ p5.Gain.prototype.setInput = function (src) { src.connect(this.input); }; /** * Send output to a p5.sound or web audio object * * @method connect * @param {Object} unit */ p5.Gain.prototype.connect = function (unit) { var u = unit || p5.soundOut.input; this.output.connect(u.input ? u.input : u); }; /** * Disconnect all output. * * @method disconnect */ p5.Gain.prototype.disconnect = function () { this.output.disconnect(); }; /** * Set the output level of the gain node. * * @method amp * @param {Number} volume amplitude between 0 and 1.0 * @param {Number} [rampTime] create a fade that lasts rampTime * @param {Number} [timeFromNow] schedule this event to happen * seconds from now */ p5.Gain.prototype.amp = function (vol, rampTime, tFromNow) { var rampTime = rampTime || 0; var tFromNow = tFromNow || 0; var now = p5sound.audiocontext.currentTime; var currentVol = this.output.gain.value; this.output.gain.cancelScheduledValues(now); this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); }; p5.Gain.prototype.dispose = function () { // remove reference from soundArray var index = p5sound.soundArray.indexOf(this); p5sound.soundArray.splice(index, 1); this.output.disconnect(); this.input.disconnect(); this.output = undefined; this.input = undefined; }; }(master, sndcore); var src_app; src_app = function () { 'use strict'; var p5SOUND = sndcore; return p5SOUND; }(sndcore, master, helpers, errorHandler, panner, soundfile, amplitude, fft, signal, oscillator, env, pulse, noise, audioin, filter, delay, reverb, metro, looper, soundRecorder, peakdetect, gain); }));
/** * Created by eversvik on 22.06.2015. */ /// <reference path='../_all.ts' /> //# sourceMappingURL=ITodoStorage.js.map
const React = require('react'); const IconBase = require('react-icon-base'); export default class EditorIndent extends React.Component { render() { return ( <IconBase viewBox='0 0 20 20' {...this.props}> <path d='M3 5v-2h9v2h-9zM13 4v-1h4v1h-4zM13 7h2v-2l4 3.5-4 3.5v-2h-2v-3zM3 8v-2h9v2h-9zM5 11v-2h7v2h-7zM3 14v-2h9v2h-9zM13 14v-1h4v1h-4zM9 17v-2h3v2h-3z'/> </IconBase> ); } }
import expect from 'expect'; import $q from '../src/index'; describe('querify', () => { it(`should querify webpack loader configs`, () => { const config = { css: { modules: true, importLoaders: 2, sourceMap: true }, sass: { outputStyle: 'expanded', sourceMap: true, sourceMapContents: true }, autoprefixer: { browsers: 'last 4 version' } }; expect($q(config)).toBe('css?{"modules":true,"importLoaders":2,"sourceMap":true}!sass?{"outputStyle":"expanded","sourceMap":true,"sourceMapContents":true}!autoprefixer?{"browsers":"last 4 version"}'); }); });
(function() { 'use strict'; b3e.nodes.Fuzz = b3e.node.create('Fuzz', b3e.MODULATOR, { maxInConnections: 1, properties: [ ['curve', b3e.properties.Curve, { lockYDomain: true, }], ] }); })();
// test-childipc.js // © Harald Rudell 2013 MIT License var childipc = require('../lib/childipc') // https://github.com/haraldrudell/mochawrapper var assert = require('mochawrapper') exports['Child Ipc:'] = { 'Exports': function () { assert.exportsTest(childipc, 1) }, 'TODO': function () { }, }
#!/usr/bin/env node /** * Game Idea Machine * a twitter bot which tweets random game ideas * this file is the wrapper around the generator, and handles all the twitter related stuff */ var Twit = require('twit'); var fs = require('fs'); var path = require('path'); var util = require('util'); var generator = require('./generator.js'); var secrets = require('./secrets.js'); var data = require('./data.js'); var Twitter = new Twit(secrets); handleArguments(); /** * decide what to do based on what commands were passed in */ function handleArguments() { var count = 1, type = null; switch(process.argv[2]) { // generate some stuff case 'gen' : // how many? if(process.argv[3]) { count = parseInt(process.argv[3]); } // specific type? if(process.argv[4]) { type = process.argv[4]; } // spit them out while(count--) { console.log( generator.generateSafe(type) ); } break; // send a tweet case 'tweet': tweet(); break; // listen for commands case 'monitor': monitor(); break; } } /** * watch the gameideamachine user stream * look for tweets at it */ function monitor() { var stream = Twitter.stream('user', { with:'user'}); stream.on('tweet', function (tweet) { // ignore own tweets if(tweet.user.screen_name == 'gameideamachine') { return; } var message = tweet.text; util.log('tweet received from ' + tweet.user.screen_name); // ignore everything other than "@gameidemachine command" (for now) if(message.indexOf('@gameideamachine') !== 0) { util.log('not aimed at me'); return; } var command = message.replace('@gameideamachine','').trim().toLowerCase().split(' ')[0]; if(command === 'idea') { reply(tweet, generator.generateSafe(null, tweet.user.screen_name)); } else if(data[command]) { reply(tweet, generator.generateSafe(command, tweet.user.screen_name)); } else { util.log('unknown command ' + String(command) ); return; } }); } function reply(tweet, message) { var status = '@' + tweet.user.screen_name + ' ' + message; Twitter.post('statuses/update', { status: status, in_reply_to_status_id : tweet.id_str }, function(err, reply) { if(err) { util.log(err); } else { util.log('reply sent to ' + tweet.user.screen_name); } }); } function tweet() { var file = path.resolve(__dirname, 'queue.txt'); fs.readFile(file, function(err, contents) { var queue = contents.toString().split('\n'); var status = queue.shift(); if(!status) { status = generator.generateSafe(); } Twitter.post('statuses/update', { status: status }, function(err, reply) { // drop any empty elements queue = queue.filter(function(e){ return e; }); // add a replacement to the queue queue.push(generator.generateSafe()); fs.writeFile(file, queue.join('\n'), function (err) { }); if(err) { util.log(err); } else { util.log('scheduled tweet sent'); } }); }); }
import React from 'react'; import {SafeAreaView, Text, StatusBar, Platform, Button} from 'react-native'; import { BluetoothStatus, useBluetoothStatus, } from 'react-native-bluetooth-status'; class AppClass extends React.Component { state = { bluetoothState: undefined, }; componentDidMount() { this.checkInitialBluetoothState(); BluetoothStatus.addListener(isEnabled => { this.setState({bluetoothState: isEnabled ? 'On' : 'Off'}); }); } async checkInitialBluetoothState() { const isEnabled = await BluetoothStatus.state(); this.setState({bluetoothState: isEnabled ? 'On' : 'Off'}); } async toggleBluetooth() { const isEnabled = await BluetoothStatus.state(); BluetoothStatus.enable(!isEnabled); } render() { const {bluetoothState} = this.state; return ( <> <StatusBar barStyle="dark-content" /> <SafeAreaView> <Text>New tester is here!</Text> {bluetoothState !== undefined && <Text>{bluetoothState}</Text>} {Platform.OS === 'android' && ( <Button title="Toggle BT" onPress={() => this.toggleBluetooth()} /> )} </SafeAreaView> </> ); } } export default AppClass;
import React, { Component, PropTypes } from 'react'; import _ from 'lodash'; import parentStyles from './ArrayField.css'; import styles from './ObjectArrayField.css'; import ArrayField from './ArrayField'; import Field from './Field'; import SortableList from '../../../ui/SortableList'; import Button from '../../../ui/Button'; import Icon from '../../../ui/Icon'; export default class ObjectArrayField extends ArrayField { constructor(props) { super(props); this.state.definition = null; this.state.value = null; } handleAdd() { const values = Array.isArray(this.props.value) ? this.props.value : []; values.push(this.state.value); this.props.onValueChange(this.props.definition, values); this.setState({definition: null, value: null}); } handleCancelAdd(e) { this.setState({ definition: null, value: null, }); } handleItemValueChange(index, def, value, validation) { const values = Array.isArray(this.props.value) ? this.props.value : []; values[index] = value; this.props.onValueChange(this.props.definition, values); } handleNewItemValueChange(def, value, validation) { this.setState({value}); } handleNewItemCreate(definition) { this.setState({ value: definition.value || definition.defaultValue || null, definition }) } pickFieldDefinition(item) { const isObject = _.isObject(item); const keys = isObject ? Object.keys(item) : []; const defs = this.props.definition.fields; return defs.find(def => { if (!def.fields && !keys.length) { // We're dealing with a simple value, so a guess can't be made well. // Just return the first non-complex field definition. return true; } if (!def.fields) return false; const objectNames = def.fields.map(field => field.name); return objectNames.length === keys.length && objectNames.every((el, i) => el === keys[i]); }); } renderInput() { let buttons, badges, field; buttons = this.props.definition.fields.map((definition, i) => { return ( <Button className={styles.newItemButton} key={i} onClick={this.handleNewItemCreate.bind(this, definition)}> {definition.label} <Icon name="add"/> </Button> ); }); if (Array.isArray(this.props.value)) { badges = this.props.value.map((item, i) => { const fieldDefinition = this.pickFieldDefinition(item); let itemField = item; let itemTitle = ''; if (fieldDefinition) { itemTitle = fieldDefinition.label || fieldDefinition.name || ''; itemField = ( <Field id={this.props.id} definition={fieldDefinition} value={item} onValueChange={this.handleItemValueChange.bind(this, i)} /> ); } else if (_.isObject(item)) { itemTitle = 'Object'; itemField = JSON.stringify(item, false, 2); } return ( <div className={styles.item}> <div className={styles.header}> <Button mode="warning" className={styles.badge} key={i} onClick={this.handleRemove.bind(this, i)} title="Delete" > <Icon name="delete_forever"/> </Button> <div className={styles.title}>{itemTitle}</div> </div> {itemField} </div> ); }); } if (this.state.definition) { field = ( <div className={styles.newItem}> <Field definition={this.state.definition} value={this.state.value} onValueChange={this.handleNewItemValueChange.bind(this)} /> <div className={styles.buttons}> <Button className={styles.cancel} onClick={this.handleCancelAdd.bind(this)} title="Cancel">Cancel</Button> <Button mode="secondary" onClick={this.handleAdd.bind(this)} title="Add">Add {this.state.definition.label} <Icon name="add"/></Button> </div> </div> ); } return ( <div className={parentStyles.input}> <div className={parentStyles.badges}> <SortableList onChange={this.handleSort.bind(this)} items={badges}/> </div> {field} {buttons} </div> ); } }
if (!customValidators) { } else { customValidators.validateCnsaBaseline = function(viewValue, form, model) { var fieldId = form.fieldId; var returnValue = { custom: true, valid: false, error: { code: 0, element_ids: [] }, rootScopeBroadCast: true }; if (model.employment == 1) { var employedFields = [ 'full_part_time', 'occupation_level' ]; for (var i = 0; i < employedFields.length; i++) { var fieldName = employedFields[i]; if (!model[fieldName] || model[fieldName] == -88) { returnValue.error.element_ids.push('field-' + fieldName + '-' + fieldId); } } if (model.plan_return_work == -88) { returnValue.error.element_ids.push('field-plan_return_work-' + fieldId); } } if (model.employment == 2) { var notWorkingFields = [ 'employed_not_working', 'occupation_level' ]; for (var j = 0; j < notWorkingFields.length; j++) { var fieldName = notWorkingFields[j]; if (!model[fieldName] || model[fieldName] == -88) { returnValue.error.element_ids.push('field-' + fieldName + '-' + fieldId); } } if (model.plan_return_work == -88) { returnValue.error.element_ids.push('field-plan_return_work-' + fieldId); } } if (model.employment == 3) { if (!model.unemployed || model.unemployed == -88) { returnValue.error.element_ids.push('field-unemployed-' + fieldId); } } if (model.act_out_home == 1) { if (!model.describe_act_out || model.describe_act_out == -88) { returnValue.error.element_ids.push('field-describe_act_out-' + fieldId); } } if (model.act_in_home == 1) { if (!model.describe_act_in || model.describe_act_in == -88) { returnValue.error.element_ids.push('field-describe_act_in-' + fieldId); } } if (model.smoking_status == 1 || model.smoking_status == 2) { if (!model.smoking_cessation || model.smoking_cessation == -88) { returnValue.error.element_ids.push('field-smoking_cessation-' + fieldId); } } if (returnValue.error.element_ids.length > 0) { return returnValue; } return { valid: true }; } }
describe('prototype', function() { it('[new]', function() { var p = new T.Prototype(); var c = p.extend(); var i = c(); assert(i instanceof c); }); it('._arguments', function() { var p = new T.Prototype(); var i = p.extend()(1, 2, 3); assert(_.isArguments(i._arguments)); assert.equal(i._arguments[0], 1); assert.equal(i._arguments[1], 2); assert.equal(i._arguments[2], 3); }); it('.returner', function() { var p = new T.Prototype(); var c = p.extend(function() { this.returner = function() { var _this = this; return function() { return _this; }; }; }); var i = c(1, 2, 3)(); assert(i instanceof c); }); it('static', function() { var result = undefined; var p = new T.Prototype(); var c = p.extend('test', function() { var parent = this._parent; this.test = function() { result = 123; }; }); c.test(); assert.equal(result, 123); }); });
import config from 'config'; import axios from 'axios'; import URL from 'url'; import { AllNews } from './services'; import { configFetch } from './configuration'; export default (args) => { const url = URL.parse(AllNews); const params = { q: args.query } return axios(configFetch(url, 'get', params)).then(response => { console.log("response===: ", response.data); return response.data }); };
'use strict' module.exports = function (sequelize, DataTypes) { var Image = sequelize.define('Image', { url: DataTypes.STRING }, { underscored: true, freezeTableName: true, tableName: 'images' }) Image.associate = function (models) { Image.belongsTo(models.User, { foreignKey: 'user_id' }) } return Image }
/*global describe, it, beforeEach, afterEach*/ // libraries var path = require('path'), chai = require('chai'), spies = require('chai-spies'), expect = chai.expect, Q = require('q'); chai.use(spies); // code under test var provisionCmd = require('../src/command/provision'); // mocks var mockSpeedboat = require('./mock-speedboat'); var speedboat = {}; var droplet = {}; var options = { subdomain: 'subdomain', configObject: { hostname: 'hostname', destination: '/opt/app', image_id: 12345, digital_ocean: {} } }; describe('Provision', function () { var _consoleInfo, _consoleError; beforeEach(function (done) { speedboat = mockSpeedboat(); speedboat._options.domain_id = 123456; droplet.id = Date.now(); droplet.ip_address = '111.111.111.111'; _consoleInfo = console.info; _consoleError = console.error; console.info = chai.spy(function() {}); // we don't really want to log stuff console.info._real = _consoleInfo; // just in case we need it console.error = chai.spy(function() {}); // we don't really want to log stuff done(); }); afterEach(function() { // let's put the console methods back console.info = _consoleInfo; console.error = _consoleError; }); it('returns a command function', function (done) { var actual = provisionCmd(speedboat); expect(actual).to.be.a('function'); done(); }); describe('when a droplet already exists', function () { it('should succeed if the deploy command is successful', function (done) { speedboat.getDropletByName._resolveWith = droplet; var cmd = provisionCmd(speedboat); cmd(options).then(function () { expect(speedboat.plot).to.have.been.called.exactly(4); done(); }, function (err) { done(err); }); }); }); describe('when a droplet does not exist', function () { it('should succeed if the deploy command is successful', function (done) { speedboat.getDropletByName._resolveWith = null; speedboat.getDropletByName._rejectWith = null; speedboat.dropletGet._resolveWith = droplet; speedboat.provision._resolveWith = [droplet]; speedboat.domainRecordGetAll._resolveWith = []; var cmd = provisionCmd(speedboat); cmd(options).then(function () { expect(speedboat.plot).to.have.been.called.exactly(5); done(); }, function (err) { console.log(err); done(err); }); }); }); });
import _ from 'lodash' import Vue from 'vue/dist/vue' import test from 'ava' import nextTick from 'p-immediate' import FlexTable from '../../src/components/FlexTable' import FlexDataTable from '../../src/index' Vue.config.productionTip = false Vue.use(FlexDataTable) test('has a created hook', (t) => { t.true(_.isFunction(FlexTable.created)) }) test('has data as function', (t) => { t.true(_.isFunction(FlexTable.data)) }) test('can be mounted', async (t) => { document.body.innerHTML = ` <div id="app"> <flex-table :rows="[{ firstName: 'John' },{ firstName: 'Doe' }]"> <flex-table-column show="firstName" label="First name"></flex-table-column> </flex-table> </div> ` const vm = new Vue({ el: '#app' }) await nextTick t.snapshot(vm.$el.innerHTML) }) test('can format values using a formatting function passed by prop', async (t) => { document.body.innerHTML = ` <div id="app"> <flex-table :rows="[{ firstName: 'John' },{ firstName: 'Doe' }]"> <flex-table-column show="firstName" label="First name" :formatter="formatter"></flex-table-column> </flex-table> </div> ` const vm = new Vue({ el: '#app', methods: { formatter (value, properties) { return `Formatted: <strong>${value}</strong>` } } }) await nextTick t.snapshot(vm.$el.innerHTML) }) test('allows a scoped slot to custom template the table column', async (t) => { document.body.innerHTML = ` <div id="app"> <flex-table :data="[{ firstName: 'John' },{ firstName: 'Doe' }]"> <flex-table-column label="First name"> <template scope="row"> {{ row.firstName }} slot </template> </flex-table-column> </flex-table> </div> ` const vm = new Vue({ el: '#app' }) await nextTick t.snapshot(vm.$el.innerHTML) }) test('can display a filter for the table', async (t) => { document.body.innerHTML = ` <div id="app"> <flex-table show-filter :data="[{ firstName: 'John' },{ id: 2, firstName: 'Doe' }]"> <flex-table-column show="firstName" label="First name"></flex-table-column> </flex-table> </div> ` const vm = new Vue({ el: '#app' }) await nextTick t.snapshot(vm.$el.innerHTML) }) test('can pass row data as a function', async (t) => { document.body.innerHTML = ` <div id="app"> <flex-table show-filter :data="sampleFetchData"> <flex-table-column show="firstName" label="First name"></flex-table-column> </flex-table> </div> ` const vm = new Vue({ el: '#app', data: { sampleFetchData: () => { return { data: [ { firstName: 'John', lastName: 'Doe', email: 'johndoe@example.com', phone: '222-222-2222', nested: {song: 'Done Dirt Cheap'}, children: [ { firstName: 'Max', lastName: 'Joshie', email: 'maxj@example.com', phone: '333-333-3333', nested: {song: 'Back in Black'} }, { firstName: 'Josh', lastName: 'Max', email: 'jmax@example.com', phone: '333-333-3333', nested: {song: 'Born to be wild'} } ] }, { firstName: 'Jane', lastName: 'Doe', email: 'janedoe@example.com', phone: '222-222-2222', nested: {song: 'Enter Sandman'} }, { firstName: 'Jack', lastName: 'Davis', email: 'jackdavis@example.com', phone: '222-222-2222', nested: {song: 'Fire and Ice'} }, { firstName: 'Joan', lastName: 'Davis', email: 'joandavis@example.com', phone: '222-222-2222', nested: {song: 'Crackerman'} } ], pagination: { currentPage: 1, totalPages: 3 } } } } }) await nextTick t.snapshot(vm.$el.innerHTML) })
var require('fuse-bindings');