_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q45300
train
function(){ // If the data grid has already been built, nothing to do here if (this.spreadsheet.datagrid) return this.spreadsheet.datagrid; var s = this.series, datagrid = this.spreadsheet.loadDataGrid(), colgroup = ['<colgroup><col />'], buttonDownload, buttonSelect, t; // First row : series' labels var html = ['<table class="flotr-datagrid"><tr class="first-row">']; html.push('<th>&nbsp;</th>'); _.each(s, function(serie,i){ html.push('<th scope="col">'+(serie.label || String.fromCharCode(65+i))+'</th>'); colgroup.push('<col />'); }); html.push('</tr>'); // Data rows _.each(datagrid, function(row){ html.push('<tr>'); _.times(s.length+1, function(i){ var tag = 'td', value = row[i], // TODO: do we really want to handle problems with floating point // precision here? content = (!_.isUndefined(value) ? Math.round(value*100000)/100000 : ''); if (i === 0) { tag = 'th'; var label = getRowLabel.call(this, content); if (label) content = label; } html.push('<'+tag+(tag=='th'?' scope="row"':'')+'>'+content+'</'+tag+'>'); }, this); html.push('</tr>'); }, this); colgroup.push('</colgroup>'); t = D.node(html.join('')); /** * @TODO disabled this if (!Flotr.isIE || Flotr.isIE == 9) { function handleMouseout(){ t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover'); } function handleMouseover(e){ var td = e.element(), siblings = td.previousSiblings(); t.select('th[scope=col]')[siblings.length-1].addClassName('hover'); t.select('colgroup col')[siblings.length].addClassName('hover'); } _.each(t.select('td'), function(td) { Flotr.EventAdapter. observe(td, 'mouseover', handleMouseover). observe(td, 'mouseout', handleMouseout); }); } */ buttonDownload = D.node( '<button type="button" class="flotr-datagrid-toolbar-button">' + this.options.spreadsheet.toolbarDownload + '</button>'); buttonSelect = D.node( '<button type="button" class="flotr-datagrid-toolbar-button">' + this.options.spreadsheet.toolbarSelectAll+ '</button>'); this. observe(buttonDownload, 'click', _.bind(this.spreadsheet.downloadCSV, this)). observe(buttonSelect, 'click', _.bind(this.spreadsheet.selectAllData, this)); var toolbar = D.node('<div class="flotr-datagrid-toolbar"></div>'); D.insert(toolbar, buttonDownload); D.insert(toolbar, buttonSelect); var containerHeight =this.canvasHeight - D.size(this.spreadsheet.tabsContainer).height-2, container = D.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:'+ this.canvasWidth+'px;height:'+containerHeight+'px;overflow:auto;z-index:10"></div>'); D.insert(container, toolbar); D.insert(container, t); D.insert(this.el, container); this.spreadsheet.datagrid = t; this.spreadsheet.container = container; return t; }
javascript
{ "resource": "" }
q45301
train
function(tabName){ if (this.spreadsheet.activeTab === tabName){ return; } switch(tabName) { case 'graph': D.hide(this.spreadsheet.container); D.removeClass(this.spreadsheet.tabs.data, 'selected'); D.addClass(this.spreadsheet.tabs.graph, 'selected'); break; case 'data': if (!this.spreadsheet.datagrid) this.spreadsheet.constructDataGrid(); D.show(this.spreadsheet.container); D.addClass(this.spreadsheet.tabs.data, 'selected'); D.removeClass(this.spreadsheet.tabs.graph, 'selected'); break; default: throw 'Illegal tab name: ' + tabName; } this.spreadsheet.activeTab = tabName; }
javascript
{ "resource": "" }
q45302
train
function(){ var csv = '', series = this.series, options = this.options, dg = this.spreadsheet.loadDataGrid(), separator = encodeURIComponent(options.spreadsheet.csvFileSeparator); if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) { throw "The decimal separator is the same as the column separator ("+options.spreadsheet.decimalSeparator+")"; } // The first row _.each(series, function(serie, i){ csv += separator+'"'+(serie.label || String.fromCharCode(65+i)).replace(/\"/g, '\\"')+'"'; }); csv += "%0D%0A"; // \r\n // For each row csv += _.reduce(dg, function(memo, row){ var rowLabel = getRowLabel.call(this, row[0]) || ''; rowLabel = '"'+(rowLabel+'').replace(/\"/g, '\\"')+'"'; var numbers = row.slice(1).join(separator); if (options.spreadsheet.decimalSeparator !== '.') { numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator); } return memo + rowLabel+separator+numbers+"%0D%0A"; // \t and \r\n }, '', this); if (Flotr.isIE && Flotr.isIE < 9) { csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r'); window.open().document.write(csv); } else window.open('data:text/csv,'+csv); }
javascript
{ "resource": "" }
q45303
train
function(src, dest){ var i, v, result = dest || {}; for (i in src) { v = src[i]; if (v && typeof(v) === 'object') { if (v.constructor === Array) { result[i] = this._.clone(v); } else if (v.constructor !== RegExp && !this._.isElement(v)) { result[i] = Flotr.merge(v, (dest ? dest[i] : undefined)); } else { result[i] = v; } } else { result[i] = v; } } return result; }
javascript
{ "resource": "" }
q45304
train
function(element, child){ if(_.isString(child)) element.innerHTML += child; else if (_.isElement(child)) element.appendChild(child); }
javascript
{ "resource": "" }
q45305
train
function (mouse) { var options = this.options, prevHit = this.prevHit, closest, sensibility, dataIndex, seriesIndex, series, value, xaxis, yaxis, n; if (this.series.length === 0) return; // Nearest data element. // dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse, // xaxis, yaxis, series, index, seriesIndex n = { relX : mouse.relX, relY : mouse.relY, absX : mouse.absX, absY : mouse.absY }; if (options.mouse.trackY && !options.mouse.trackAll && this.hit.executeOnType(this.series, 'hit', [mouse, n]) && !_.isUndefined(n.seriesIndex)) { series = this.series[n.seriesIndex]; n.series = series; n.mouse = series.mouse; n.xaxis = series.xaxis; n.yaxis = series.yaxis; } else { closest = this.hit.closest(mouse); if (closest) { closest = options.mouse.trackY ? closest.point : closest.x; seriesIndex = closest.seriesIndex; series = this.series[seriesIndex]; xaxis = series.xaxis; yaxis = series.yaxis; sensibility = 2 * series.mouse.sensibility; if (options.mouse.trackAll || (closest.distanceX < sensibility / xaxis.scale && (!options.mouse.trackY || closest.distanceY < sensibility / yaxis.scale))) { n.series = series; n.xaxis = series.xaxis; n.yaxis = series.yaxis; n.mouse = series.mouse; n.x = closest.x; n.y = closest.y; n.dist = closest.distance; n.index = closest.dataIndex; n.seriesIndex = seriesIndex; } } } if (!prevHit || (prevHit.index !== n.index || prevHit.seriesIndex !== n.seriesIndex)) { this.hit.clearHit(); if (n.series && n.mouse && n.mouse.track) { this.hit.drawMouseTrack(n); this.hit.drawHit(n); Flotr.EventAdapter.fire(this.el, 'flotr:hit', [n, this]); } } return n; }
javascript
{ "resource": "" }
q45306
resolve
train
function resolve (framework) { // strip off a trailing slash if present if (framework[framework.length-1] == '/') framework = framework.slice(0, framework.length-1); // already absolute, return as-is if (~framework.indexOf('/')) return framework; var i=0, l=PATH.length, rtn=null; for (; i<l; i++) { rtn = join(PATH[i], framework + SUFFIX); if (exists(rtn)) return rtn; } throw new Error('Could not resolve framework: ' + framework); }
javascript
{ "resource": "" }
q45307
getStruct
train
function getStruct (type) { // First check if a regular name was passed in var rtn = structCache[type]; if (rtn) return rtn; // If the struct type name has already been created, return that one var name = parseStructName(type); rtn = structCache[name]; if (rtn) return rtn; if(knownStructs[name]) type = knownStructs[name]; // Next parse the type structure var parsed = parseStruct(type); // Otherwise we need to create a new Struct constructor var props = []; parsed.props.forEach(function (prop) { props.push([ map(prop[1]), prop[0] ]) }); var z; try { z = Struct(props); } catch(e) { } return structCache[parsed.name] = z; }
javascript
{ "resource": "" }
q45308
parseStructName
train
function parseStructName (struct) { var s = struct.substring(1, struct.length-1) , equalIndex = s.indexOf('=') if (~equalIndex) s = s.substring(0, equalIndex) return s }
javascript
{ "resource": "" }
q45309
map
train
function map (type) { if (!type) throw new Error('got falsey "type" to map ('+type+'). this should NOT happen!'); if (type.type) type = type.type; if (isStruct(type)) return getStruct(type); type = type.replace(methodEncodingsTest, '') // if the first letter is a ^ then it's a "pointer" type if (type[0] === '^') return 'pointer' // now we can try matching from the typeEncodings map var rtn = typeEncodings[type] if (rtn) return rtn // last shot... try the last char? this may be a bad idea... rtn = typeEncodings[type[type.length-1]] if (rtn) return rtn // couldn't find the type. throw a descriptive error as to why: if (type[0] == '[') return 'pointer'; //throw new Error('Array types not yet supported: ' + type) if (type[0] == '(') return 'pointer'; //throw new Error('Union types not yet supported: ' + type) if (type[0] == 'b') return 'pointer'; //throw new Error('Bit field types not yet supported: ' + type) throw new Error('Could not convert type: ' + type) }
javascript
{ "resource": "" }
q45310
parse
train
function parse (types) { if (typeof types === 'string') { var rtn = [] , cur = [] , len = types.length , depth = 0 for (var i=0; i<len; i++) { var c = types[i] if (depth || !/(\d)/.test(c)) { cur.push(c) } if (c == '{' || c == '[' || c == '(') { depth++ } else if (c == '}' || c == ']' || c == ')') { depth-- if (!depth) add() } else if (~DELIMS.indexOf(c) && !depth) { add() } } function add () { rtn.push(cur.join('')) cur = [] depth = 0 } assert.equal(rtn[1], '@', '_self argument expected as first arg: ' + types) assert.equal(rtn[2], ':', 'SEL argument expected as second arg: ' + types) return [ rtn[0], rtn.slice(1) ] } else if (Array.isArray(types)) { return normalizeObjects(types); } else { var args = types.args assert.equal(args[0], '@', '_self argument expected as first arg: ' + types) assert.equal(args[1], ':', 'SEL argument expected as second arg: ' + types) return [ types.retval, args ] } }
javascript
{ "resource": "" }
q45311
ID
train
function ID (pointer) { if (typeof this !== 'function') return createFunction(null, 0, ID, arguments); var objClass = core.object_getClass(pointer); // This is absolutely necessary, otherwise we'll seg fault if a user passes in // a simple type or specifies an object on a class that takes a simple type. if (!objClass || ref.isNull(objClass)) { throw new TypeError('An abstract class or delegate implemented a method ' + 'that takes an ID (object), but a simple type or ' + 'structure (such as NSRect) was passed in'); } this.pointer = pointer; this.msgCache = []; this[invoke] = function () { return this.msgSend(arguments, false, this); }.bind(this); }
javascript
{ "resource": "" }
q45312
copyIvarList
train
function copyIvarList (classPtr) { var rtn = [] , numIvars = ref.alloc('uint') , ivars = objc.class_copyIvarList(classPtr, numIvars) , count = numIvars.deref(); for (var i=0; i<count; i++) rtn.push(objc.ivar_getName(ivars.readPointer(i * ref.sizeof.pointer))); free(ivars); return rtn; }
javascript
{ "resource": "" }
q45313
copyMethodList
train
function copyMethodList (classPtr) { var numMethods = ref.alloc('uint') , rtn = [] , methods = objc.class_copyMethodList(classPtr, numMethods) , count = numMethods.deref(); for (var i=0; i<count; i++) rtn.push(wrapValue(objc.method_getName(methods.readPointer(i * ref.sizeof.pointer)),':')); free(methods); return rtn; }
javascript
{ "resource": "" }
q45314
wrapValues
train
function wrapValues (values, objtypes) { var result = []; for(var i=0; i < objtypes.length; i++) result.push(wrapValue(values[i], objtypes[i])); return result; }
javascript
{ "resource": "" }
q45315
unwrapValue
train
function unwrapValue (val, type) { var basetype = type.type ? type.type : type; if (basetype == '@?') return createBlock(val, basetype); else if (basetype == '^?') return createWrapperPointer(val, type); else if (basetype == '@' || basetype == '#') { if(Buffer.isBuffer(val)) return val; return val ? val.pointer : null; } else if (basetype == ':') return selCache[val] || (selCache[val] = objc.sel_registerName(val)); else if (val === true) return 1; else if (val === false) return 0; else return val; }
javascript
{ "resource": "" }
q45316
unwrapValues
train
function unwrapValues (values, objtypes) { var result = []; for(var i=0; i < objtypes.length; i++) result.push(unwrapValue(values[i], objtypes[i])); return result; }
javascript
{ "resource": "" }
q45317
createUnwrapperFunction
train
function createUnwrapperFunction (funcPtr, type, isVariadic) { var rtnType = type.retval || type[0] || 'v'; var argTypes = type.args || type[1] || []; var unwrapper; if (isVariadic) { var func = ffi.VariadicForeignFunction(funcPtr, types.map(rtnType), types.mapArray(argTypes)); unwrapper = function() { var newtypes = []; // Detect the types coming in, make sure to ignore previously defined baseTypes, // garner a list of these then send the function through the normal exec. // The types system in objc, should probably be cleaned up considerably. This is // somewhat faulty but since 95% of objects coming through are mostly ID/Class // it works, we may have issues for function pointers/etc. for(var i=argTypes.length; i < arguments.length; i++) { if(arguments[i].type) newtypes.push(arguments[i].type) else if(arguments[i].pointer) newtypes.push('@'); else if(typeof arguments[i] == 'function') newtypes.push('@?'); else if(typeof arguments[i] == 'string') newtypes.push('r*'); else if(typeof arguments[i] == 'number') newtypes.push('d'); else newtypes.push('?'); } return wrapValue(func .apply(null, types.mapArray(newtypes)) .apply(null, unwrapValues(arguments,argTypes.concat(newtypes))), rtnType); }; } else { var func = ffi.ForeignFunction(funcPtr, types.map(rtnType), types.mapArray(argTypes)); unwrapper = function() { return wrapValue(func.apply(null, unwrapValues(arguments, argTypes)), rtnType); } } unwrapper.retval = rtnType; unwrapper.args = argTypes; unwrapper.pointer = funcPtr; return unwrapper; }
javascript
{ "resource": "" }
q45318
Filter
train
function Filter(opts) { this.model = opts.model this.filteredKeys = isPlainObject(opts.filteredKeys) ? { private: opts.filteredKeys.private || [], protected: opts.filteredKeys.protected || [] } : { private: [], protected: [] } if (this.model && this.model.discriminators && isPlainObject(opts.excludedMap)) { for (const modelName in this.model.discriminators) { if (opts.excludedMap[modelName]) { this.filteredKeys.private = this.filteredKeys.private.concat(opts.excludedMap[modelName].private) this.filteredKeys.protected = this.filteredKeys.protected.concat(opts.excludedMap[modelName].protected) } } } }
javascript
{ "resource": "" }
q45319
createAbortSignal
train
function createAbortSignal() { const signal = Object.create(AbortSignal.prototype); eventTargetShim.EventTarget.call(signal); abortedFlags.set(signal, false); return signal; }
javascript
{ "resource": "" }
q45320
abortSignal
train
function abortSignal(signal) { if (abortedFlags.get(signal) !== false) { return; } abortedFlags.set(signal, true); signal.dispatchEvent({ type: "abort" }); }
javascript
{ "resource": "" }
q45321
getSignal
train
function getSignal(controller) { const signal = signals.get(controller); if (signal == null) { throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); } return signal; }
javascript
{ "resource": "" }
q45322
Config
train
function Config(rules, options) { this.options = {}; if (options) { options.forEach(this.addOption.bind(this)); } this.rulesMap = {}; if (rules) { rules.forEach(this.addRule.bind(this)); } }
javascript
{ "resource": "" }
q45323
train
function (config) { this.setOption = config.setOption.bind(config); this.isOption = function (name) { return name in config.options; }; this.clear(); }
javascript
{ "resource": "" }
q45324
applyConfig
train
function applyConfig(config) { var previous = {}; config.rules.forEach(function (rule) { var isprev = (rule.value === '$previous'); var setOption = function (name, value) { previous[name] = this.current[name]; this.current[name] = this.setOption(name, value, isprev); }.bind(this); if (rule.type === 'rule') { setOption(rule.name, isprev ? this.previous[rule.name] : rule.value); /* istanbul ignore else */ } else if (rule.type === 'preset') { var preset = isprev ? this.previousPreset : presets.presets[rule.value]; Object.keys(preset).forEach(function (name) { setOption(name, preset[name]); }); } }.bind(this)); lodash.merge(this.previous, this.previousPreset = previous); }
javascript
{ "resource": "" }
q45325
parsePair
train
function parsePair(name, value, pos, isOption) { if (!name || !value || !name.length || !value.length) { return new Issue('E050', pos); } var nameRegex = /^[a-zA-Z0-9-_]+$/; if (!nameRegex.test(name)) { return new Issue('E051', pos, {name: name}); } // Strip quotes and replace single quotes with double quotes var squote = '\'', dquote = '"'; // Single and double quote, for sanity if (value[0] === squote || value[0] === dquote) { value = value.substr(1, value.length - 2); } value = value.replace(/\'/g, dquote); // Treat _ and - interchangeably name = name.replace(/_/g, '-'); // check if our value is for a preset. if (name === 'preset') { if (value !== '$previous' && !presets.presets[value]) { return new Issue('E052', pos, {preset: value}); } else { return { type: 'preset', value: value }; } } // it's not a preset. var parsed = null; if (value === '$previous') { parsed = '$previous'; } else if (value[0] === '$') { var vs = value.substr(1); if (!presets.presets[vs]) { return new Issue('E052', pos, {preset: vs}); } parsed = presets.presets[vs][name]; } else { if (!isOption(name)) { return new Issue('E054', pos, {name: name}); } try { parsed = JSON.parse(value); } catch (e) { if (!nameRegex.test(value)) { return new Issue('E053', pos, {rule: name, value: value}); } parsed = value; } } return { type: 'rule', name: name, value: parsed }; }
javascript
{ "resource": "" }
q45326
train
function (rules, options) { this.rules = new Config(rules, options); this.parser = new Parser(); this.inlineConfig = new InlineConfig(this.rules); }
javascript
{ "resource": "" }
q45327
linspace
train
function linspace(min, max, count) { var range = (max - min) / (count - 1); var res = []; for (var i = 0; i < count; i++) { res.push(min + range * i); } return res; }
javascript
{ "resource": "" }
q45328
train
function (newProps) { var value = this._or(ensureArray(newProps.value), this.state.value); // ensure the array keeps the same size as `value` this.tempArray = value.slice(); for (var i = 0; i < value.length; i++) { this.state.value[i] = this._trimAlignValue(value[i], newProps); } if (this.state.value.length > value.length) this.state.value.length = value.length; // If an upperBound has not yet been determined (due to the component being hidden // during the mount event, or during the last resize), then calculate it now if (this.state.upperBound === 0) { this._resize(); } }
javascript
{ "resource": "" }
q45329
train
function (value) { var range = this.props.max - this.props.min; if (range === 0) { return 0; } var ratio = (value - this.props.min) / range; return ratio * this.state.upperBound; }
javascript
{ "resource": "" }
q45330
train
function (offset) { var ratio = offset / this.state.upperBound; return ratio * (this.props.max - this.props.min) + this.props.min; }
javascript
{ "resource": "" }
q45331
train
function (position, callback) { var pixelOffset = this._calcOffsetFromPosition(position); var closestIndex = this._getClosestIndex(pixelOffset); var nextValue = this._trimAlignValue(this._calcValue(pixelOffset)); var value = this.state.value.slice(); // Clone this.state.value since we'll modify it temporarily value[closestIndex] = nextValue; // Prevents the slider from shrinking below `props.minDistance` for (var i = 0; i < value.length - 1; i += 1) { if (value[i + 1] - value[i] < this.props.minDistance) return; } this.setState({value: value}, callback.bind(this, closestIndex)); }
javascript
{ "resource": "" }
q45332
train
function (i) { return function (e) { if (this.props.disabled) return; this._start(i); this._addHandlers(this._getKeyDownEventMap()); pauseEvent(e); }.bind(this); }
javascript
{ "resource": "" }
q45333
train
function (i) { return function (e) { if (this.props.disabled) return; var position = this._getMousePosition(e); this._start(i, position[0]); this._addHandlers(this._getMouseEventMap()); pauseEvent(e); }.bind(this); }
javascript
{ "resource": "" }
q45334
train
function (i) { return function (e) { if (this.props.disabled || e.touches.length > 1) return; var position = this._getTouchPosition(e); this.startPosition = position; this.isScrolling = undefined; // don't know yet if the user is trying to scroll this._start(i, position[0]); this._addHandlers(this._getTouchEventMap()); stopPropagation(e); }.bind(this); }
javascript
{ "resource": "" }
q45335
train
function() { var result = {}; for (var i = arguments.length - 1; i >= 0; i--) { var obj = arguments[i]; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } } return result; }
javascript
{ "resource": "" }
q45336
train
function(el, text) { var scrollPos = el.scrollTop, strPos = 0, browser = false, range; if ((el.selectionStart || el.selectionStart === '0')) { browser = "ff"; } else if (document.selection) { browser = "ie"; } if (browser === "ie") { el.focus(); range = document.selection.createRange(); range.moveStart('character', -el.value.length); strPos = range.text.length; } else if (browser === "ff") { strPos = el.selectionStart; } var front = (el.value).substring(0, strPos); var back = (el.value).substring(strPos, el.value.length); el.value = front + text + back; strPos = strPos + text.length; if (browser === "ie") { el.focus(); range = document.selection.createRange(); range.moveStart('character', -el.value.length); range.moveStart('character', strPos); range.moveEnd('character', 0); range.select(); } else if (browser === "ff") { el.selectionStart = strPos; el.selectionEnd = strPos; el.focus(); } el.scrollTop = scrollPos; }
javascript
{ "resource": "" }
q45337
readParameters
train
function readParameters(obj, scope) { var result = {}, attrs = obj.$attr, option, value; for (var key in attrs) { option = lcfirst(key.substr(attrName.length)); value = obj[key]; // Check if the given key is a valid string type, not empty and starts with the attribute name if ((option.length > 0) && (key.substring(0, attrName.length) === attrName)) { result[option] = value; if (typeof scope[value] === 'function') { result[option] = scope[value]; } } } return result; }
javascript
{ "resource": "" }
q45338
train
function(instance) { var $this = $(instance); return { getValue: function() { return $this.val(); }, insertValue: function(val) { inlineAttachment.util.insertTextAtCursor($this[0], val); }, setValue: function(val) { $this.val(val); } }; }
javascript
{ "resource": "" }
q45339
train
function (matrix4x4) { let ismirror = matrix4x4.isMirroring() // get two vectors in the plane: let r = this.normal.randomNonParallelVector() let u = this.normal.cross(r) let v = this.normal.cross(u) // get 3 points in the plane: let point1 = this.normal.times(this.w) let point2 = point1.plus(u) let point3 = point1.plus(v) // transform the points: point1 = point1.multiply4x4(matrix4x4) point2 = point2.multiply4x4(matrix4x4) point3 = point3.multiply4x4(matrix4x4) // and create a new plane from the transformed points: let newplane = Plane.fromVector3Ds(point1, point2, point3) if (ismirror) { // the transform is mirroring // We should mirror the plane: newplane = newplane.flipped() } return newplane }
javascript
{ "resource": "" }
q45340
train
function (p1, p2) { let direction = p2.minus(p1) let labda = (this.w - this.normal.dot(p1)) / this.normal.dot(direction) if (isNaN(labda)) labda = 0 if (labda > 1) labda = 1 if (labda < 0) labda = 0 let result = p1.plus(direction.times(labda)) return result }
javascript
{ "resource": "" }
q45341
vectorParams
train
function vectorParams (options, input) { if (!input && typeof options === 'string') { options = { input: options } } options = options || {} let params = Object.assign({}, defaultsVectorParams, options) params.input = input || params.input return params }
javascript
{ "resource": "" }
q45342
setShared
train
function setShared (shared) { let polygons = this.polygons.map(function (p) { return new Polygon3(p.vertices, shared, p.plane) }) let result = fromPolygons(polygons) result.properties = this.properties // keep original properties result.isRetesselated = this.isRetesselated result.isCanonicalized = this.isCanonicalized return result }
javascript
{ "resource": "" }
q45343
train
function (options) { options = options || {} if (('points' in options) !== ('faces' in options)) { throw new Error("polyhedron needs 'points' and 'faces' arrays") } let vertices = parseOptionAs3DVectorList(options, 'points', [ [1, 1, 0], [1, -1, 0], [-1, -1, 0], [-1, 1, 0], [0, 0, 1] ]) .map(function (pt) { return new Vertex3(pt) }) let faces = parseOption(options, 'faces', [ [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4], [1, 0, 3], [2, 1, 3] ]) // Openscad convention defines inward normals - so we have to invert here faces.forEach(function (face) { face.reverse() }) let polygons = faces.map(function (face) { return new Polygon3(face.map(function (idx) { return vertices[idx] })) }) // TODO: facecenters as connectors? probably overkill. Maybe centroid // the re-tesselation here happens because it's so easy for a user to // create parametrized polyhedrons that end up with 1-2 dimensional polygons. // These will create infinite loops at CSG.Tree() return fromPolygons(polygons).reTesselated() }
javascript
{ "resource": "" }
q45344
connectTo
train
function connectTo (shape3, connector, otherConnector, mirror, normalrotation) { let matrix = connector.getTransformationTo(otherConnector, mirror, normalrotation) return transform(matrix, shape3) }
javascript
{ "resource": "" }
q45345
rotate
train
function rotate (...params) { let out let angle let vector if (params.length === 2) { out = create() angle = params[0] vector = params[1] } else { out = params[0] angle = params[1] vector = params[2] } // fIXME: not correct console.log('rotate', angle, vector) const origin = [0, 0, 0] out = rotateZ(angle[2], origin, rotateY(angle[1], origin, rotateX(angle[0], origin, vector))) return out }
javascript
{ "resource": "" }
q45346
train
function (plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) { if (this.children.length) { let queue = [this.children] let i let j let l let node let nodes for (i = 0; i < queue.length; i++) { // queue.length can increase, do not cache nodes = queue[i] for (j = 0, l = nodes.length; j < l; j++) { // ok to cache length node = nodes[j] if (node.children.length) { queue.push(node.children) } else { // no children. Split the polygon: node._splitByPlane(plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) } } } } else { this._splitByPlane(plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) } }
javascript
{ "resource": "" }
q45347
translateLine
train
function translateLine (options, line) { const { x, y } = Object.assign({ x: 0, y: 0 }, options || {}) let segments = line.segments let segment = null let point = null for (let i = 0, il = segments.length; i < il; i++) { segment = segments[i] for (let j = 0, jl = segment.length; j < jl; j++) { point = segment[j] segment[j] = [point[0] + x, point[1] + y] } } return line }
javascript
{ "resource": "" }
q45348
fromObject
train
function fromObject (obj) { let polygons = obj.polygons.map(polygonLike => poly3.fromObject(polygonLike)) let shape3 = fromPolygons(polygons) shape3.isCanonicalized = obj.isCanonicalized shape3.isRetesselated = obj.isRetesselated return shape3 }
javascript
{ "resource": "" }
q45349
train
function (plane, rightvector) { if (arguments.length < 2) { // choose an arbitrary right hand vector, making sure it is somewhat orthogonal to the plane normal: rightvector = vec3.random(plane) } else { rightvector = rightvector } this.v = vec3.unit(vec3.cross(plane, rightvector)) this.u = vec3.cross(this.v, plane) this.plane = plane this.planeorigin = vec3.scale(plane[3], plane) }
javascript
{ "resource": "" }
q45350
setEngine
train
function setEngine(Engine, config) { initialized = false; engine = new Engine(config); init(config); }
javascript
{ "resource": "" }
q45351
init
train
function init(config) { if (!engine) throw new Error( "No engine set for research. Set an engine using gitbook.research.setEngine(Engine)." ); return engine.init(config).then(function() { initialized = true; gitbook.events.trigger("search.ready"); }); }
javascript
{ "resource": "" }
q45352
query
train
function query(q, offset, length) { if (!initialized) throw new Error("Search has not been initialized"); return engine.search(q, offset, length); }
javascript
{ "resource": "" }
q45353
enlargeFontSize
train
function enlargeFontSize(e) { e.preventDefault(); if (fontState.size >= MAX_SIZE) return; fontState.size++; saveFontSettings(); }
javascript
{ "resource": "" }
q45354
reduceFontSize
train
function reduceFontSize(e) { e.preventDefault(); if (fontState.size <= MIN_SIZE) return; fontState.size--; saveFontSettings(); }
javascript
{ "resource": "" }
q45355
changeFontFamily
train
function changeFontFamily(configName, e) { if (e && e instanceof Event) { e.preventDefault(); } var familyId = getFontFamilyId(configName); fontState.family = familyId; saveFontSettings(); }
javascript
{ "resource": "" }
q45356
changeColorTheme
train
function changeColorTheme(configName, e) { if (e && e instanceof Event) { e.preventDefault(); } var $book = gitbook.state.$book; // Remove currently applied color theme if (fontState.theme !== 0) $book.removeClass("color-theme-" + fontState.theme); // Set new color theme var themeId = getThemeId(configName); fontState.theme = themeId; if (fontState.theme !== 0) $book.addClass("color-theme-" + fontState.theme); saveFontSettings(); }
javascript
{ "resource": "" }
q45357
getFontFamilyId
train
function getFontFamilyId(configName) { // Search for plugin configured font family var configFamily = $.grep(FAMILIES, function(family) { return family.config == configName; })[0]; // Fallback to default font family return !!configFamily ? configFamily.id : 0; }
javascript
{ "resource": "" }
q45358
getThemeId
train
function getThemeId(configName) { // Search for plugin configured theme var configTheme = $.grep(THEMES, function(theme) { return theme.config == configName; })[0]; // Fallback to default theme return !!configTheme ? configTheme.id : 0; }
javascript
{ "resource": "" }
q45359
sanitizeKey
train
function sanitizeKey(obj) { if (typeof obj !== 'object') return obj; if (Array.isArray(obj)) return obj; if (obj === null) return null; if (obj instanceof Boolean) return obj; if (obj instanceof Number) return obj; if (obj instanceof Buffer) return obj.toString(); for (const k in obj) { const escapedK = sjs(k); if (escapedK !== k) { obj[escapedK] = sanitizeKey(obj[k]); obj[k] = undefined; } else { obj[k] = sanitizeKey(obj[k]); } } return obj; }
javascript
{ "resource": "" }
q45360
train
function(property) { if (!property) { return true } var div = document.createElement("div") var vendorPrefixes = ["khtml", "ms", "o", "moz", "webkit"] var count = vendorPrefixes.length // Note: HTMLElement.style.hasOwnProperty seems broken in Edge if (property in div.style) { return true } property = property.replace(/^[a-z]/, function(val) { return val.toUpperCase() }) while (count--) { var prefixedProperty = vendorPrefixes[count] + property // See comment re: HTMLElement.style.hasOwnProperty above if (prefixedProperty in div.style) { return true } } return false }
javascript
{ "resource": "" }
q45361
train
function (mapping) { const result = {}; for (const [key, value] of _.toPairs(mapping)) { result[key] = _.isString(value) ? value : JSON.stringify(value); } return result; }
javascript
{ "resource": "" }
q45362
extractFromApks
train
async function extractFromApks (apks, dstPath) { if (!_.isArray(dstPath)) { dstPath = [dstPath]; } return await APKS_CACHE_GUARD.acquire(apks, async () => { // It might be that the original file has been replaced, // so we need to keep the hash sums instead of the actual file paths // as caching keys const apksHash = await fs.hash(apks); log.debug(`Calculated '${apks}' hash: ${apksHash}`); if (APKS_CACHE.has(apksHash)) { const resultPath = path.resolve(APKS_CACHE.get(apksHash), ...dstPath); if (await fs.exists(resultPath)) { return resultPath; } APKS_CACHE.del(apksHash); } const tmpRoot = await tempDir.openDir(); log.debug(`Unpacking application bundle at '${apks}' to '${tmpRoot}'`); await unzipFile(apks, tmpRoot); const resultPath = path.resolve(tmpRoot, ...dstPath); if (!await fs.exists(resultPath)) { throw new Error(`${dstPath.join(path.sep)} cannot be found in '${apks}' bundle. ` + `Does the archive contain a valid application bundle?`); } APKS_CACHE.set(apksHash, tmpRoot); return resultPath; }); }
javascript
{ "resource": "" }
q45363
extractApkInfoWithApkanalyzer
train
async function extractApkInfoWithApkanalyzer (localApk, apkanalyzerPath) { const args = ['-h', 'manifest', 'print', localApk]; log.debug(`Starting '${apkanalyzerPath}' with args ${JSON.stringify(args)}`); const manifestXml = (await exec(apkanalyzerPath, args, { shell: true, cwd: path.dirname(apkanalyzerPath) })).stdout; const doc = new xmldom.DOMParser().parseFromString(manifestXml); const apkPackageAttribute = xpath.select1('//manifest/@package', doc); if (!apkPackageAttribute) { throw new Error(`Cannot parse package name from ${manifestXml}`); } const apkPackage = apkPackageAttribute.value; // Look for activity or activity-alias with // action == android.intent.action.MAIN and // category == android.intent.category.LAUNCHER // descendants const apkActivityAttribute = xpath.select1( "//application/*[starts-with(name(), 'activity') " + "and .//action[@*[local-name()='name' and .='android.intent.action.MAIN']] " + "and .//category[@*[local-name()='name' and .='android.intent.category.LAUNCHER']]]" + "/@*[local-name()='name']", doc); if (!apkActivityAttribute) { throw new Error(`Cannot parse main activity name from ${manifestXml}`); } const apkActivity = apkActivityAttribute.value; return {apkPackage, apkActivity}; }
javascript
{ "resource": "" }
q45364
buildStartCmd
train
function buildStartCmd (startAppOptions, apiLevel) { let cmd = ['am', 'start']; if (util.hasValue(startAppOptions.user)) { cmd.push('--user', startAppOptions.user); } cmd.push('-W', '-n', `${startAppOptions.pkg}/${startAppOptions.activity}`); if (startAppOptions.stopApp && apiLevel >= 15) { cmd.push('-S'); } if (startAppOptions.action) { cmd.push('-a', startAppOptions.action); } if (startAppOptions.category) { cmd.push('-c', startAppOptions.category); } if (startAppOptions.flags) { cmd.push('-f', startAppOptions.flags); } if (startAppOptions.optionalIntentArguments) { // expect optionalIntentArguments to be a single string of the form: // "-flag key" // "-flag key value" // or a combination of these (e.g., "-flag1 key1 -flag2 key2 value2") // take a string and parse out the part before any spaces, and anything after // the first space let parseKeyValue = function (str) { str = str.trim(); let space = str.indexOf(' '); if (space === -1) { return str.length ? [str] : []; } else { return [str.substring(0, space).trim(), str.substring(space + 1).trim()]; } }; // cycle through the optionalIntentArguments and pull out the arguments // add a space initially so flags can be distinguished from arguments that // have internal hyphens let optionalIntentArguments = ` ${startAppOptions.optionalIntentArguments}`; let re = / (-[^\s]+) (.+)/; while (true) { // eslint-disable-line no-constant-condition let args = re.exec(optionalIntentArguments); if (!args) { if (optionalIntentArguments.length) { // no more flags, so the remainder can be treated as 'key' or 'key value' cmd.push.apply(cmd, parseKeyValue(optionalIntentArguments)); } // we are done break; } // take the flag and see if it is at the beginning of the string // if it is not, then it means we have been through already, and // what is before the flag is the argument for the previous flag let flag = args[1]; let flagPos = optionalIntentArguments.indexOf(flag); if (flagPos !== 0) { let prevArgs = optionalIntentArguments.substring(0, flagPos); cmd.push.apply(cmd, parseKeyValue(prevArgs)); } // add the flag, as there are no more earlier arguments cmd.push(flag); // make optionalIntentArguments hold the remainder optionalIntentArguments = args[2]; } } return cmd; }
javascript
{ "resource": "" }
q45365
train
function (str) { str = str.trim(); let space = str.indexOf(' '); if (space === -1) { return str.length ? [str] : []; } else { return [str.substring(0, space).trim(), str.substring(space + 1).trim()]; } }
javascript
{ "resource": "" }
q45366
train
function (dumpsysOutput, groupNames, grantedState = null) { const groupPatternByName = (groupName) => new RegExp(`^(\\s*${_.escapeRegExp(groupName)} permissions:[\\s\\S]+)`, 'm'); const indentPattern = /\S|$/; const permissionNamePattern = /android\.permission\.\w+/; const grantedStatePattern = /\bgranted=(\w+)/; const result = []; for (const groupName of groupNames) { const groupMatch = groupPatternByName(groupName).exec(dumpsysOutput); if (!groupMatch) { continue; } const lines = groupMatch[1].split('\n'); if (lines.length < 2) { continue; } const titleIndent = lines[0].search(indentPattern); for (const line of lines.slice(1)) { const currentIndent = line.search(indentPattern); if (currentIndent <= titleIndent) { break; } const permissionNameMatch = permissionNamePattern.exec(line); if (!permissionNameMatch) { continue; } const item = { permission: permissionNameMatch[0], }; const grantedStateMatch = grantedStatePattern.exec(line); if (grantedStateMatch) { item.granted = grantedStateMatch[1] === 'true'; } result.push(item); } } const filteredResult = result .filter((item) => !_.isBoolean(grantedState) || item.granted === grantedState) .map((item) => item.permission); log.debug(`Retrieved ${filteredResult.length} permission(s) from ${JSON.stringify(groupNames)} group(s)`); return filteredResult; }
javascript
{ "resource": "" }
q45367
patchApksigner
train
async function patchApksigner (originalPath) { const originalContent = await fs.readFile(originalPath, 'ascii'); const patchedContent = originalContent.replace('-Djava.ext.dirs="%frameworkdir%"', '-cp "%frameworkdir%\\*"'); if (patchedContent === originalContent) { return originalPath; } log.debug(`Patching '${originalPath}...`); const patchedPath = await tempDir.path({prefix: 'apksigner', suffix: '.bat'}); await mkdirp(path.dirname(patchedPath)); await fs.writeFile(patchedPath, patchedContent, 'ascii'); return patchedPath; }
javascript
{ "resource": "" }
q45368
google
train
function google (query, start, callback) { var startIndex = 0 if (typeof callback === 'undefined') { callback = start } else { startIndex = start } igoogle(query, startIndex, callback) }
javascript
{ "resource": "" }
q45369
copypaste
train
function copypaste(from, to, ...props) { props.forEach((prop) => { if (prop in from) to[prop] = from[prop]; }); }
javascript
{ "resource": "" }
q45370
prepare
train
function prepare(props) { const clean = rip(props, 'translate', 'scale', 'rotate', 'skewX', 'skewY', 'originX', 'originY', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'style' ); const transform = []; // // Correctly apply the transformation properties. // To apply originX and originY we need to translate the element on those values and // translate them back once the element is scaled, rotated and skewed. // if ('originX' in props || 'originY' in props) transform.push(`translate(${props.originX || 0}, ${props.originY || 0})`); if ('translate' in props) transform.push(`translate(${props.translate})`); if ('scale' in props) transform.push(`scale(${props.scale})`); if ('rotate' in props) transform.push(`rotate(${props.rotate})`); if ('skewX' in props) transform.push(`skewX(${props.skewX})`); if ('skewY' in props) transform.push(`skewY(${props.skewY})`); if ('originX' in props || 'originY' in props) transform.push(`translate(${-props.originX || 0}, ${-props.originY || 0})`); if (transform.length) clean.transform = transform.join(' '); // // Correctly set the initial style value. // const style = ('style' in props) ? props.style : {}; // // This is the nasty part where we depend on React internals to work as // intended. If we add an empty object as style, it shouldn't render a `style` // attribute. So we can safely conditionally add things to our `style` object // and re-introduce it to our `clean` object // copypaste(props, style, 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle'); clean.style = style; // // React-Native svg provides as a default of `xMidYMid` if aspectRatio is not // specified with align information. So we need to support this behavior and // correctly default to `xMidYMid [mode]`. // const preserve = clean.preserveAspectRatio; if (preserve && preserve !== 'none' && !~preserve.indexOf(' ')) { clean.preserveAspectRatio = 'xMidYMid ' + preserve; } return clean; }
javascript
{ "resource": "" }
q45371
G
train
function G(props) { const { x, y, ...rest } = props; if ((x || y) && !rest.translate) { rest.translate = `${x || 0}, ${y || 0}`; } return <g { ...prepare(rest) } />; }
javascript
{ "resource": "" }
q45372
Svg
train
function Svg(props) { const { title, ...rest } = props; if (title) { return ( <svg role='img' aria-label='[title]' { ...prepare(rest) }> <title>{ title }</title> { props.children } </svg> ); } return <svg { ...prepare(rest) } />; }
javascript
{ "resource": "" }
q45373
Text
train
function Text(props) { const { x, y, dx, dy, rotate, ...rest } = props; return <text { ...prepare(rest) } { ...{ x, y, dx, dy, rotate } } />; }
javascript
{ "resource": "" }
q45374
TSpan
train
function TSpan(props) { const { x, y, dx, dy, rotate, ...rest } = props; return <tspan { ...prepare(rest) } { ...{ x, y, dx, dy, rotate } } />; }
javascript
{ "resource": "" }
q45375
_applyAttrs
train
function _applyAttrs(context, attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { context.setAttribute(attr, attrs[attr]); } } }
javascript
{ "resource": "" }
q45376
_applyStyles
train
function _applyStyles(context, attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { context.style[attr] = attrs[attr]; } } }
javascript
{ "resource": "" }
q45377
_getStyle
train
function _getStyle(el, styleProp) { var x = el , y = null; if (window.getComputedStyle) { y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp); } else if (x.currentStyle) { y = x.currentStyle[styleProp]; } return y; }
javascript
{ "resource": "" }
q45378
_saveStyleState
train
function _saveStyleState(el, type, styles) { var returnState = {} , style; if (type === 'save') { for (style in styles) { if (styles.hasOwnProperty(style)) { returnState[style] = _getStyle(el, style); } } // After it's all done saving all the previous states, change the styles _applyStyles(el, styles); } else if (type === 'apply') { _applyStyles(el, styles); } return returnState; }
javascript
{ "resource": "" }
q45379
_outerWidth
train
function _outerWidth(el) { var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10) , p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10) , w = el.offsetWidth , t; // For IE in case no border is set and it defaults to "medium" if (isNaN(b)) { b = 0; } t = b + p + w; return t; }
javascript
{ "resource": "" }
q45380
_outerHeight
train
function _outerHeight(el) { var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10) , p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10) , w = parseInt(_getStyle(el, 'height'), 10) , t; // For IE in case no border is set and it defaults to "medium" if (isNaN(b)) { b = 0; } t = b + p + w; return t; }
javascript
{ "resource": "" }
q45381
_getText
train
function _getText(el) { var theText; // Make sure to check for type of string because if the body of the page // doesn't have any text it'll be "" which is falsey and will go into // the else which is meant for Firefox and shit will break if (typeof document.body.innerText == 'string') { theText = el.innerText; } else { // First replace <br>s before replacing the rest of the HTML theText = el.innerHTML.replace(/<br>/gi, "\n"); // Now we can clean the HTML theText = theText.replace(/<(?:.|\n)*?>/gm, ''); // Now fix HTML entities theText = theText.replace(/&lt;/gi, '<'); theText = theText.replace(/&gt;/gi, '>'); } return theText; }
javascript
{ "resource": "" }
q45382
_mergeObjs
train
function _mergeObjs() { // copy reference to target object var target = arguments[0] || {} , i = 1 , length = arguments.length , deep = false , options , name , src , copy // Handle a deep copy situation if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== "object" && !_isFunction(target)) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = this; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { // @NOTE: added hasOwnProperty check if (options.hasOwnProperty(name)) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging object values if (deep && copy && typeof copy === "object" && !copy.nodeType) { target[name] = _mergeObjs(deep, // Never move original objects, clone them src || (copy.length != null ? [] : {}) , copy); } else if (copy !== undefined) { // Don't bring in undefined values target[name] = copy; } } } } } // Return the modified object return target; }
javascript
{ "resource": "" }
q45383
shortcutHandler
train
function shortcutHandler(e) { if (e.keyCode == self.settings.shortcut.modifier) { isMod = true } // check for modifier press(default is alt key), save to var if (e.keyCode == 17) { isCtrl = true } // check for ctrl/cmnd press, in order to catch ctrl/cmnd + s if (e.keyCode == 18) { isCtrl = false } // Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview if (isMod === true && e.keyCode == self.settings.shortcut.preview && !self.is('fullscreen')) { e.preventDefault(); if (self.is('edit') && self._previewEnabled) { self.preview(); } else if (self._editEnabled) { self.edit(); } } // Check for alt+f - default shortcut to make editor fullscreen if (isMod === true && e.keyCode == self.settings.shortcut.fullscreen && self._fullscreenEnabled) { e.preventDefault(); self._goFullscreen(fsElement); } // Set the modifier key to false once *any* key combo is completed // or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133) if (isMod === true && e.keyCode !== self.settings.shortcut.modifier) { isMod = false; } // When a user presses "esc", revert everything! if (e.keyCode == 27 && self.is('fullscreen')) { self._exitFullscreen(fsElement); } // Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing if (isCtrl === true && e.keyCode == 83) { self.save(); e.preventDefault(); isCtrl = false; } // Do the same for Mac now (metaKey == cmd). if (e.metaKey && e.keyCode == 83) { self.save(); e.preventDefault(); } }
javascript
{ "resource": "" }
q45384
deposit
train
function deposit(g, i, j, xl, displacement) { var currentKey = j * xl + i; // Pick a random neighbor. for (var k = 0; k < 3; k++) { var r = Math.floor(Math.random() * 8); switch (r) { case 0: i++; break; case 1: i--; break; case 2: j++; break; case 3: j--; break; case 4: i++; j++; break; case 5: i++; j--; break; case 6: i--; j++; break; case 7: i--; j--; break; } var neighborKey = j * xl + i; // If the neighbor is lower, move the particle to that neighbor and re-evaluate. if (typeof g[neighborKey] !== 'undefined') { if (g[neighborKey].z < g[currentKey].z) { deposit(g, i, j, xl, displacement); return; } } // Deposit some particles on the edge. else if (Math.random() < 0.2) { g[currentKey].z += displacement; return; } } g[currentKey].z += displacement; }
javascript
{ "resource": "" }
q45385
WhiteNoise
train
function WhiteNoise(g, options, scale, segments, range, data) { if (scale > segments) return; var i = 0, j = 0, xl = segments, yl = segments, inc = Math.floor(segments / scale), lastX = -inc, lastY = -inc; // Walk over the target. For a target of size W and a resolution of N, // set every W/N points (in both directions). for (i = 0; i <= xl; i += inc) { for (j = 0; j <= yl; j += inc) { var k = j * xl + i; data[k] = Math.random() * range; if (lastX < 0 && lastY < 0) continue; // jscs:disable disallowSpacesInsideBrackets /* c b * * l t */ var t = data[k], l = data[ j * xl + (i-inc)] || t, // left b = data[(j-inc) * xl + i ] || t, // bottom c = data[(j-inc) * xl + (i-inc)] || t; // corner // jscs:enable disallowSpacesInsideBrackets // Interpolate between adjacent points to set the height of // higher-resolution target data. for (var x = lastX; x < i; x++) { for (var y = lastY; y < j; y++) { if (x === lastX && y === lastY) continue; var z = y * xl + x; if (z < 0) continue; var px = ((x-lastX) / inc), py = ((y-lastY) / inc), r1 = px * b + (1-px) * c, r2 = px * t + (1-px) * l; data[z] = py * r2 + (1-py) * r1; } } lastY = j; } lastX = i; lastY = -inc; } // Assign the temporary data back to the actual terrain heightmap. for (i = 0, xl = options.xSegments + 1; i < xl; i++) { for (j = 0, yl = options.ySegments + 1; j < yl; j++) { // http://stackoverflow.com/q/23708306/843621 var kg = j * xl + i, kd = j * segments + i; g[kg].z += data[kd]; } } }
javascript
{ "resource": "" }
q45386
gaussianBoxBlur
train
function gaussianBoxBlur(scl, w, h, r, n, tcl) { if (typeof r === 'undefined') r = 1; if (typeof n === 'undefined') n = 3; if (typeof tcl === 'undefined') tcl = new Float64Array(scl.length); var boxes = boxesForGauss(r, n); for (var i = 0; i < n; i++) { boxBlur(scl, tcl, w, h, (boxes[i]-1)/2); } return tcl; }
javascript
{ "resource": "" }
q45387
boxesForGauss
train
function boxesForGauss(sigma, n) { // Calculate how far out we need to go to capture the bulk of the distribution. var wIdeal = Math.sqrt(12*sigma*sigma/n + 1); // Ideal averaging filter width var wl = Math.floor(wIdeal); // Lower odd integer bound on the width if (wl % 2 === 0) wl--; var wu = wl+2; // Upper odd integer bound on the width var mIdeal = (12*sigma*sigma - n*wl*wl - 4*n*wl - 3*n)/(-4*wl - 4); var m = Math.round(mIdeal); // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 ); var sizes = new Int16Array(n); for (var i = 0; i < n; i++) { sizes[i] = i < m ? wl : wu; } return sizes; }
javascript
{ "resource": "" }
q45388
boxBlur
train
function boxBlur(scl, tcl, w, h, r) { for (var i = 0, l = scl.length; i < l; i++) { tcl[i] = scl[i]; } boxBlurH(tcl, scl, w, h, r); boxBlurV(scl, tcl, w, h, r); }
javascript
{ "resource": "" }
q45389
boxBlurH
train
function boxBlurH(scl, tcl, w, h, r) { var iarr = 1 / (r+r+1); // averaging adjustment parameter for (var i = 0; i < h; i++) { var ti = i * w, // current target index li = ti, // current left side of the examined range ri = ti + r, // current right side of the examined range fv = scl[ti], // first value in the row lv = scl[ti + w - 1], // last value in the row val = (r+1) * fv, // target value, accumulated over examined points j; // Sum the source values in the box for (j = 0; j < r; j++) { val += scl[ti + j]; } // Compute the target value by taking the average of the surrounding // values. This is done by adding the deviations so far and adjusting, // accounting for the edges by extending the first and last values. for (j = 0 ; j <= r ; j++) { val += scl[ri++] - fv ; tcl[ti++] = val*iarr; } for (j = r+1; j < w-r; j++) { val += scl[ri++] - scl[li++]; tcl[ti++] = val*iarr; } for (j = w-r; j < w ; j++) { val += lv - scl[li++]; tcl[ti++] = val*iarr; } } }
javascript
{ "resource": "" }
q45390
distanceToNearest
train
function distanceToNearest(coords, points, distanceType) { var color = Infinity, distanceFunc = 'distanceTo' + distanceType; for (var k = 0; k < points.length; k++) { var d = points[k][distanceFunc](coords); if (d < color) { color = d; } } return color; }
javascript
{ "resource": "" }
q45391
watchFocus
train
function watchFocus() { var _blurred = false; window.addEventListener('focus', function() { if (_blurred) { _blurred = false; // startAnimating(); // controls.freeze = false; } }); window.addEventListener('blur', function() { // stopAnimating(); _blurred = true; controls.freeze = true; }); }
javascript
{ "resource": "" }
q45392
numberToCategory
train
function numberToCategory(value, buckets) { if (!buckets) { buckets = [-2, -2/3, 2/3, 2]; } if (typeof buckets.length === 'number' && buckets.length > 3) { if (value < buckets[0]) return 'very low'; if (value < buckets[1]) return 'low'; if (value < buckets[2]) return 'medium'; if (value < buckets[3]) return 'high'; if (value >= buckets[3]) return 'very high'; } var keys = Object.keys(buckets).sort(function(a, b) { return buckets[a] - buckets[b]; }), l = keys.length; for (var i = 0; i < l; i++) { if (value < buckets[keys[i]]) { return keys[i]; } } return keys[l-1]; }
javascript
{ "resource": "" }
q45393
percentRank
train
function percentRank(arr, v) { if (typeof v !== 'number') throw new TypeError('v must be a number'); for (var i = 0, l = arr.length; i < l; i++) { if (v <= arr[i]) { while (i < l && v === arr[i]) { i++; } if (i === 0) return 0; if (v !== arr[i-1]) { i += (v - arr[i-1]) / (arr[i] - arr[i-1]); } return i / l; } } return 1; }
javascript
{ "resource": "" }
q45394
getFittedPlaneNormal
train
function getFittedPlaneNormal(points, centroid) { var n = points.length, xx = 0, xy = 0, xz = 0, yy = 0, yz = 0, zz = 0; if (n < 3) throw new Error('At least three points are required to fit a plane'); var r = new THREE.Vector3(); for (var i = 0, l = points.length; i < l; i++) { r.copy(points[i]).sub(centroid); xx += r.x * r.x; xy += r.x * r.y; xz += r.x * r.z; yy += r.y * r.y; yz += r.y * r.z; zz += r.z * r.z; } var xDeterminant = yy*zz - yz*yz, yDeterminant = xx*zz - xz*xz, zDeterminant = xx*yy - xy*xy, maxDeterminant = Math.max(xDeterminant, yDeterminant, zDeterminant); if (maxDeterminant <= 0) throw new Error("The points don't span a plane"); if (maxDeterminant === xDeterminant) { r.set( 1, (xz*yz - xy*zz) / xDeterminant, (xy*yz - xz*yy) / xDeterminant ); } else if (maxDeterminant === yDeterminant) { r.set( (yz*xz - xy*zz) / yDeterminant, 1, (xy*xz - yz*xx) / yDeterminant ); } else if (maxDeterminant === zDeterminant) { r.set( (yz*xy - xz*yy) / zDeterminant, (xz*xy - yz*xx) / zDeterminant, 1 ); } return r.normalize(); }
javascript
{ "resource": "" }
q45395
bucketNumbersLinearly
train
function bucketNumbersLinearly(data, bucketCount, min, max) { var i = 0, l = data.length; // If min and max aren't given, set them to the highest and lowest data values if (typeof min === 'undefined') { min = Infinity; max = -Infinity; for (i = 0; i < l; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; } } var inc = (max - min) / bucketCount, buckets = new Array(bucketCount); // Initialize buckets for (i = 0; i < bucketCount; i++) { buckets[i] = []; } // Put the numbers into buckets for (i = 0; i < l; i++) { // Buckets include the lower bound but not the higher bound, except the top bucket try { if (data[i] === max) buckets[bucketCount-1].push(data[i]); else buckets[((data[i] - min) / inc) | 0].push(data[i]); } catch(e) { console.warn('Numbers in the data are outside of the min and max values used to bucket the data.'); } } return buckets; }
javascript
{ "resource": "" }
q45396
percentVariationExplainedByFittedPlane
train
function percentVariationExplainedByFittedPlane(vertices, centroid, normal, range) { var numVertices = vertices.length, diff = 0; for (var i = 0; i < numVertices; i++) { var fittedZ = Math.sqrt( (vertices[i].x - centroid.x) * (vertices[i].x - centroid.x) + (vertices[i].y - centroid.y) * (vertices[i].y - centroid.y) ) * Math.tan(normal.z * Math.PI) + centroid.z; diff += (vertices[i].z - fittedZ) * (vertices[i].z - fittedZ); } return 1 - Math.sqrt(diff / numVertices) * 2 / range; }
javascript
{ "resource": "" }
q45397
convolve
train
function convolve(src, kernel, tgt) { // src and kernel must be nonzero rectangular number arrays. if (!src.length || !kernel.length) return src; // Initialize tracking variables. var i = 0, // current src x-position j = 0, // current src y-position a = 0, // current kernel x-position b = 0, // current kernel y-position w = src.length, // src width l = src[0].length, // src length m = kernel.length, // kernel width n = kernel[0].length; // kernel length // If a target isn't passed, initialize it to an array the same size as src. if (typeof tgt === 'undefined') { tgt = new Array(w); for (i = 0; i < w; i++) { tgt[i] = new Float64Array(l); } } // The kernel is a rectangle smaller than the source. Hold it over the // source so that its top-left value sits over the target position. Then, // for each value in the kernel, multiply it by the value in the source // that it is sitting on top of. The target value at that position is the // sum of those products. // For each position in the source: for (i = 0; i < w; i++) { for (j = 0; j < l; j++) { var last = 0; tgt[i][j] = 0; // For each position in the kernel: for (a = 0; a < m; a++) { for (b = 0; b < n; b++) { // If we're along the right or bottom edges of the source, // parts of the kernel will fall outside of the source. In // that case, pretend the source value is the last valid // value we got from the source. This gives reasonable // results. The alternative is to drop the edges and end up // with a target smaller than the source. That is // unreasonable for some applications, so we let the caller // make that choice. if (typeof src[i+a] !== 'undefined' && typeof src[i+a][j+b] !== 'undefined') { last = src[i+a][j+b]; } // Multiply the source and the kernel at this position. // The value at the target position is the sum of these // products. tgt[i][j] += last * kernel[a][b]; } } } } return tgt; }
javascript
{ "resource": "" }
q45398
gauss
train
function gauss(x, s) { // 2.5066282746310005 is sqrt(2*pi) return Math.exp(-0.5 * x*x / (s*s)) / (s * 2.5066282746310005); }
javascript
{ "resource": "" }
q45399
gaussianKernel1D
train
function gaussianKernel1D(s, n) { if (typeof n !== 'number') n = 7; var kernel = new Float64Array(n), halfN = Math.floor(n * 0.5), odd = n % 2, i; if (!s || !n) return kernel; for (i = 0; i <= halfN; i++) { kernel[i] = gauss(s * (i - halfN - odd * 0.5), s); } for (; i < n; i++) { kernel[i] = kernel[n - 1 - i]; } return kernel; }
javascript
{ "resource": "" }