_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q52600
train
function() { // convert to a poly point string for (var i = 0, il = this.value.length, array = []; i < il; i++) array.push(this.value[i].join(',')) return array.join(' ') }
javascript
{ "resource": "" }
q52601
train
function(o, ease, delay){ if(typeof o == 'object'){ ease = o.ease delay = o.delay o = o.duration } var situation = new SVG.Situation({ duration: o || 1000, delay: delay || 0, ease: SVG.easing[ease || '-'] || ease }) this.queue(situation) return this }
javascript
{ "resource": "" }
q52602
train
function(o, ease, delay) { return (this.fx || (this.fx = new SVG.FX(this))).animate(o, ease, delay) }
javascript
{ "resource": "" }
q52603
train
function(a, v, relative) { // apply attributes individually if (typeof a == 'object') { for (var key in a) this.attr(key, a[key]) } else { // the MorphObj takes care about the right function used this.add(a, new SVG.MorphObj(null, v), 'attrs') } return this }
javascript
{ "resource": "" }
q52604
train
function(box) { var b = new c() // merge boxes b.x = Math.min(this.x, box.x) b.y = Math.min(this.y, box.y) b.width = Math.max(this.x + this.width, box.x + box.width) - b.x b.height = Math.max(this.y + this.height, box.y + box.height) - b.y return fullBox(b) }
javascript
{ "resource": "" }
q52605
train
function() { // find delta transform points var px = deltaTransformPoint(this, 0, 1) , py = deltaTransformPoint(this, 1, 0) , skewX = 180 / Math.PI * Math.atan2(px.y, px.x) - 90 return { // translation x: this.e , y: this.f , transformedX:(this.e * Math.cos(skewX * Math.PI / 180) + this.f * Math.sin(skewX * Math.PI / 180)) / Math.sqrt(this.a * this.a + this.b * this.b) , transformedY:(this.f * Math.cos(skewX * Math.PI / 180) + this.e * Math.sin(-skewX * Math.PI / 180)) / Math.sqrt(this.c * this.c + this.d * this.d) // skew , skewX: -skewX , skewY: 180 / Math.PI * Math.atan2(py.y, py.x) // scale , scaleX: Math.sqrt(this.a * this.a + this.b * this.b) , scaleY: Math.sqrt(this.c * this.c + this.d * this.d) // rotation , rotation: skewX , a: this.a , b: this.b , c: this.c , d: this.d , e: this.e , f: this.f , matrix: new SVG.Matrix(this) } }
javascript
{ "resource": "" }
q52606
train
function(a, v, n) { // act as full getter if (a == null) { // get an object of attributes a = {} v = this.node.attributes for (n = v.length - 1; n >= 0; n--) a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue) ? parseFloat(v[n].nodeValue) : v[n].nodeValue return a } else if (typeof a == 'object') { // apply every attribute individually if an object is passed for (v in a) this.attr(v, a[v]) } else if (v === null) { // remove value this.node.removeAttribute(a) } else if (v == null) { // act as a getter if the first and only argument is not an object v = this.node.getAttribute(a) return v == null ? SVG.defaults.attrs[a] : SVG.regex.isNumber.test(v) ? parseFloat(v) : v } else { // BUG FIX: some browsers will render a stroke if a color is given even though stroke width is 0 if (a == 'stroke-width') this.attr('stroke', parseFloat(v) > 0 ? this._stroke : null) else if (a == 'stroke') this._stroke = v // convert image fill and stroke to patterns if (a == 'fill' || a == 'stroke') { if (SVG.regex.isImage.test(v)) v = this.doc().defs().image(v, 0, 0) if (v instanceof SVG.Image) v = this.doc().defs().pattern(0, 0, function() { this.add(v) }) } // ensure correct numeric values (also accepts NaN and Infinity) if (typeof v === 'number') v = new SVG.Number(v) // ensure full hex color else if (SVG.Color.isColor(v)) v = new SVG.Color(v) // parse array values else if (Array.isArray(v)) v = new SVG.Array(v) // store parametric transformation values locally else if (v instanceof SVG.Matrix && v.param) this.param = v.param // if the passed attribute is leading... if (a == 'leading') { // ... call the leading method instead if (this.leading) this.leading(v) } else { // set given attribute on node typeof n === 'string' ? this.node.setAttributeNS(n, a, v.toString()) : this.node.setAttribute(a, v.toString()) } // rebuild if required if (this.rebuild && (a == 'font-size' || a == 'x')) this.rebuild(a, v) } return this }
javascript
{ "resource": "" }
q52607
train
function() { var matrix = (this.attr('transform') || '') // split transformations .split(/\)\s*/).slice(0,-1).map(function(str){ // generate key => value pairs var kv = str.trim().split('(') return [kv[0], kv[1].split(SVG.regex.matrixElements).map(function(str){ return parseFloat(str) })] }) // calculate every transformation into one matrix .reduce(function(matrix, transform){ if(transform[0] == 'matrix') return matrix.multiply(arrayToMatrix(transform[1])) return matrix[transform[0]].apply(matrix, transform[1]) }, new SVG.Matrix()) return matrix }
javascript
{ "resource": "" }
q52608
train
function(parent) { if(this == parent) return this var ctm = this.screenCTM() var temp = parent.rect(1,1) var pCtm = temp.screenCTM().inverse() temp.remove() this.addTo(parent).untransform().transform(pCtm.multiply(ctm)) return this }
javascript
{ "resource": "" }
q52609
train
function(s, v) { if (arguments.length == 0) { // get full style return this.node.style.cssText || '' } else if (arguments.length < 2) { // apply every style individually if an object is passed if (typeof s == 'object') { for (v in s) this.style(v, s[v]) } else if (SVG.regex.isCss.test(s)) { // parse css string s = s.split(';') // apply every definition individually for (var i = 0; i < s.length; i++) { v = s[i].split(':') this.style(v[0].replace(/\s+/g, ''), v[1]) } } else { // act as a getter if the first and only argument is not an object return this.node.style[camelCase(s)] } } else { this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v } return this }
javascript
{ "resource": "" }
q52610
train
function() { return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) { return SVG.adopt(node) }) }
javascript
{ "resource": "" }
q52611
train
function() { // unmask all targets for (var i = this.targets.length - 1; i >= 0; i--) if (this.targets[i]) this.targets[i].unmask() this.targets = [] // remove mask from parent this.parent().removeElement(this) return this }
javascript
{ "resource": "" }
q52612
train
function(element) { // use given mask or create a new one this.masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element) // store reverence on self in mask this.masker.targets.push(this) // apply mask return this.attr('mask', 'url("#' + this.masker.attr('id') + '")') }
javascript
{ "resource": "" }
q52613
train
function() { // unclip all targets for (var i = this.targets.length - 1; i >= 0; i--) if (this.targets[i]) this.targets[i].unclip() this.targets = [] // remove clipPath from parent this.parent().removeElement(this) return this }
javascript
{ "resource": "" }
q52614
train
function(element) { // use given clip or create a new one this.clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element) // store reverence on self in mask this.clipper.targets.push(this) // apply mask return this.attr('clip-path', 'url("#' + this.clipper.attr('id') + '")') }
javascript
{ "resource": "" }
q52615
train
function(offset, color, opacity) { return this.put(new SVG.Stop).update(offset, color, opacity) }
javascript
{ "resource": "" }
q52616
train
function(o) { if (typeof o == 'number' || o instanceof SVG.Number) { o = { offset: arguments[0] , color: arguments[1] , opacity: arguments[2] } } // set attributes if (o.opacity != null) this.attr('stop-opacity', o.opacity) if (o.color != null) this.attr('stop-color', o.color) if (o.offset != null) this.attr('offset', new SVG.Number(o.offset)) return this }
javascript
{ "resource": "" }
q52617
train
function(text) { // remove contents while (this.node.hasChildNodes()) this.node.removeChild(this.node.lastChild) // create text node this.node.appendChild(document.createTextNode(text)) return this }
javascript
{ "resource": "" }
q52618
train
function(size) { return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0) }
javascript
{ "resource": "" }
q52619
train
function(x1, y1, x2, y2) { return this.put(new SVG.Line).plot(x1, y1, x2, y2) }
javascript
{ "resource": "" }
q52620
train
function(source, width, height) { return this.put(new SVG.Image).load(source).size(width || 0, height || width || 0) }
javascript
{ "resource": "" }
q52621
train
function(text) { if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '') typeof text === 'function' ? text.call(this, this) : this.plain(text) return this }
javascript
{ "resource": "" }
q52622
train
function(d) { // create textPath element var path = new SVG.TextPath , track = this.doc().defs().path(d) // move lines to textpath while (this.node.hasChildNodes()) path.node.appendChild(this.node.firstChild) // add textPath element as child node this.node.appendChild(path.node) // link textPath to path and add content path.attr('href', '#' + track, SVG.xlink) return this }
javascript
{ "resource": "" }
q52623
train
function(url) { var link = new SVG.A if (typeof url == 'function') url.call(link, link) else link.to(url) return this.parent().put(link).put(this) }
javascript
{ "resource": "" }
q52624
train
function(marker, width, height, block) { var attr = ['marker'] // Build attribute name if (marker != 'all') attr.push(marker) attr = attr.join('-') // Set marker attribute marker = arguments[1] instanceof SVG.Marker ? arguments[1] : this.doc().marker(width, height, block) return this.attr(attr, marker) }
javascript
{ "resource": "" }
q52625
train
function(d, cx, cy) { return this.transform({ rotation: d, cx: cx, cy: cy }) }
javascript
{ "resource": "" }
q52626
train
function(x, y) { var type = (this._target || this).type; return type == 'radial' || type == 'circle' ? this.attr('r', new SVG.Number(x)) : this.rx(x).ry(y == null ? x : y) }
javascript
{ "resource": "" }
q52627
train
function() { var i, il, elements = [].slice.call(arguments) for (i = 0, il = elements.length; i < il; i++) this.members.push(elements[i]) return this }
javascript
{ "resource": "" }
q52628
train
function(a, v, r) { if (typeof a == 'object') { for (v in a) this.data(v, a[v]) } else if (arguments.length < 2) { try { return JSON.parse(this.attr('data-' + a)) } catch(e) { return this.attr('data-' + a) } } else { this.attr( 'data-' + a , v === null ? null : r === true || typeof v === 'string' || typeof v === 'number' ? v : JSON.stringify(v) ) } return this }
javascript
{ "resource": "" }
q52629
train
function(k, v) { // remember every item in an object individually if (typeof arguments[0] == 'object') for (var v in k) this.remember(v, k[v]) // retrieve memory else if (arguments.length == 1) return this.memory()[k] // store memory else this.memory()[k] = v return this }
javascript
{ "resource": "" }
q52630
camelCase
train
function camelCase(s) { return s.toLowerCase().replace(/-(.)/g, function(m, g) { return g.toUpperCase() }) }
javascript
{ "resource": "" }
q52631
fullHex
train
function fullHex(hex) { return hex.length == 4 ? [ '#', hex.substring(1, 2), hex.substring(1, 2) , hex.substring(2, 3), hex.substring(2, 3) , hex.substring(3, 4), hex.substring(3, 4) ].join('') : hex }
javascript
{ "resource": "" }
q52632
proportionalSize
train
function proportionalSize(box, width, height) { if (height == null) height = box.height / box.width * width else if (width == null) width = box.width / box.height * height return { width: width , height: height } }
javascript
{ "resource": "" }
q52633
deltaTransformPoint
train
function deltaTransformPoint(matrix, x, y) { return { x: x * matrix.a + y * matrix.c + 0 , y: x * matrix.b + y * matrix.d + 0 } }
javascript
{ "resource": "" }
q52634
parseMatrix
train
function parseMatrix(matrix) { if (!(matrix instanceof SVG.Matrix)) matrix = new SVG.Matrix(matrix) return matrix }
javascript
{ "resource": "" }
q52635
ensureCentre
train
function ensureCentre(o, target) { o.cx = o.cx == null ? target.bbox().cx : o.cx o.cy = o.cy == null ? target.bbox().cy : o.cy }
javascript
{ "resource": "" }
q52636
stringToMatrix
train
function stringToMatrix(source) { // remove matrix wrapper and split to individual numbers source = source .replace(SVG.regex.whitespace, '') .replace(SVG.regex.matrix, '') .split(SVG.regex.matrixElements) // convert string values to floats and convert to a matrix-formatted object return arrayToMatrix( SVG.utils.map(source, function(n) { return parseFloat(n) }) ) }
javascript
{ "resource": "" }
q52637
at
train
function at(o, pos) { // number recalculation (don't bother converting to SVG.Number for performance reasons) return typeof o.from == 'number' ? o.from + (o.to - o.from) * pos : // instance recalculation o instanceof SVG.Color || o instanceof SVG.Number || o instanceof SVG.Matrix ? o.at(pos) : // for all other values wait until pos has reached 1 to return the final value pos < 1 ? o.from : o.to }
javascript
{ "resource": "" }
q52638
assignNewId
train
function assignNewId(node) { // do the same for SVG child nodes as well for (var i = node.childNodes.length - 1; i >= 0; i--) if (node.childNodes[i] instanceof SVGElement) assignNewId(node.childNodes[i]) return SVG.adopt(node).id(SVG.eid(node.nodeName)) }
javascript
{ "resource": "" }
q52639
fullBox
train
function fullBox(b) { if (b.x == null) { b.x = 0 b.y = 0 b.width = 0 b.height = 0 } b.w = b.width b.h = b.height b.x2 = b.x + b.width b.y2 = b.y + b.height b.cx = b.x + b.width / 2 b.cy = b.y + b.height / 2 return b }
javascript
{ "resource": "" }
q52640
idFromReference
train
function idFromReference(url) { var m = url.toString().match(SVG.regex.reference) if (m) return m[1] }
javascript
{ "resource": "" }
q52641
serializeProperty
train
function serializeProperty(metadata, prop) { if (!metadata || metadata.excludeToJson === true) { return; } if (metadata.customConverter) { return metadata.customConverter.toJson(prop); } if (!metadata.clazz) { return prop; } if (utils_1.isArrayOrArrayClass(prop)) { return prop.map(function (propItem) { return serialize(propItem); }); } return serialize(prop); }
javascript
{ "resource": "" }
q52642
goTo
train
function goTo(hash,changehash){ win.unbind('hashchange', hashchange); hash = hash.replace(/!\//,''); win.stop().scrollTo(hash,duration,{ easing:easing, axis:'y' }); if(changehash !== false){ var l = location; location.href = (l.protocol+'//'+l.host+l.pathname+'#!/'+hash.substr(1)); } win.bind('hashchange', hashchange); }
javascript
{ "resource": "" }
q52643
activateNav
train
function activateNav(pos){ var offset = 100, current, next, parent, isSub, hasSub; win.unbind('hashchange', hashchange); for(var i=sectionscount;i>0;i--){ if(sections[i-1].pos <= pos+offset){ navanchors.removeClass('current'); current = navanchors.eq(i-1); current.addClass('current'); parent = current.parent().parent(); next = current.next(); hasSub = next.is('ul'); isSub = !parent.is('#documenter_nav'); nav.find('ol:visible').not(parent).slideUp('fast'); if(isSub){ parent.prev().addClass('current'); parent.stop().slideDown('fast'); }else if(hasSub){ next.stop().slideDown('fast'); } win.bind('hashchange', hashchange); break; }; } }
javascript
{ "resource": "" }
q52644
train
function (param, value) { var jvmObject; if (arguments[0] instanceof org.apache.spark.ml.param.ParamPair) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.ml.param.ParamPair(param, value); } this.logger = Logger.getLogger("ParamPair_js"); JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52645
train
function(rows,nRows,nCols) { this.logger = Logger.getLogger("RowMatrix_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.linalg.distributed.RowMatrix) { jvmObject = arguments[0]; } else if (arguments.length === 3) { jvmObject = new org.apache.spark.mllib.linalg.distributed.RowMatrix(Utils.unwrapObject(rows).rdd(),nRows,nCols); } else { jvmObject = new org.apache.spark.mllib.linalg.distributed.RowMatrix(Utils.unwrapObject(rows).rdd()); } DistributedMatrix.call(this, jvmObject); }
javascript
{ "resource": "" }
q52646
train
function () { this.logger = Logger.getLogger("Gradient_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.optimization.Gradient) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.mllib.optimization.Gradient(); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52647
train
function (clusterCenters) { var jvmObject; if (clusterCenters instanceof org.apache.spark.mllib.clustering.KMeansModel) { jvmObject = clusterCenters; } else { jvmObject = new org.apache.spark.mllib.clustering.KMeansModel(clusterCenters); } this.logger = Logger.getLogger("KMeansModel_js"); JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52648
train
function () { var jvmObject; if (arguments.length == 1) { jvmObject = arguments[0]; } else { var value = arguments[0]; this._accumulableParam = arguments[1]; if (arguments[1] instanceof FloatAccumulatorParam) { value = parseFloat(value); } else if (arguments[1] instanceof IntAccumulatorParam) { value = new java.lang.Integer(parseInt(value)); // we need to create a Integer or we will get a java.lang.Double } var accumulableParam_uw = Utils.unwrapObject(arguments[1]); jvmObject = new org.apache.spark.Accumulable(value, accumulableParam_uw); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52649
train
function (jvmObject) { this.logger = Logger.getLogger("mllib_recommendation_ALS_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.recommendation.ALS(); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52650
train
function (predictionAndObservations) { this.logger = Logger.getLogger("RegressionMetrics_js"); var jvmObject; if (predictionAndObservations instanceof org.apache.spark.mllib.evaluation.RegressionMetrics) { jvmObject = predictionAndObservations; } else { jvmObject = new org.apache.spark.mllib.evaluation.RegressionMetrics(Utils.unwrapObject(predictionAndObservations).rdd()); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52651
train
function (topNode, algo) { var jvmObject; if (topNode instanceof org.apache.spark.mllib.tree.model.DecisionTreeModel) { jvmObject = topNode; }/* if (topeNode instanceof Node { jvmObject = new org.apache.spark.mllib.tree.model.DecisionTreeModel(topNode,algo); } */ else { throw "DecisionTreeModel invalid constructor parameter" } this.logger = Logger.getLogger("DecisionTreeModel_js"); JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52652
train
function (jvmObject) { this.logger = Logger.getLogger("mllib_feature_Word2Vec_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.feature.Word2Vec(); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52653
train
function (boundaries, predictions, isotonic) { this.logger = Logger.getLogger("IsotonicRegressionModel_js"); var jvmObject; if (boundaries instanceof org.apache.spark.mllib.regression.IsotonicRegressionModel) { jvmObject = boundaries; } else { jvmObject = new org.apache.spark.mllib.regression.IsotonicRegressionModel(boundaries, predictions, isotonic); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52654
train
function () { this.logger = Logger.getLogger("MatrixFactorizationModel_js"); var jvmObject = arguments[0]; if (arguments.length > 1) { var userFeatures = Utils.unwrapObject(arguments[1]); var productFeatures = Utils.unwrapObject(arguments[2]); jvmObject = new org.apache.spark.mllib.recommendation.MatrixFactorizationModel(arguments[0], userFeatures, productFeatures); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52655
handleArguments
train
function handleArguments(args) { return new Promise(function(resolve, reject) { var requires = []; var promises = []; // check for Promises in args if (args && args instanceof Array) { args.some(function (arg, i) { if ((arg.value === null || typeof(arg.value) == 'undefined') && arg.optional) { return true; } if (arg.value && Array.isArray(arg.value) && arg.optional && arg.value.length == 0) { return true; } if (arg.type == 'string') { var s = '"' + arg.value.replace(/"/g, '\\\"') + '"'; promises.push(Promise.resolve(s)); } else if (arg.type == 'lambda') { promises.push(serializeLambda(arg.value)); } else if (arg.type == 'lambdaArgs') { promises.push(new Promise(function(resolve, reject) { handleArrayArgument(arg.value).then(function (result) { resolve(result); }).catch(reject); })); } else if (arg.type == 'map') { promises.push(Promise.resolve(JSON.stringify(arg.value))); } else if (arg.type == 'promise') { promises.push(new Promise(function(resolve, reject) { arg.value.then(function(val) { if (typeof(val) == 'string') { if (isNaN(val)) { // a string var s = '"' + val.replace(/"/g, '\\\"') + '"'; resolve(s); } else { resolve(parseFloat(val)); } } else { resolve(val); } }); })); } else if (arg.value.refIdP) { promises.push(arg.value.refIdP); } else if (arg.type == 'List') { promises.push(Promise.resolve(arg.value.toString())); } else if (arg.type == 'array') { // simple array argument promises.push(handleArrayArgument(arg.value)); } else if (arg.type == '_eclairSerialize') { if (arg.value._eclairSerialize == 'staticProperty') { var val = arg.value.ref.name + '.' + arg.value.value; promises.push(Promise.resolve(val)); requires.push({name: arg.value.ref.name, moduleLocation: arg.value.ref.moduleLocation}); } } else if (Array.isArray(arg.value)) { // TODO: should we try to wrap the array if it isn't? promises.push(new Promise(function (resolve, reject) { handleArguments(arg.value).then(function (result) { if (result.requires.length > 0) { result.requires.forEach(function (r) { requires.push(r) }); } resolve('[' + result.args + ']'); }).catch(reject); })); } else if (arg.type == '_eclairForceFloat') { var val = arg.value.value; if (val.toString().indexOf('.') === -1) { val = val.toFixed(1); } promises.push(Promise.resolve(val)); } else if (arg.type == '_eclairLocal') { promises.push(Promise.resolve(arg.value._generateRemote().refIdP)); } else if (arg.type == 'sparkclassref') { // we have a spark class reference, so return its name promises.push(Promise.resolve(arg.value.name)); // add the class to the requires list requires.push({name: arg.value.name, moduleLocation: arg.value.moduleLocation}); } else { promises.push(Promise.resolve(arg.value)); } return false; }); } Promise.all(promises).then(function(finalArgs) { resolve({args: finalArgs, requires: requires}); //resolve(finalArgs); }).catch(function(e) { console.log(e); reject(e) }); }); }
javascript
{ "resource": "" }
q52656
train
function(jvmObject) { this.logger = Logger.getLogger("BisectingKMeans_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.clustering.BisectingKMeans(); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52657
train
function (jvmObject) { this.logger = Logger.getLogger("ml_param_ParamMap_js"); if (!jvmObject) { jvmObject = new org.apache.spark.ml.param.ParamMap(); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52658
run
train
function run(sc) { var LogisticRegressionModel = require('eclairjs/mllib/classification').LogisticRegressionModel; var LabeledPoint = require("eclairjs/mllib/regression/LabeledPoint"); var Vectors = require("eclairjs/mllib/linalg/Vectors"); var BinaryClassificationMetrics = require("eclairjs/mllib/evaluation/BinaryClassificationMetrics"); var LBFGS = require("eclairjs/mllib/optimization/LBFGS"); var LogisticGradient = require("eclairjs/mllib/optimization/LogisticGradient"); var SquaredL2Updater = require("eclairjs/mllib/optimization/SquaredL2Updater"); var Tuple2 = require('eclairjs/Tuple2'); var path = ((typeof args !== "undefined") && (args.length > 1)) ? args[1] : "examples/data/mllib/sample_libsvm_data.txt"; var data = MLUtils.loadLibSVMFile(sc, path); var ret = {}; var numFeatures = data.take(1)[0].getFeatures().size(); // Split initial RDD into two... [60% training data, 40% testing data]. var trainingInit = data.sample(false, 0.6, 11); var test = data.subtract(trainingInit); // Append 1 into the training data as intercept. var training = data.map(function (lp, Tuple2, MLUtils) { /* NOTE: MLUtils must be defined in the Global scope, or in this LAMBDA function. */ return new Tuple2(lp.getLabel(), MLUtils.appendBias(lp.getFeatures())); }, [Tuple2, MLUtils]); training.cache(); // Run training algorithm to build the model. var numCorrections = 10; var convergenceTol = 0.0001; var maxNumIterations = 20; var regParam = 0.1; var w = []; for (var i = 0; i < numFeatures + 1; i++) { w.push(0.0); } var initialWeightsWithIntercept = Vectors.dense(w); var result = LBFGS.runLBFGS( // training.rdd(), training, new LogisticGradient(), new SquaredL2Updater(), numCorrections, convergenceTol, maxNumIterations, regParam, initialWeightsWithIntercept); var weightsWithIntercept = result._1(); ret.loss = result._2(); var arrayWeightsWithIntercept = weightsWithIntercept.toArray(); var copyOfWeightsWithIntercept = []; for (var ii = 0; ii < arrayWeightsWithIntercept.length - 1; ii++) { copyOfWeightsWithIntercept.push(arrayWeightsWithIntercept[ii]); } var model = new LogisticRegressionModel(Vectors.dense(copyOfWeightsWithIntercept), copyOfWeightsWithIntercept.length); // Clear the default threshold. model.clearThreshold(); var scoreAndLabels = test.map(function (lp, model, Tuple2) { return new Tuple2(model.predict(lp.getFeatures()), lp.getLabel()); }, [model, Tuple2]); // Get evaluation metrics. var metrics = new BinaryClassificationMetrics(scoreAndLabels); ret.auROC = metrics.areaUnderROC(); return ret; }
javascript
{ "resource": "" }
q52659
train
function(scoreAndLabels,numBins) { var jvmObject; if (scoreAndLabels instanceof org.apache.spark.mllib.evaluation.BinaryClassificationMetrics) { jvmObject = scoreAndLabels; } else { jvmObject = new org.apache.spark.mllib.evaluation.BinaryClassificationMetrics(Utils.unwrapObject(scoreAndLabels).rdd(),numBins); } this.logger = Logger.getLogger("BinaryClassificationMetrics_js"); JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52660
train
function (algo, trees, treeWeights) { this.logger = Logger.getLogger("GradientBoostedTreesModel_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.tree.model.GradientBoostedTreesModel) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.mllib.tree.model.GradientBoostedTreesModel(Utils.unwrapObject(arguments[0]), Utils.unwrapObject(trees), treeWeights ); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52661
train
function (sqlContext, logical) { var jvmObject; if (arguments[0] instanceof org.apache.spark.sql.execution.QueryExecution) { var jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.sql.execution.QueryExecution(Utils.unwrapObject(sqlContext), Utils.unwrapObject(logical)); } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52662
run
train
function run(sc) { var lines = sc.textFile(directory); var points = lines.map(function (line, LabeledPoint, Vectors) { var parts = line.split(","); var y = parseFloat(parts[0]); var tok = parts[1].split(" "); var x = []; for (var i = 0; i < tok.length; ++i) { x[i] = parseFloat(tok[i]); } return new LabeledPoint(y, Vectors.dense(x)); }, [LabeledPoint, Vectors]).cache(); // Another way to configure LogisticRegression // // LogisticRegressionWithSGD lr = new LogisticRegressionWithSGD(); // lr.optimizer().setNumIterations(iterations) // .setStepSize(stepSize) // .setMiniBatchFraction(1.0); // lr.setIntercept(true); // var model = lr.train(points.rdd()); var model = LogisticRegressionWithSGD.train(points, iterations, stepSize); return model.weights(); }
javascript
{ "resource": "" }
q52663
train
function (strategy) { this.logger = Logger.getLogger("DecisionTree_js"); var jvmObject; if (strategy instanceof Strategy) { jvmObject = new org.apache.spark.mllib.tree.DecisionTree(Utils.unwrapObject(strategy)); } else if (strategy instanceof rg.apache.spark.mllib.tree.DecisionTree) { jvmObject = strategy; } else { throw "DecisionTree invalid constructor parameter" } JavaWrapper.call(this, jvmObject); }
javascript
{ "resource": "" }
q52664
EclairJS
train
function EclairJS(sessionName) { if (sessionName && EJSCache[sessionName]) { console.log("got hit") return EJSCache[sessionName].ejs; } else { var server = new Server(); var kernelP = server.getKernelPromise(); var instance = { Accumulable: require('./Accumulable.js')(kernelP), AccumulableParam: require('./AccumulableParam.js')(kernelP), List: require('./List.js')(kernelP), Tuple: require('./Tuple.js')(kernelP), Tuple2: require('./Tuple2.js')(kernelP), Tuple3: require('./Tuple3.js')(kernelP), Tuple4: require('./Tuple4.js')(kernelP), SparkConf: require('./SparkConf.js')(kernelP), SparkContext: require('./SparkContext.js')(kernelP, server), ml: require('./ml/module.js')(kernelP), mllib: require('./mllib/module.js')(kernelP), rdd: require('./rdd/module.js')(kernelP), sql: require('./sql/module.js')(kernelP, server), storage: require('./storage/module.js')(kernelP), streaming: require('./streaming/module.js')(kernelP), forceFloat: Utils.forceFloat, addJar: function (jar) { return Utils.addSparkJar(kernelP, jar); }, getUtils: function () { return Utils; }, executeMethod: function (args) { return Utils.executeMethod(kernelP, args); }, addModule: function (module) { server.addModule(module); } }; if (sessionName) { EJSCache[sessionName] = {ejs: instance, server: server}; } return instance; } }
javascript
{ "resource": "" }
q52665
componentWillReceiveProps
train
function componentWillReceiveProps(nextProps) { var children = this.props.children; var index = children.findIndex(function (c) { return c.props.value === nextProps.value && !c.props.disabled; }); if (index !== -1 && index !== this.state.checkedIndex) { this.setState({ checkedIndex: index }); } }
javascript
{ "resource": "" }
q52666
executeCommand
train
function executeCommand(sid, command, ain, options, path) { path = path || '/webservices/homeautoswitch.lua?0=0'; if (sid) path += '&sid=' + sid; if (command) path += '&switchcmd=' + command; if (ain) path += '&ain=' + ain; return httpRequest(path, {}, options); }
javascript
{ "resource": "" }
q52667
sequence
train
function sequence(promises) { var result = Promise.resolve(); promises.forEach(function(promise,i) { result = result.then(promise); }); return result; }
javascript
{ "resource": "" }
q52668
switches
train
function switches() { return fritz.getSwitchList().then(function(switches) { console.log("Switches: " + switches + "\n"); return sequence(switches.map(function(sw) { return function() { return sequence([ function() { return fritz.getSwitchName(sw).then(function(name) { console.log("[" + sw + "] " + name); }); }, function() { return fritz.getSwitchPresence(sw).then(function(presence) { console.log("[" + sw + "] presence: " + presence); }); }, function() { return fritz.getSwitchState(sw).then(function(state) { console.log("[" + sw + "] state: " + state); }); }, function() { return fritz.getTemperature(sw).then(function(temp) { temp = isNaN(temp) ? '-' : temp + "°C"; console.log("[" + sw + "] temp: " + temp + "\n"); }); } ]); }; })); }); }
javascript
{ "resource": "" }
q52669
train
function() { return fritz.getDevice(thermostat).then(function(device) { console.log("[" + thermostat + "] " + device.name); }); }
javascript
{ "resource": "" }
q52670
debug
train
function debug() { return fritz.getDeviceList().then(function(devices) { console.log("Raw devices\n"); console.log(devices); }); }
javascript
{ "resource": "" }
q52671
train
function(params, callback) { var t = this; if (typeof(params) !== 'string' || params.length < 1) { callback("Autocomplete paramter must be a nonzero string"); } // Forward to the completion mechanism if it can be completed if (params.substr(-1).match(/([0-9])|([a-z])|([A-Z])|([_])/)) { t.repl.complete(params, callback); } else { // Return a no-op autocomplete callback(null, [[],'']); } }
javascript
{ "resource": "" }
q52672
train
function(params, callback) { var t = this; if (params === '.break' && t.shellCmd) { t.shellCmd.kill(); } if (NEW_REPL) { t.stream.emit('data', params + "\n"); } else { t.stream.emit('data', params); } return callback(null); }
javascript
{ "resource": "" }
q52673
train
function(command) { var t = this; t.shellCmd = ChildProcess.exec(command, function(err, stdout, stderr) { if (err) { var outstr = 'exit'; if (err.code) { outstr += ' (' + err.code + ')'; } if (err.signal) { outstr += ' ' + err.signal; } t._output(outstr); return null; } if (stdout.length) { t._output(stdout); } if (stderr.length) { t._output(stderr); } t.shellCmd = null; t._output(CONSOLE_PROMPT); }); return null; }
javascript
{ "resource": "" }
q52674
train
function(probe){ var t = this; t.probe = probe; events.EventEmitter.call(t); if (t.setEncoding) { t.setEncoding('utf8'); } }
javascript
{ "resource": "" }
q52675
train
function(attrs, callback) { var t = this; // Value is the only thing to set if (typeof attrs.value === 'undefined') { return callback({code:'NO_VALUE'}); } // Set the model elements. These cause change events to fire if (t.isModel) { t.value.set(attrs.value); } else { // Set the variable directly var jsonValue = JSON.stringify(attrs.value); t._evaluate(t.key + ' = ' + jsonValue); t.set('value', attrs.value); } return callback(); }
javascript
{ "resource": "" }
q52676
train
function() { var t = this; if (t.isModel) { t.value.off('change', t.poll, t); } else { PollingProbe.prototype.release.apply(t, arguments); } }
javascript
{ "resource": "" }
q52677
train
function(expression, depth){ var t = this; // Determine a default depth depth = typeof depth === 'undefined' ? DEFAULT_DEPTH : depth; // Get the raw value var value = t._evaluate(expression); // Return the depth limited results return Monitor.deepCopy(value, depth); }
javascript
{ "resource": "" }
q52678
train
function() { var t = this, newValue = t.eval_control(t.key, t.depth); // Set the new value if it has changed from the current value if (!_.isEqual(newValue, t.get('value'))) { t.set({value: newValue}); } }
javascript
{ "resource": "" }
q52679
train
function() { var t = this, hostName = t.get('hostName'), hostPort = t.get('hostPort'), url = t.get('url'); // Build the URL if not specified if (!url) { url = t.attributes.url = 'http://' + hostName + ':' + hostPort; t.set('url', url); } // Connect with this url var opts = { // 'transports': ['websocket', 'xhr-polling', 'jsonp-polling'], 'force new connection': true, // Don't re-use existing connections 'reconnect': false // Don't let socket.io reconnect. // Reconnects are performed by the Router. }; var socket = SocketIO.connect(url, opts); t.set({socket:socket}).bindConnectionEvents(); }
javascript
{ "resource": "" }
q52680
train
function(callback) { var t = this; callback = callback || function(){}; var onPong = function() { t.off('pong', onPong); callback(); }; t.on('pong', onPong); t.emit('connection:ping'); }
javascript
{ "resource": "" }
q52681
train
function(reason) { var t = this, socket = t.get('socket'); t.connecting = false; t.connected = false; // Only disconnect once. // This method can be called many times during a disconnect (manually, // by socketIO disconnect, and/or by the underlying socket disconnect). if (t.socketEvents) { t.removeAllEvents(); socket.disconnect(); t.trigger('disconnect', reason); log.info(t.logId + 'disconnect', reason); } }
javascript
{ "resource": "" }
q52682
train
function(hostName) { var t = this, testHost = hostName.toLowerCase(), myHostName = t.get('hostName'), remoteHostName = t.get('remoteHostName'); myHostName = myHostName && myHostName.toLowerCase(); remoteHostName = remoteHostName && remoteHostName.toLowerCase(); return (testHost === myHostName || testHost === remoteHostName); }
javascript
{ "resource": "" }
q52683
train
function() { var t = this, socket = t.get('socket'); log.info(t.logId + 'emit', Monitor.deepCopy(arguments, 5)); socket.emit.apply(socket, arguments); }
javascript
{ "resource": "" }
q52684
train
function(eventName, handler) { var t = this, socket = t.get('socket'); t.socketEvents = t.socketEvents || {}; if (t.socketEvents[eventName]) { throw new Error('Event already connected: ' + eventName); } socket.on(eventName, handler); t.socketEvents[eventName] = handler; return t; }
javascript
{ "resource": "" }
q52685
train
function(eventName) { var t = this, socket = t.get('socket'); if (t.socketEvents && t.socketEvents[eventName]) { socket.removeListener(eventName, t.socketEvents[eventName]); delete t.socketEvents[eventName]; } return t; }
javascript
{ "resource": "" }
q52686
train
function() { var t = this, socket = t.get('socket'); for (var event in t.socketEvents) { socket.removeListener(event, t.socketEvents[event]); } t.socketEvents = null; return t; }
javascript
{ "resource": "" }
q52687
train
function() { var t = this, socket = t.get('socket'); if (t.socketEvents) {throw new Error('Already connected');} t.socketEvents = {}; // key = event name, data = handler // Failure events t.addEvent('connect_failed', function(){ t.trigger('error', 'connect failed'); t.disconnect('connect failed'); }); t.addEvent('disconnect', function(){t.disconnect('remote_disconnect');}); t.addEvent('error', function(reason){ t.trigger('error', reason); t.disconnect('connect error'); }); // Inbound probe events t.addEvent('probe:connect', t.probeConnect.bind(t)); t.addEvent('probe:disconnect', t.probeDisconnect.bind(t)); t.addEvent('probe:control', t.probeControl.bind(t)); // Connection events t.addEvent('connection:ping', function(){socket.emit('connection:pong');}); t.addEvent('connection:pong', function(){t.trigger('pong');}); // Connected once remote info is known t.addEvent('connection:info', function (info) { t.set({ remoteHostName: info.hostName, remoteAppName: info.appName, remoteAppInstance: info.appInstance, remotePID: info.pid, remoteProbeClasses: info.probeClasses, remoteGateway: info.gateway, remoteFirewall: info.firewall }); t.connecting = false; t.connected = true; t.trigger('connect'); }); // Determine the process id var pid = typeof process === 'undefined' ? 1 : process.pid; // Determine the app instance var appInstance = '' + (typeof process === 'undefined' ? pid : process.env.NODE_APP_INSTANCE || pid); // Exchange connection information socket.emit('connection:info', { hostName:Monitor.getRouter().getHostName(), appName:Config.Monitor.appName, appInstance: appInstance, pid: pid, probeClasses: _.keys(Probe.classes), gateway:t.get('gateway'), firewall:t.get('firewall') }); }
javascript
{ "resource": "" }
q52688
train
function(monitorJSON, callback) { callback = callback || function(){}; var t = this, errorText = '', router = Monitor.getRouter(), gateway = t.get('gateway'), startTime = Date.now(), firewall = t.get('firewall'), logCtxt = _.extend({}, monitorJSON); // Don't allow inbound requests if this connection is firewalled if (firewall) { errorText = 'firewalled'; log.error('probeConnect', errorText, logCtxt); return callback(errorText); } // Determine the connection to use (or internal) router.determineConnection(monitorJSON, gateway, function(err, connection) { if (err) {return callback(err);} if (connection && !gateway) {return callback('Not a gateway');} // Function to run upon connection (internal or external) var onConnect = function(error, probe) { if (error) { log.error(t.logId + 'probeConnect', error, logCtxt); return callback(error); } // Get probe info var probeId = probe.get('id'); logCtxt.id = probeId; // Check for a duplicate proxy for this probeId. This happens when // two connect requests are made before the first one completes. var monitorProxy = t.incomingMonitorsById[probeId]; if (monitorProxy != null) { probe.refCount--; logCtxt.dupDetected = true; logCtxt.refCount = probe.refCount; log.info(t.logId + 'probeConnected', logCtxt); return callback(null, monitorProxy.probe.toJSON()); } // Connect the montior proxy monitorProxy = new Monitor(monitorJSON); monitorProxy.set('probeId', probeId); t.incomingMonitorsById[probeId] = monitorProxy; monitorProxy.probe = probe; monitorProxy.probeChange = function(){ try { t.emit('probe:change:' + probeId, probe.changedAttributes()); } catch (e) { log.error('probeChange', e, probe, logCtxt); } }; probe.connectTime = Date.now(); var duration = probe.connectTime - startTime; logCtxt.duration = duration; logCtxt.refCount = probe.refCount; log.info(t.logId + 'probeConnected', logCtxt); stat.time(t.logId + 'probeConnected', duration); callback(null, probe.toJSON()); probe.on('change', monitorProxy.probeChange); // Disconnect the probe on connection disconnect t.on('disconnect', function() { t.probeDisconnect({probeId:probeId}); }); }; // Connect internally or externally if (connection) { router.connectExternal(monitorJSON, connection, onConnect); } else { router.connectInternal(monitorJSON, onConnect); } }); }
javascript
{ "resource": "" }
q52689
train
function(params, callback) { callback = callback || function(){}; var t = this, errorText = '', router = Monitor.getRouter(), probeId = params.probeId, monitorProxy = t.incomingMonitorsById[probeId], firewall = t.get('firewall'), logCtxt = null, probe = null; // Already disconnected if (!monitorProxy || !monitorProxy.probe) { return callback(null); } // Get a good logging context probe = monitorProxy.probe; logCtxt = { probeClass: monitorProxy.get('probeClass'), initParams: monitorProxy.get('initParams'), probeId: probeId }; // Called upon disconnect (internal or external) var onDisconnect = function(error) { if (error) { log.error(t.logId + 'probeDisconnect', error); return callback(error); } var duration = logCtxt.duration = Date.now() - probe.connectTime; probe.off('change', monitorProxy.probeChange); monitorProxy.probe = monitorProxy.probeChange = null; delete t.incomingMonitorsById[probeId]; log.info(t.logId + 'probeDisconnected', logCtxt); stat.time(t.logId + 'probeDisconnected', duration); return callback(null); }; // Disconnect from an internal or external probe if (probe && probe.connection) { router.disconnectExternal(probe.connection, probeId, onDisconnect); } else { router.disconnectInternal(probeId, onDisconnect); } }
javascript
{ "resource": "" }
q52690
train
function(params, callback) { callback = callback || function(){}; var t = this, errorText = '', logId = t.logId + 'probeControl', startTime = Date.now(), router = Monitor.getRouter(), firewall = t.get('firewall'); // Don't allow inbound requests if this connection is firewalled if (firewall) { errorText = 'firewalled'; log.error(logId, errorText); return callback(errorText); } // Called upon return var onReturn = function(error) { if (error) { log.error(logId, error); return callback(error); } else { var duration = Date.now() - startTime; log.info(logId + '.return', {duration:duration, returnArgs: arguments}); stat.time(logId, duration); return callback.apply(null, arguments); } }; // Is this an internal probe? var probe = router.runningProbesById[params.probeId]; if (!probe) { // Is this a remote (proxied) probe? var monitorProxy = t.incomingMonitorsById[params.probeId]; if (!monitorProxy) { errorText = 'Probe id not found: ' + params.probeId; log.error(errorText); return callback(errorText); } // Proxying requires this form vs. callback as last arg. return monitorProxy.control(params.name, params.params, function(err, returnParams) { onReturn(err, returnParams); }); } logId = logId + '.' + probe.probeClass + '.' + params.name; log.info(logId + '.request', {params:params.params, probeId:params.probeId}); return probe.onControl(params.name, params.params, onReturn); }
javascript
{ "resource": "" }
q52691
train
function(name, callback, context) { if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this; this._events || (this._events = {}); var list = this._events[name] || (this._events[name] = []); list.push({callback: callback, context: context, ctx: context || this}); return this; }
javascript
{ "resource": "" }
q52692
train
function(loud) { this.changed = {}; var already = {}; var triggers = []; var current = this._currentAttributes; var changes = this._changes; // Loop through the current queue of potential model changes. for (var i = changes.length - 2; i >= 0; i -= 2) { var key = changes[i], val = changes[i + 1]; if (already[key]) continue; already[key] = true; // Check if the attribute has been modified since the last change, // and update `this.changed` accordingly. If we're inside of a `change` // call, also add a trigger to the list. if (current[key] !== val) { this.changed[key] = val; if (!loud) continue; triggers.push(key, val); current[key] = val; } } if (loud) this._changes = []; // Signals `this.changed` is current to prevent duplicate calls from `this.hasChanged`. this._hasComputed = true; return triggers; }
javascript
{ "resource": "" }
q52693
train
function(models, options) { var model, i, l, existing; var add = [], remove = [], modelMap = {}; var idAttr = this.model.prototype.idAttribute; options = _.extend({add: true, merge: true, remove: true}, options); if (options.parse) models = this.parse(models); // Allow a single model (or no argument) to be passed. if (!_.isArray(models)) models = models ? [models] : []; // Proxy to `add` for this case, no need to iterate... if (options.add && !options.remove) return this.add(models, options); // Determine which models to add and merge, and which to remove. for (i = 0, l = models.length; i < l; i++) { model = models[i]; existing = this.get(model.id || model.cid || model[idAttr]); if (options.remove && existing) modelMap[existing.cid] = true; if ((options.add && !existing) || (options.merge && existing)) { add.push(model); } } if (options.remove) { for (i = 0, l = this.models.length; i < l; i++) { model = this.models[i]; if (!modelMap[model.cid]) remove.push(model); } } // Remove models (if applicable) before we add and merge the rest. if (remove.length) this.remove(remove, options); if (add.length) this.add(add, options); return this; }
javascript
{ "resource": "" }
q52694
train
function(methodName, method) { return function() { // Connect the success/error methods for callback style requests. // These style callbacks don't need the model or options arguments // because they're in the scope of the anonymous callback function. var args = _.toArray(arguments), callback = args[args.length - 1]; if (typeof callback === 'function') { // Remove the last element (the callback) args.splice(-1, 1); // Place options if none were specified. if (args.length === 0) { args.push({}); } // Place attributes if save and only options were specified if (args.length === 1 && methodName === 'save') { args.push({}); } var options = args[args.length - 1]; // Place the success and error methods options.success = function(model, response) { callback(null, response); }; options.error = function(model, response) { // Provide the response as the error. callback(response, null); }; } // Invoke the original method return method.apply(this, args); }; }
javascript
{ "resource": "" }
q52695
train
function(callback) { var t = this, startTime = Date.now(); Monitor.getRouter().connectMonitor(t, function(error) { // Monitor changes to writable attributes if (!error && t.get('writableAttributes').length > 0) { t.on('change', t.onChange, t); } // Give the caller first crack at knowing we're connected, // followed by anyone registered for the connect event. if (callback) {callback(error);} // Initial data setting into the model was done silently // in order for the connect event to fire before the first // change event. Fire the connect / change in the proper order. if (!error) { // An unfortunate side effect is any change listeners registered during // connect will get triggered with the same values as during connect. // To get around this, add change listeners from connect on nextTick. t.trigger('connect', t); t.trigger('change', t); log.info('connected', {initParams: t.get('initParams'), probeId: t.get('probeId')}); stat.time('connect', Date.now() - startTime); } }); }
javascript
{ "resource": "" }
q52696
train
function() { var t = this; return (t.probe && t.probe.connection ? t.probe.connection : null); }
javascript
{ "resource": "" }
q52697
train
function(callback) { var t = this, reason = 'manual_disconnect', startTime = Date.now(), probeId = t.get('probeId'); // Stop forwarding changes to the probe t.off('change', t.onChange, t); // Disconnect from the router Monitor.getRouter().disconnectMonitor(t, reason, function(error, reason) { if (callback) {callback(error);} if (error) { log.error('disconnect', {error: error}); } else { t.trigger('disconnect', reason); log.info('disconnected', {reason: reason, probeId: probeId}); stat.time('disconnect', Date.now() - startTime); } }); }
javascript
{ "resource": "" }
q52698
train
function() { var t = this, writableAttributes = t.get('writableAttributes'), writableChanges = {}; // Add any writable changes var probeAttrs = t.toProbeJSON(); delete probeAttrs.id; for (var attrName in probeAttrs) { var isWritable = writableAttributes === '*' || writableAttributes.indexOf(attrName) >= 0; if (isWritable && !(_.isEqual(t.attributes[attrName], t._probeValues[attrName]))) { writableChanges[attrName] = t.attributes[attrName]; } } // Pass any writable changes on to control.set() if (Monitor._.size(writableChanges)) { t.control('set', writableChanges, function(error) { if (error) { log.error('probeSet', 'Problem setting writable value', writableChanges, t.toMonitorJSON()); } }); } }
javascript
{ "resource": "" }
q52699
train
function(name, params, callback) { var t = this, probe = t.probe, logId = 'control.' + t.get('probeClass') + '.' + name, startTime = Date.now(); // Switch callback if sent in 2nd arg if (typeof params === 'function') { callback = params; params = null; } log.info(logId, params); var whenDone = function(error, args) { if (error) { log.error(logId, error); } else { log.info('return.' + logId, args); stat.time(logId, Date.now() - startTime); } if (callback) { callback.apply(t, arguments); } }; if (!probe) { return whenDone('Probe not connected'); } // Send the message internally or to the probe connection if (probe.connection) { probe.connection.emit('probe:control', {probeId: t.get('probeId'), name: name, params:params}, whenDone); } else { probe.onControl(name, params, whenDone); } }
javascript
{ "resource": "" }