_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q35500
PointView
train
function PointView(geometryModel) { var self = this; // events to link var events = [ 'click', 'dblclick', 'mousedown', 'mouseover', 'mouseout', 'dragstart', 'drag', 'dragend' ]; this._eventHandlers = {}; this.model = geometryModel; this.points = []; var style = _.clone(geometryModel.get('style')) || {}; var iconAnchor = this.model.get('iconAnchor'); var icon = { url: this.model.get('iconUrl') || cdb.config.get('assets_url') + '/images/layout/default_marker.png', anchor: { x: iconAnchor && iconAnchor[0] || 10, y: iconAnchor && iconAnchor[1] || 10, } }; this.geom = new GeoJSON ( geometryModel.get('geojson'), { icon: icon, raiseOnDrag: false, crossOnDrag: false } ); // bind events var i; for(i = 0; i < events.length; ++i) { var e = events[i]; google.maps.event.addListener(this.geom, e, self._eventHandler(e)); } // link dragging this.bind('dragend', function(e, pos) { geometryModel.set({ geojson: { type: 'Point', // geojson is lng,lat coordinates: [pos[1], pos[0]] } }); }); }
javascript
{ "resource": "" }
q35501
train
function(index, columnName) { var r = this.at(index); if(!r) { return null; } return r.get(columnName); }
javascript
{ "resource": "" }
q35502
train
function() { this.$('tfoot').remove(); this.$('tr.noRows').remove(); // unbind rows before cleaning them when all are gonna be removed var rowView = null; while(rowView = this.rowViews.pop()) { // this is a hack to avoid all the elements are removed one by one rowView.unbind(null, null, this); // each element removes itself from rowViews rowView.clean(); } // clean all the html at the same time this.rowViews = []; }
javascript
{ "resource": "" }
q35503
train
function() { this.clear_rows(); if(! this.isEmptyTable()) { if(this.dataModel.fetched) { var self = this; this.dataModel.each(function(row) { self.addRow(row); }); } else { this._renderLoading(); } } else { this._renderEmpty(); } }
javascript
{ "resource": "" }
q35504
train
function(type, vis, data) { var t = Overlay._types[type]; if (!t) { cdb.log.error("Overlay: " + type + " does not exist"); return; } data.options = typeof data.options === 'string' ? JSON.parse(data.options): data.options; data.options = data.options || {} var widget = t(data, vis); if (widget) { widget.type = type; return widget; } return false; }
javascript
{ "resource": "" }
q35505
train
function(layers) { var mods = Layers.modulesForLayers(layers); return _.every(_.map(mods, function(m) { return cartodb[m] !== undefined; })); }
javascript
{ "resource": "" }
q35506
train
function() { var self = this; return _.compact(this.map.layers.map(function(layer) { return self.mapView.getLayerByCid(layer.cid); })); }
javascript
{ "resource": "" }
q35507
cartodbUrl
train
function cartodbUrl(opts) { var host = opts.host || 'carto.com'; var protocol = opts.protocol || 'https'; return protocol + '://' + opts.user + '.' + host + '/api/v1/viz/' + opts.table + '/viz.json'; }
javascript
{ "resource": "" }
q35508
_getLayerJson
train
function _getLayerJson(layer, callback) { var url = null; if(layer.layers !== undefined || ((layer.kind || layer.type) !== undefined)) { // layer object contains the layer data _.defer(function() { callback(layer); }); return; } else if(layer.table !== undefined && layer.user !== undefined) { // layer object points to cartodbjson url = cartodbUrl(layer); } else if(layer.indexOf) { // fetch from url url = layer; } if(url) { cdb.core.Loader.get(url, callback); } else { _.defer(function() { callback(null); }); } }
javascript
{ "resource": "" }
q35509
seq
train
function seq(to, from = 0, step = 1) { var result = []; var count = 0; if (to > from) for (let i = from; i < to; i += step) result[count++] = i; else for (let i = from; i > to; i -= step) result[count++] = i; return result; }
javascript
{ "resource": "" }
q35510
omit
train
function omit(a, elt) { var index = a.indexOf(elt); if (index !== -1) { a.splice(index, 1); } return a; }
javascript
{ "resource": "" }
q35511
replace
train
function replace(a, elt1, elt2) { var idx = a.indexOf(elt1); if (idx !== -1) { a[idx] = elt2; } return a; }
javascript
{ "resource": "" }
q35512
reverse
train
function reverse(a) { var len = a.length; for (var i = 0; i < Math.floor(len/2); i++) { [a[i], a[len-i-1]] = [a[len-i-1], a[i]]; } return a; }
javascript
{ "resource": "" }
q35513
flatten
train
function flatten(a) { function _reduce(a) { return a.reduce(_flatten, []); } function _flatten(a, b) { return a.concat(Array.isArray(b) ? _reduce(b) : b); } return _reduce(a); }
javascript
{ "resource": "" }
q35514
uniqueize
train
function uniqueize(a) { return a.filter((elt, i) => a.indexOf(elt) === i); }
javascript
{ "resource": "" }
q35515
indexesOf
train
function indexesOf(a, elt) { var ret = [], index = 0; while ((index = a.indexOf(elt, index)) !== -1) { ret.push(index++); } return ret; }
javascript
{ "resource": "" }
q35516
runningMap
train
function runningMap(a, fn, init) { return a.map(v => init = fn(v, init)); }
javascript
{ "resource": "" }
q35517
chainPromises
train
function chainPromises(...fns) { return [...fns].reduce( (result, fn) => result.then(fn), Promise.resolve() ); }
javascript
{ "resource": "" }
q35518
makeCounterMap
train
function makeCounterMap() { var map = new WeakMap(); return { init(obj) { map.set(obj, 0); }, incr(obj) { console.assert(map.has(obj), "Object must be in counter map."); map.set(obj, map.get(obj) + 1); }, get(obj) { return map.get(obj); } }; }
javascript
{ "resource": "" }
q35519
interleave
train
function interleave(...arrays) { var more = true; var n = 0; var result = []; while (more) { more = false; for (var array of arrays) { if (n >= array.length) continue; result.push(array[n]); more = true; } n++; } return result; }
javascript
{ "resource": "" }
q35520
getUniqueItemId
train
function getUniqueItemId(selector) { var base_id = selectorToId(selector), id = base_id, numeric_suffix = 0; while (used_item_ids.indexOf(id) !== -1) { id = base_id + "_" + ++numeric_suffix; } used_item_ids.push(id); return id; }
javascript
{ "resource": "" }
q35521
getUniqueSectionAnchor
train
function getUniqueSectionAnchor(anchor) { var base_anchor = anchor, numeric_suffix = 0; while (used_section_anchors.indexOf(anchor) !== -1) { anchor = base_anchor + "_" + ++numeric_suffix; } used_section_anchors.push(anchor); return anchor; }
javascript
{ "resource": "" }
q35522
getPreviewContainerStyle
train
function getPreviewContainerStyle(options) { var preview_container_style = ""; var padding_value = options.preview_padding; if (typeof padding_value === "number") { padding_value = [ padding_value ]; } if (isArray(padding_value)) { preview_container_style += "padding: " + padding_value.join("px ") + "px !important; "; } if (options.background_color) { preview_container_style += "background-color: " + options.background_color + " !important; "; } return preview_container_style.replace(/\s$/, "") || undefined; }
javascript
{ "resource": "" }
q35523
selectorToId
train
function selectorToId(selector) { var id = selector.replace(/[^a-z0-9_-]/ig, "_"); if (styledoc.item_id_trim_underscores) { id = id.replace(/_{2,}/g, "_").replace(/^_/, "").replace(/_$/, ""); } return id; }
javascript
{ "resource": "" }
q35524
on
train
function on(event, callback, context) { var events = eventsplitter.test(event) ? event.split(eventsplitter) : [event]; this.events = this.events || (this.events = {}); while (event = events.shift()) { if (!event) continue; (this.events[event] = this.events[event] || []).push({ context: context , callback: callback }); } return this; }
javascript
{ "resource": "" }
q35525
remove
train
function remove(handle) { return !( handle.callback === callback && (!context ? true : handle.context === context) ); }
javascript
{ "resource": "" }
q35526
call
train
function call(handle) { handle.callback.apply(handle.context, args); called = true; }
javascript
{ "resource": "" }
q35527
get
train
function get(attr) { if (!~attr.indexOf('.')) return this.attributes[attr]; var result = attr , structure = this.attributes; for (var paths = attr.split('.'), i = 0, length = paths.length; i < length && structure; i++) { result = structure[+paths[i] || paths[i]]; structure = result; } return result || this.attributes[attr]; }
javascript
{ "resource": "" }
q35528
train
function(state) { console.log('# Started batch process\n'); console.log('## Initial State:\n'); console.log('```'); console.log(JSON.stringify(sortKeys(state), null, 2)); console.log('```'); console.log('\n## Execution\n'); }
javascript
{ "resource": "" }
q35529
train
function(state, command, error) { console.log('> Failed to execute ``', command, '``' + withCmdPrefix(state) + ':'); console.log('```'); console.log(JSON.stringify(error, null, 2)); console.log('```'); }
javascript
{ "resource": "" }
q35530
train
function(state, command, output) { console.log('> Finished execution of ``', command, '``' + withCmdPrefix(state) + ':'); if (!Array.isArray(output)) output = [output]; console.log('```'); console.log(output.map(format).join('\n')); console.log('```'); }
javascript
{ "resource": "" }
q35531
train
function(state, error) { if (error) { console.log('\n## Finished with errors:\n'); console.log('```'); console.log(JSON.stringify(error, null, 2)); console.log('```'); } console.log('\n## Final State:\n'); console.log('```'); console.log(JSON.stringify(sortKeys(state), null, 2)); console.log('```'); }
javascript
{ "resource": "" }
q35532
sortKeys
train
function sortKeys(obj) { var sortedObj = {}; if (typeOf(obj) == 'object') { Object.keys(obj).sort().forEach(function(key) { sortedObj[key] = sortKeys(obj[key]); }); obj = sortedObj; } return obj; }
javascript
{ "resource": "" }
q35533
format
train
function format(obj) { var output; if (typeOf(obj) == 'object' || typeOf(obj) == 'array' || typeOf(obj) == 'null') { output = JSON.stringify(obj); } else if (typeOf(obj) != 'undefined') { output = obj.toString(); } else { output = ''; } return output; }
javascript
{ "resource": "" }
q35534
withCmdPrefix
train
function withCmdPrefix(state) { var prefix; if (state.options && state.options.cmdPrefix) { prefix = ' with ``' + state.options.cmdPrefix + '`` prefix'; } return prefix || ''; }
javascript
{ "resource": "" }
q35535
isMatching
train
function isMatching(result, expectation) { if (result.length !== expectation.length) { return false; } // convert results and expectations to strings for easier comparison result = result.map(item => item.toString()); expectation = expectation.map(item => getBox(item).toString()); const reduce_callback = function (previous_result, current_item) { return previous_result === true && result.indexOf(current_item) > -1; }; return expectation.reduce(reduce_callback, true); }
javascript
{ "resource": "" }
q35536
selfContained
train
function selfContained(collection) { const proto = getPrototypeOf(collection); /* istanbul ignore if */ if (!proto || getPrototypeOf(proto) !== ObjectPrototype) { // The loop below is insufficient. throw new Error(); } for (const key of getOwnPropertyNames(proto)) { defineProperty(collection, key, { value: collection[key] }); } return collection; }
javascript
{ "resource": "" }
q35537
makeModuleKeys
train
function makeModuleKeys(moduleIdentifier) { // Allocate a public/private key pair. function privateKey(fun) { const previous = hidden; hidden = privateKey; try { return fun(); } finally { hidden = previous; } } function publicKey() { return hidden === privateKey; } publicKeys.add(publicKey); // Allow a private key to be used in lieu of the pair. defineProperty( privateKey, 'publicKey', { value: publicKey, enumerable: true }); // We attach a module identifier to the public key to enable // whitelisting based on strings in a configuration without having // to load modules before storing their public key in a set. defineProperties( publicKey, { moduleIdentifier: { value: `${ moduleIdentifier }`, enumerable: true }, call: { value: fCall, enumerable: true }, apply: { value: fApply, enumerable: true }, }); /** * Wraps a value in a box so that only an approved * opener may unbox it. * * @param {*} value the value that will be given to * an approved unboxer. * @param {!function(function():boolean):boolean} mayOpen * receives the public key of the opener. * Should return `true` to allow. * This will be called in the context of the opener's * private key, so the public key should also return true * called with no arguments. * @return {!Box} a box that is opaque to any receivers that cannot * unbox it. */ function box(value, mayOpen) { if (typeof mayOpen !== 'function') { throw new TypeError(`Expected function not ${ mayOpen }`); } // Allocate an opaque token const newBox = new Box(); boxes.set( newBox, freeze({ boxerPriv: privateKey, boxerPub: publicKey, value, mayOpen })); return newBox; } /** * Tries to open a box. * * @param {*} box the box to unbox. * @param {?function(function():boolean):boolean} ifFrom * if the box may be opened by this unboxer's owner, * then ifFrom receives the publicKey of the box creator. * It should return true to allow unboxing to proceed. * @param {*} fallback a value to substitute if unboxing failed. * Defaults to undefined. * @return {*} the value if unboxing is allowed or fallback otherwise. */ function unbox(box, ifFrom, fallback) { // eslint-disable-line no-shadow if (ifFrom == null) { // eslint-disable-line ifFrom = () => true; } if (typeof ifFrom !== 'function') { throw new TypeError(`Expected function not ${ ifFrom }`); } const boxData = boxes.get(box); if (!boxData) { return fallback; } const { boxerPriv, boxerPub, value, mayOpen } = boxData; // Require mutual consent // TODO: Is this the object identity equivalent of an // out-of-order verify/decrypt fault? // http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html return (privateKey(() => mayOpen(publicKey)) === true && boxerPriv(() => ifFrom(boxerPub)) === true) ? value : fallback; } const neverBoxed = {}; /** * Like unbox but raises an exception if unboxing fails. * @param {*} box the box to unbox. * @param {?function(function():boolean):boolean} ifFrom * if the box may be opened by this unboxer's owner, * then ifFrom receives the publicKey of the box creator. * It should return true to allow unboxing to proceed. * @return {*} the value if unboxing is allowed or fallback otherwise. */ function unboxStrict(box, ifFrom) { // eslint-disable-line no-shadow const result = unbox(box, ifFrom, neverBoxed); if (result === neverBoxed) { throw new Error('Could not unbox'); } return result; } return defineProperties( create(null), { // These close over private keys, so do not leak them. box: { value: box, enumerable: true }, unbox: { value: unbox, enumerable: true }, unboxStrict: { value: unboxStrict, enumerable: true }, privateKey: { value: privateKey, enumerable: true }, isPublicKey: { value: isPublicKey, enumerable: true }, // Modules may allow access to this, perhaps via module object. // See cjs/index.js. publicKey: { value: publicKey, enumerable: true }, [publicKeySymbol]: { value: publicKey, enumerable: true }, }); }
javascript
{ "resource": "" }
q35538
box
train
function box(value, mayOpen) { if (typeof mayOpen !== 'function') { throw new TypeError(`Expected function not ${ mayOpen }`); } // Allocate an opaque token const newBox = new Box(); boxes.set( newBox, freeze({ boxerPriv: privateKey, boxerPub: publicKey, value, mayOpen })); return newBox; }
javascript
{ "resource": "" }
q35539
unbox
train
function unbox(box, ifFrom, fallback) { // eslint-disable-line no-shadow if (ifFrom == null) { // eslint-disable-line ifFrom = () => true; } if (typeof ifFrom !== 'function') { throw new TypeError(`Expected function not ${ ifFrom }`); } const boxData = boxes.get(box); if (!boxData) { return fallback; } const { boxerPriv, boxerPub, value, mayOpen } = boxData; // Require mutual consent // TODO: Is this the object identity equivalent of an // out-of-order verify/decrypt fault? // http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html return (privateKey(() => mayOpen(publicKey)) === true && boxerPriv(() => ifFrom(boxerPub)) === true) ? value : fallback; }
javascript
{ "resource": "" }
q35540
unboxStrict
train
function unboxStrict(box, ifFrom) { // eslint-disable-line no-shadow const result = unbox(box, ifFrom, neverBoxed); if (result === neverBoxed) { throw new Error('Could not unbox'); } return result; }
javascript
{ "resource": "" }
q35541
result
train
function result(rule) { var r = {} var reserved = ['filename', 'exists', 'grep', 'jsonKeyExists'] Object.keys(rule).forEach(function(key) { if (reserved.indexOf(key) !== -1) return r[key] = rule[key] }) return r }
javascript
{ "resource": "" }
q35542
scheduleServerConnectivityChecks
train
function scheduleServerConnectivityChecks() { if (connectivityIntervalId === null) { connectivityIntervalId = asyncExecService.setInterval(function () { updateRegistrations(); connectToServers(); }, INTERVAL_BETWEEN_SERVER_CONNECTIVITY_CHECKS); } else { throw new Error("BUG ::: Attempt was made to start connectivity checks twice"); } }
javascript
{ "resource": "" }
q35543
connectToServers
train
function connectToServers() { var knownServers = signallingServerSelector.getServerSpecsInPriorityOrder(); for (var i = 0; i < knownServers.length; i++) { var connectionsRemaining = signallingServerService.getPreferredNumberOfSockets() - Object.keys(connectedSockets).length; // // We have enough connections // if (connectionsRemaining === 0) { break; } // // Try to connect to a new server // var serverSpec = knownServers[i]; if (!currentlyConnectedToServer(serverSpec)) { var socket; try { socket = socketFactory.createSocket(serverSpec); storeSocket(serverSpec, socket); addListeners(socket, serverSpec); loggingService.info("Attempting to connect to signalling server (" + serverSpec.signallingApiBase + ")"); } catch (error) { loggingService.error("Error connecting to socket " + serverSpec.signallingApiBase, error); } } } // // Store the new set of connected servers in session storage so we // can prefer them in the event of a reload // signallingServerSelector.setLastConnectedServers(getListOfCurrentSignallingApiBases()); }
javascript
{ "resource": "" }
q35544
storeSocket
train
function storeSocket(spec, socket) { connectedSpecs[spec.signallingApiBase] = spec; connectedSockets[spec.signallingApiBase] = socket; }
javascript
{ "resource": "" }
q35545
addListeners
train
function addListeners(socket, serverSpec) { var apiBase = serverSpec.signallingApiBase; var disposeFunction = disposeOfSocket(apiBase); var registerFunction = register(socket); // Register if we connect socket.on("connect", registerFunction); // Dispose if we disconnect/fail to connect/error socket.io.on("connect_error", disposeFunction); socket.on("error", disposeFunction); socket.on("disconnect", disposeFunction); /** * Emit offers/answers when they're received */ socket.on("answer", emitAnswer); socket.on("offer", emitOffer); socket.on("candidates", emitCandidates); }
javascript
{ "resource": "" }
q35546
disposeOfSocket
train
function disposeOfSocket(apiBase) { return function (error) { loggingService.warn("Got disconnected from signalling server (" + apiBase + ")", error); var socket = connectedSockets[apiBase]; if (socket) { stopConnectivityChecks(); socket.removeAllListeners(); socket.io.removeAllListeners(); try { socket.disconnect(); } catch (ignore) { } deleteSocket(apiBase); if (!unloadInProgress) { connectAndMonitor(); } } else { throw new Error("BUG ::: Disconnected from a socket we're not connected to?!"); } }; }
javascript
{ "resource": "" }
q35547
parseGlyphCoordinate
train
function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { var v; if ((flag & shortVectorBitMask) > 0) { // The coordinate is 1 byte long. v = p.parseByte(); // The `same` bit is re-used for short values to signify the sign of the value. if ((flag & sameBitMask) === 0) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if ((flag & sameBitMask) > 0) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parseShort(); } } return v; }
javascript
{ "resource": "" }
q35548
transformPoints
train
function transformPoints(points, transform) { var newPoints, i, pt, newPt; newPoints = []; for (i = 0; i < points.length; i += 1) { pt = points[i]; newPt = { x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; }
javascript
{ "resource": "" }
q35549
getPath
train
function getPath(points) { var p, contours, i, realFirstPoint, j, contour, pt, firstPt, prevPt, midPt, curvePt, lastPt; p = new path.Path(); if (!points) { return p; } contours = getContours(points); for (i = 0; i < contours.length; i += 1) { contour = contours[i]; firstPt = contour[0]; lastPt = contour[contour.length - 1]; if (firstPt.onCurve) { curvePt = null; // The first point will be consumed by the moveTo command, // so skip it in the loop. realFirstPoint = true; } else { if (lastPt.onCurve) { // If the first point is off-curve and the last point is on-curve, // start at the last point. firstPt = lastPt; } else { // If both first and last points are off-curve, start at their middle. firstPt = { x: (firstPt.x + lastPt.x) / 2, y: (firstPt.y + lastPt.y) / 2 }; } curvePt = firstPt; // The first point is synthesized, so don't skip the real first point. realFirstPoint = false; } p.moveTo(firstPt.x, firstPt.y); for (j = realFirstPoint ? 1 : 0; j < contour.length; j += 1) { pt = contour[j]; prevPt = j === 0 ? firstPt : contour[j - 1]; if (prevPt.onCurve && pt.onCurve) { // This is a straight line. p.lineTo(pt.x, pt.y); } else if (prevPt.onCurve && !pt.onCurve) { curvePt = pt; } else if (!prevPt.onCurve && !pt.onCurve) { midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; p.quadraticCurveTo(prevPt.x, prevPt.y, midPt.x, midPt.y); curvePt = pt; } else if (!prevPt.onCurve && pt.onCurve) { // Previous point off-curve, this point on-curve. p.quadraticCurveTo(curvePt.x, curvePt.y, pt.x, pt.y); curvePt = null; } else { throw new Error('Invalid state.'); } } if (firstPt !== lastPt) { // Connect the last and first points if (curvePt) { p.quadraticCurveTo(curvePt.x, curvePt.y, firstPt.x, firstPt.y); } else { p.lineTo(firstPt.x, firstPt.y); } } } p.closePath(); return p; }
javascript
{ "resource": "" }
q35550
parseGlyfTable
train
function parseGlyfTable(data, start, loca) { var glyphs, i, j, offset, nextOffset, glyph, component, componentGlyph, transformedPoints; glyphs = []; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { offset = loca[i]; nextOffset = loca[i + 1]; // console.log('pg: ', offset, nextOffset); if (offset !== nextOffset) { glyphs.push(parseGlyph(data, i, start + offset)); } else { glyphs.push(new Glyph(i)); } } // console.log(start); // Go over the glyphs again, resolving the composite glyphs. for (i = 0; i < glyphs.length; i += 1) { glyph = glyphs[i]; if (glyph.isComposite) { for (j = 0; j < glyph.components.length; j += 1) { component = glyph.components[j]; componentGlyph = glyphs[component.glyphIndex]; if (componentGlyph.points) { transformedPoints = transformPoints(componentGlyph.points, component); glyph.points = glyph.points.concat(transformedPoints); } } } glyph.path = getPath(glyph.points); } return glyphs; }
javascript
{ "resource": "" }
q35551
Salesforce
train
function Salesforce(username, password, token, wsdl) { //Required NodeJS libraries this.q = require("q"); this.soap = require("soap"); //Salesforce access data this.username = username; this.password = password; this.token = token; this.wsdl = wsdl || "./node_modules/soap_salesforce/wsdl/enterprise.xml"; //Other properties this.promise; //A promise will be used for returning soapClient after finishing Salesforce login this.soapClient; //Salesforce SOAP client instance will be stored here }
javascript
{ "resource": "" }
q35552
AddCallback
train
function AddCallback(mesgId, callbackFunction, callbackTimeout) { var callbackElement, now; now = new Date().getTime(); callbackElement = { id : mesgId, func : callbackFunction, timeout : now + callbackTimeout }; callbackList.push(callbackElement); }
javascript
{ "resource": "" }
q35553
ParseReply
train
function ParseReply(mesgId, data, sid) { var i; for(i = 0 ; i < callbackList.length ; i++) { if(callbackList[i].id.toString() === mesgId.toString() ) { callbackList[i].func(data, sid); } } }
javascript
{ "resource": "" }
q35554
GetOnEvent
train
function GetOnEvent(title) { var retList, i; retList = []; for(i = 0 ; i < onList.length ; i++) { if(onList[i].event.toString() === title.toString()) { retList.push(onList[i].callback); } } return retList; }
javascript
{ "resource": "" }
q35555
msg
train
function msg(str) { if (str == null) { return null; } for (var i = 1, len = arguments.length; i < len; ++i) { str = str.replace('{' + (i - 1) + '}', String(arguments[i])); } return str; }
javascript
{ "resource": "" }
q35556
tpl_apply_with_register_helper
train
function tpl_apply_with_register_helper(Handlebars, template_path, data_obj, dest_file_path) { var rs = fs.createReadStream(template_path, {bufferSize: 11}); var bufferHelper = new BufferHelper(); rs.on("data", function (trunk){ bufferHelper.concat(trunk); }); rs.on("end", function () { var source = bufferHelper.toBuffer().toString('utf8'); var template = Handlebars.compile(source); // log(template); var content = template(data_obj); fs.writeFile(dest_file_path, content , function (err) { if (err) throw err; log('It\'s saved!'); }); }); }
javascript
{ "resource": "" }
q35557
AssociationManager
train
function AssociationManager(options) { var self = this; self.associationsRootUrl = options.associationsRootUrl || SNIFFYPEDIA_ROOT_URL; var datafolder = options.persistentDataFolder || DEFAULT_DATA_FOLDER; var filename = ASSOCIATION_DB; if(options.persistentDataFolder !== '') { filename = datafolder.concat('/' + filename); } self.db = new nedb({ filename: filename, autoload: true }); self.db.insert(TEST_TRANSMITTER); self.db.insert(TEST_RECEIVER_0); self.db.insert(TEST_RECEIVER_1); self.db.insert(TEST_RECEIVER_2); self.db.insert(TEST_RECEIVER_3); }
javascript
{ "resource": "" }
q35558
getAssociations
train
function getAssociations(instance, ids, callback) { instance.db.find({ _id: { $in: ids } }, function(err, associations) { for(var cAssociation = 0; cAssociation < associations.length; cAssociation++) { associations[cAssociation].deviceId = associations[cAssociation]._id; } callback(err, associations); }); }
javascript
{ "resource": "" }
q35559
extractRadioDecoders
train
function extractRadioDecoders(devices) { var radioDecoders = {}; for(var deviceId in devices) { var radioDecodings = devices[deviceId].radioDecodings || []; for(var cDecoding = 0; cDecoding < radioDecodings.length; cDecoding++) { var radioDecoder = radioDecodings[cDecoding].identifier; var radioDecoderId = radioDecoder.value; radioDecoders[radioDecoderId] = { identifier: radioDecoder }; } } return radioDecoders; }
javascript
{ "resource": "" }
q35560
extractAssociationIds
train
function extractAssociationIds(devices) { var associationIds = []; for(var deviceId in devices) { var device = devices[deviceId]; var hasAssociationIds = device.hasOwnProperty("associationIds"); if(!hasAssociationIds) { device.associationIds = reelib.tiraid.getAssociationIds(device); } for(var cId = 0; cId < device.associationIds.length; cId++) { if(associationIds.indexOf(device.associationIds[cId]) < 0) { associationIds.push(device.associationIds[cId]); } } } return associationIds; }
javascript
{ "resource": "" }
q35561
subMatrix
train
function subMatrix (data, numRows, numCols, row, col) { var sub = [] for (var i = 0; i < numRows; i++) { for (var j = 0; j < numCols; j++) { if ((i !== row) && (j !== col)) { sub.push(data[matrixToArrayIndex(i, j, numCols)]) } } } return sub }
javascript
{ "resource": "" }
q35562
determinant
train
function determinant (data, scalar, order) { // Recursion will stop here: // the determinant of a 1x1 matrix is its only element. if (data.length === 1) return data[0] if (no(order)) order = Math.sqrt(data.length) if (order % 1 !== 0) { throw new TypeError('data.lenght must be a square') } // Default to common real number field. if (no(scalar)) { scalar = { addition: function (a, b) { return a + b }, multiplication: function (a, b) { return a * b }, negation: function (a) { return -a } } } var det // TODO choose best row or column to start from, i.e. the one with more zeros // by now we start from first row, and walk by column // needs scalar.isZero // // is scalar.isZero is a function will be used, but should remain optional var startingRow = 0 for (var col = 0; col < order; col++) { var subData = subMatrix(data, order, order, startingRow, col) // +-- Recursion here. // ↓ var cofactor = determinant(subData, scalar, order - 1) if ((startingRow + col) % 2 === 1) { cofactor = scalar.negation(cofactor) } var index = matrixToArrayIndex(startingRow, col, order) if (no(det)) { det = scalar.multiplication(data[index], cofactor) // first iteration } else { det = scalar.addition(det, scalar.multiplication(data[index], cofactor)) } } return det }
javascript
{ "resource": "" }
q35563
notifyAccess
train
function notifyAccess({object, name}) { // Create an observer for changes in properties accessed during execution of this function. function makeAccessedObserver() { return Observer(object, function(changes) { changes.forEach(({type, name}) => { var {names} = accessEntry; if (!names || type === 'update' && names.indexOf(name) !== -1) rerun(); }); }); } // Make a new entry in the access table, containing initial property name if any // and observer for properties accessed on the object. function makeAccessEntry() { accesses.set(object, { names: name ? [name] : null, observer: makeAccessedObserver() }); } // If properties on this object are already being watched, there is already an entry // in the access table for it. Add a new property name to the existing entry. function setAccessEntry() { if (name && accessEntry.names) accessEntry.names.push(name); else accessEntry.names = null; } var accessEntry = accesses.get(object); if (accessEntry) setAccessEntry(); else makeAccessEntry(); }
javascript
{ "resource": "" }
q35564
makeAccessedObserver
train
function makeAccessedObserver() { return Observer(object, function(changes) { changes.forEach(({type, name}) => { var {names} = accessEntry; if (!names || type === 'update' && names.indexOf(name) !== -1) rerun(); }); }); }
javascript
{ "resource": "" }
q35565
makeAccessEntry
train
function makeAccessEntry() { accesses.set(object, { names: name ? [name] : null, observer: makeAccessedObserver() }); }
javascript
{ "resource": "" }
q35566
setAccessEntry
train
function setAccessEntry() { if (name && accessEntry.names) accessEntry.names.push(name); else accessEntry.names = null; }
javascript
{ "resource": "" }
q35567
fromSFComponent
train
function fromSFComponent(component, name, initialClassNameMap) { var hooksList = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var flatted = {}; function collect(component, name, initialClassNameMap) { var newComp = makeStylable(component, initialClassNameMap(name), name, hooks(hooksList)); flat(name, newComp); component.children && Object.keys(component.children).forEach(function (child) { collect(component.children[child], name + "_" + child, initialClassNameMap); }); } function flat(name, comp) { flatted[name] = comp; } collect(component, name, initialClassNameMap); return createStyleContext(flatted, hooks(hooksList)); }
javascript
{ "resource": "" }
q35568
filterByVersion
train
function filterByVersion(browsers, version) { version = String(version); if (version === 'latest' || version === 'oldest') { const filtered = numericVersions(browsers); const i = version === 'latest' ? filtered.length - 1 : 0; const value = filtered[i].short_version; return filtered.filter((el) => el.short_version === value); } const splits = version.split('..'); if (splits.length === 2) { const versions = browsers.map((el) => el.short_version); const start = splits[0]; const end = splits[1]; let startIndex = 0; let endIndex = browsers.length - 1; if (end === 'latest') endIndex = numericVersions(browsers).length - 1; else endIndex = versions.lastIndexOf(end); if (start < 0) startIndex = endIndex + Number(start); else if (start !== 'oldest') startIndex = versions.indexOf(start); if (startIndex < 0) { throw new Error(`Unable to find start version: ${start}`); } if (endIndex < 0) throw new Error(`Unable to find end version: ${end}`); return browsers.slice(startIndex, endIndex + 1); } return browsers.filter((el) => { return el.short_version === version || el.short_version === `${version}.0`; }); }
javascript
{ "resource": "" }
q35569
transform
train
function transform(wanted, available) { const browsers = new Set(); wanted.forEach((browser) => { const name = browser.name.toLowerCase(); if (!available.has(name)) { throw new Error(`Browser ${name} is not available`); } let list = available.get(name).slice().sort(compare); let platforms = browser.platform; if (platforms === undefined) { // // Remove all duplicate versions. // const filtered = [list[0]]; for (let i = 1; i < list.length; i++) { if (list[i].short_version !== list[i - 1].short_version) { filtered.push(list[i]); } } list = filtered; } else { if (!Array.isArray(platforms)) platforms = [platforms]; // // Filter out unwanted platforms. // platforms = platforms.map((el) => String(el).toLowerCase()); list = list.filter((el) => ~platforms.indexOf(el.os.toLowerCase())); } if (list.length === 0) return; let versions = browser.version; if (versions === undefined) { list.forEach((el) => browsers.add(el)); } else { if (!Array.isArray(versions)) versions = [versions]; versions.forEach((version) => { filterByVersion(list, version).forEach((el) => browsers.add(el)); }); } }); return Array.from(browsers); }
javascript
{ "resource": "" }
q35570
aggregate
train
function aggregate(browsers) { const map = new Map(); browsers.forEach((browser) => { const name = browser.api_name.toLowerCase(); let value = map.get(name); if (value === undefined) { value = []; map.set(name, value); } value.push(browser); }); const ie = map.get('internet explorer'); map.set('iexplore', ie).set('ie', ie); map.set('googlechrome', map.get('chrome')); return map; }
javascript
{ "resource": "" }
q35571
sauceBrowsers
train
function sauceBrowsers(wanted) { return got({ path: '/rest/v1/info/platforms/webdriver', hostname: 'saucelabs.com', protocol: 'https:', json: true }).then((res) => { if (wanted === undefined) return res.body; return transform(wanted, aggregate(res.body)); }); }
javascript
{ "resource": "" }
q35572
AbsyncProvider
train
function AbsyncProvider( $provide, absyncCache ) { var self = this; // Store a reference to the provide provider. self.__provide = $provide; // Store a reference to the cache service constructor. self.__absyncCache = absyncCache; // A reference to the socket.io instance we're using to receive updates from the server. self.__ioSocket = null; // We usually register event listeners on the socket.io instance right away. // If socket.io was not connected when a service was constructed, we put the registration request // into this array and register it as soon as socket.io is configured. self.__registerLater = []; // References to all registered event listeners. self.__listeners = []; // The collections that absync provides. // The keys are the names of the collections, the value contains the constructor of // the respective cache service. self.__collections = {}; // The entities that absync provides. // The keys are the names of the entities, the value contains the constructor of // the respective cache service. self.__entities = {}; // Debug should either be set through a configure() call, or on instantiated services. self.debug = undefined; }
javascript
{ "resource": "" }
q35573
onCollectionReceived
train
function onCollectionReceived( serverResponse ) { if( !serverResponse.data[ configuration.collectionName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.collectionName + "'." ); } self.__entityCacheRaw = serverResponse.data; self.entityCache.splice( 0, self.entityCache.length ); return self.__onDataAvailable( serverResponse.data ); }
javascript
{ "resource": "" }
q35574
onCollectionRetrievalFailure
train
function onCollectionRetrievalFailure( serverResponse ) { self.logInterface.error( self.logPrefix + "Unable to retrieve the collection from the server.", serverResponse ); self.__entityCacheRaw = null; self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
{ "resource": "" }
q35575
onSingleEntityReceived
train
function onSingleEntityReceived( serverResponse ) { if( !serverResponse.data[ configuration.entityName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.entityName + "'." ); } self.__entityCacheRaw = serverResponse.data; self.__onDataAvailable( serverResponse.data ); }
javascript
{ "resource": "" }
q35576
onEntityRetrieved
train
function onEntityRetrieved( serverResponse ) { if( !serverResponse.data[ configuration.entityName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.entityName + "'." ); } var rawEntity = serverResponse.data[ configuration.entityName ]; // Put the raw entity into our raw entity cache. // We keep the raw copy to allow caching of the raw data. self.__cacheMaintain( self.__entityCacheRaw[ configuration.collectionName || configuration.entityName ], rawEntity, "update", false ); // Deserialize the object and place it into the cache. // We do not need to check here if the object already exists in the cache. // While it could be possible that the same entity is retrieved multiple times, __updateCacheWithEntity // will not insert duplicates into the cache. var deserialized = self.deserializer( rawEntity ); self.__updateCacheWithEntity( deserialized ); return deserialized; }
javascript
{ "resource": "" }
q35577
onEntityRetrievalFailure
train
function onEntityRetrievalFailure( serverResponse ) { self.logInterface.error( self.logPrefix + "Unable to retrieve entity with ID '" + id + "' from the server.", serverResponse ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
{ "resource": "" }
q35578
afterEntityStored
train
function afterEntityStored( returnResult, serverResponse ) { var self = this; // Writing an entity to the backend will usually invoke an update event to be // broadcast over websockets, where we would also retrieve the updated record. // We still put the updated record we receive here into the cache to ensure early consistency, if that is requested. if( !returnResult && !self.forceEarlyCacheUpdate ) { return; } if( serverResponse.data[ configuration.entityName ] ) { var rawEntity = serverResponse.data[ configuration.entityName ]; // If early cache updates are forced, put the return entity into the cache. if( self.forceEarlyCacheUpdate ) { var newEntity = self.deserializer( rawEntity ); self.__updateCacheWithEntity( newEntity ); if( returnResult ) { return newEntity; } } if( returnResult ) { return rawEntity; } } }
javascript
{ "resource": "" }
q35579
onEntityStorageFailure
train
function onEntityStorageFailure( serverResponse ) { var self = this; self.logInterface.error( self.logPrefix + "Unable to store entity on the server.", serverResponse ); self.logInterface.error( serverResponse ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
{ "resource": "" }
q35580
onEntityDeleted
train
function onEntityDeleted( serverResponse ) { self.__cacheMaintain( self.__entityCacheRaw[ configuration.collectionName || configuration.entityName ], entity, "delete", false ); return self.__removeEntityFromCache( entityId ); }
javascript
{ "resource": "" }
q35581
onEntityDeletionFailed
train
function onEntityDeletionFailed( serverResponse ) { self.logInterface.error( serverResponse.data ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
{ "resource": "" }
q35582
decompress
train
function decompress( buffer ) { var chunks = [] var chunkType = ADC.CHUNK_UNKNOWN var position = 0 var length = 0 windowOffset = 0 while( position < buffer.length ) { chunkType = ADC.getChunkType( buffer[ position ] ) length = ADC.getSequenceLength( buffer[ position ] ) switch( chunkType ) { case ADC.CHUNK_DATA: chunks.push( decodeData( window, buffer, position ) ) break case ADC.CHUNK_THREE: chunks.push( decodeRunlength( window, buffer, position ) ) break case ADC.CHUNK_TWO: chunks.push( decodeRunlength( window, buffer, position ) ) break default: throw new Error( 'Unknown chunk type 0x' + buffer[ position ].toString(16) + ' at ' + position ) } position += length } return Buffer.concat( chunks ) }
javascript
{ "resource": "" }
q35583
train
function(schema, from) { return function(next) { var self = this; var funcs = []; for (var key in from) { var items = from[key]; var model = mongoose.model(schema.path(key).options.ref); funcs.push(function(callback) { model.findOne({ _id: self[key] }, function(err, instance) { if (err) return callback(err); items.forEach(function(item) { self[item.key] = instance[item.field]; }); callback(); }); }); } async.parallel(funcs, function(err) { if (err) return next(err); next(); }); }; }
javascript
{ "resource": "" }
q35584
train
function (result) { // don't send a second response if (responseHasBeenSent) { console.warn('JSON-RPC2 response has already been sent.') return } // notifications should not send error responses (JSON-RPC2 specs) if (!isMethodCall) { logNotificationResponseWarning(result, requestMessage) callback() return } // result should not be undefined if (result === undefined) { console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)') result = '' } var rpcMessage = { jsonrpc: '2.0', result: result, id: id } callback(rpcMessage) responseHasBeenSent = true }
javascript
{ "resource": "" }
q35585
train
function (method, result) { // result should not be undefined if (result === undefined) { console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)') result = '' } var rpcMessage = { jsonrpc: '2.0', result: result, id: id } callback(rpcMessage) responseHasBeenSent = true }
javascript
{ "resource": "" }
q35586
train
function (error, type) { // don't send a second response if (responseHasBeenSent) { console.warn('JSON-RPC2 response has already been sent.') return } // notifications should not send error responses (JSON-RPC2 specs) if (!isMethodCall) { var message = (error && error.toString) ? error.toString() : undefined logNotificationResponseWarning(message, requestMessage) callback() return } // internals var errorObject if (error instanceof Error) { // serious application error console.warn( 'Error in JSON-RPC2 method ' + methodName + ': ' + error.toString() + '\n' + error.stack ) // not sending detailed error info to not expose details about server code errorObject = { code: errorCodes['APPLICATION_ERROR'], message: errorMessages['APPLICATION_ERROR'] + ' (Check server logs for details)' } } else if (typeof error === 'string') { // error message errorObject = { code: errorCodes[type] || errorCodes['INVALID_REQUEST'], message: error } } else if (typeof error === 'object') { if (error.message) { // error object errorObject = error if (error.code === undefined) { error.code = errorCodes['INVALID_REQUEST'] } } else { // error data errorObject = { code: errorCodes[type] || errorCodes['INVALID_REQUEST'], message: errorMessages[type] || errorMessages['INVALID_REQUEST'], data: error } } } else { if (error !== undefined) { console.warn('Error parameter must be a string (error message) or object (error data)') } // fallback errorObject = errorObjects['INVALID_REQUEST'] } var rpcMessage = { jsonrpc: '2.0', error: errorObject, id: id } callback(rpcMessage) responseHasBeenSent = true }
javascript
{ "resource": "" }
q35587
merge
train
function merge(obj1, obj2) { var obj3 = {}, index; for (index in obj1) { obj3[index] = obj1[index]; } for (index in obj2) { obj3[index] = obj2[index]; } return obj3; }
javascript
{ "resource": "" }
q35588
parseData
train
function parseData(data) { var tmp_data = {}; if (nlib.isString(data)) { if (data.match(/\.json/i) && grunt.file.exists(data)) { tmp_data = grunt.file.readJSON(data); } else if (data.match(/\.ya?ml/i) && grunt.file.exists(data)) { tmp_data = grunt.file.readYAML(data); } else { tmp_data = data; } } else if (nlib.isObject(data) || nlib.isArray(data)) { for (var i in data) { if (nlib.isString(data[i])) { var parsed = parseData(data[i]); if (nlib.isString(parsed)) { tmp_data[i] = parsed; } else { tmp_data = merge(tmp_data, parsed); } } else { tmp_data = merge(tmp_data, data[i]); } } } return tmp_data; }
javascript
{ "resource": "" }
q35589
inOp
train
function inOp(a, b) { return b .trim() // remove leading and trailing space chars .replace(/\s*,\s*/g, ',') // remove any white-space chars from around commas .split(',') // put in an array .indexOf((a + '')); // search array whole matches }
javascript
{ "resource": "" }
q35590
GenericService
train
function GenericService(serviceId) { var self = this; var id = serviceId; var data = {}; /** * Method called by PK * * @param {Object} sharedData - Data object that gets passed-around by PK */ this.doStuff = function (sharedData) { console.log("In service #" + id + ", a = " + sharedData.a + " and b = " + sharedData.b); if(SERVICE_ALWAYS_FAILS) { var err = new Error("Service failed", "Service failed - it always does!"); onServiceError(err, sharedData); } else { if(id != BAD_SERVICE_ID) { data = {"id": id}; onServiceSuccess(data, sharedData); } else { var err = new Error("Service " + BAD_SERVICE_ID + " failed", "Service " + BAD_SERVICE_ID + " failed - it always does!"); onServiceError(err, sharedData); } } }; /** * @private * @param {Object} data * @param {Object} sharedData */ function onServiceSuccess(data, sharedData) { console.log("In GenericService" + id + ".onServiceSuccess: " + JSON.stringify(data)); sharedData[id] = {value: "This is the result from successful service #" + id}; self.emit("success", data); } /** * @private * @param err * @param {Object} sharedData */ function onServiceError(err, sharedData) { console.log("In GenericService" + id + ".onServiceError: " + JSON.stringify(err)); sharedData[id] = {value: "This is the result from failed service #" + id}; self.emit("error", err); } }
javascript
{ "resource": "" }
q35591
RegionOfInterestConfig
train
function RegionOfInterestConfig(regionOfInterestConfigDict){ if(!(this instanceof RegionOfInterestConfig)) return new RegionOfInterestConfig(regionOfInterestConfigDict) regionOfInterestConfigDict = regionOfInterestConfigDict || {} // Check regionOfInterestConfigDict has the required fields // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMin', regionOfInterestConfigDict.occupancyLevelMin); // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMed', regionOfInterestConfigDict.occupancyLevelMed); // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMax', regionOfInterestConfigDict.occupancyLevelMax); // // checkType('int', 'regionOfInterestConfigDict.occupancyNumFramesToEvent', regionOfInterestConfigDict.occupancyNumFramesToEvent); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMin', regionOfInterestConfigDict.fluidityLevelMin); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMed', regionOfInterestConfigDict.fluidityLevelMed); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMax', regionOfInterestConfigDict.fluidityLevelMax); // // checkType('int', 'regionOfInterestConfigDict.fluidityNumFramesToEvent', regionOfInterestConfigDict.fluidityNumFramesToEvent); // // checkType('boolean', 'regionOfInterestConfigDict.sendOpticalFlowEvent', regionOfInterestConfigDict.sendOpticalFlowEvent); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToEvent', regionOfInterestConfigDict.opticalFlowNumFramesToEvent); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToReset', regionOfInterestConfigDict.opticalFlowNumFramesToReset); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowAngleOffset', regionOfInterestConfigDict.opticalFlowAngleOffset); // // Init parent class RegionOfInterestConfig.super_.call(this, regionOfInterestConfigDict) // Set object properties Object.defineProperties(this, { occupancyLevelMin: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMin }, occupancyLevelMed: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMed }, occupancyLevelMax: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMax }, occupancyNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyNumFramesToEvent }, fluidityLevelMin: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMin }, fluidityLevelMed: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMed }, fluidityLevelMax: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMax }, fluidityNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityNumFramesToEvent }, sendOpticalFlowEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.sendOpticalFlowEvent }, opticalFlowNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowNumFramesToEvent }, opticalFlowNumFramesToReset: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowNumFramesToReset }, opticalFlowAngleOffset: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowAngleOffset } }) }
javascript
{ "resource": "" }
q35592
getInitialState
train
function getInitialState() { return { month: {}, day: {}, rangeSelection: null, rangeSelectionMode: RangeSelection.IDLE, selectedDays: [], selectedDaysByIndex: [], weekIndex: 0 }; }
javascript
{ "resource": "" }
q35593
calculateDatePos
train
function calculateDatePos(startDayOfMonth, day) { const start = startDayOfMonth - 1; day = day - 1; const weekDayIndex = (start + day) % WEEKDAYS; const weekIndex = Math.ceil((start + day + 1) / WEEKDAYS) - 1; return { weekIndex, weekDayIndex }; }
javascript
{ "resource": "" }
q35594
getDateData
train
function getDateData(date, month) { const pos = getDatePos(date, month); if (pos === null) { throw new TypeError(JSON.stringify(date) + " is invalid format."); } return getDayData(pos.weekIndex, pos.weekDayIndex, month); }
javascript
{ "resource": "" }
q35595
getDayData
train
function getDayData(weekIndex, weekDayIndex, currentMonth) { const dayData = {}; if (!currentMonth || !currentMonth.days || currentMonth.days[weekIndex] === undefined) { throw new TypeError("WeekIndex : " + weekIndex + ", weekDayIndex " + weekDayIndex + " selected day cannot be undefined"); } const selectedDay = currentMonth.days[weekIndex][weekDayIndex]; dayData.dayInfo = { weekDay: weekDayIndex, longName: currentMonth.daysLong[weekDayIndex], shortName: currentMonth.daysShort[weekDayIndex], specialDay: selectedDay.specialDay, }; dayData.date = { day: selectedDay.day }; dayData.localeDate = { day: currentMonth.days[weekIndex][weekDayIndex].localeDay, month: currentMonth.localeDate.month, year: currentMonth.localeDate.year, }; switch (selectedDay.month) { // if selected day is in the current month. case 'current': dayData.monthInfo = { longName: currentMonth.longName, shortName: currentMonth.shortName, }; dayData.date.month = currentMonth.date.month; dayData.date.year = currentMonth.date.year; break; // if selected day is in the next month. case 'next': dayData.monthInfo = { longName: currentMonth.nextMonth.longName, shortName: currentMonth.nextMonth.shortName, }; dayData.localeDate.month = currentMonth.nextMonth.localeDate.month; dayData.localeDate.year = currentMonth.nextMonth.localeDate.year; dayData.date.month = currentMonth.nextMonth.date.month; dayData.date.year = currentMonth.nextMonth.date.year; break; // if selected day is in the previous month. case 'previous': dayData.monthInfo = { longName: currentMonth.previousMonth.longName, shortName: currentMonth.previousMonth.shortName, }; dayData.localeDate.month = currentMonth.previousMonth.localeDate.month; dayData.localeDate.year = currentMonth.previousMonth.localeDate.year; dayData.date.month = currentMonth.previousMonth.date.month; dayData.date.year = currentMonth.previousMonth.date.year; break; default: throw new Error('Selected day has invalid data'); } Object.seal(dayData); return dayData; }
javascript
{ "resource": "" }
q35596
getDatePos
train
function getDatePos(date, month, notValue = null) { const monthPos = (date.month === month.date.month && 'current') || (date.month === month.nextMonth.date.month && 'next') || (date.month === month.previousMonth.date.month && 'prev'); switch (monthPos) { case 'current': return calculateDatePos(month.startDayOfMonth, date.day); case 'prev': return calculateDatePosinPrev( month.startDayOfMonth, month.previousMonth.daysCount, date.day ); case 'next': const posNext = calculateDatePosinNext( month.startDayOfMonth, month.daysCount, date.day ); return posNext; default: return notValue; } }
javascript
{ "resource": "" }
q35597
devHandler
train
function devHandler(curPath, importPath, jsFilename) { var absPath = resolve(importPath, jsFilename) var projectDir = path.resolve(require.resolve('./index.js'), '..', '..', '..', '..', '..') absPath = absPath.replace(projectDir, '@areslabs/babel-plugin-import-css/rncsscache') curPath.node.source.value = (absPath + '.js') }
javascript
{ "resource": "" }
q35598
prodHandler
train
function prodHandler(curPath, opts, importPath, jsFilename, template, t){ var absPath = resolve(importPath, jsFilename) const cssStr = fse.readFileSync(absPath).toString() const {styles: obj} = createStylefromCode(cssStr, absPath) const cssObj = convertStylesToRNCSS(obj) var defautIdenti = curPath.node.specifiers[0].local.name const buildNode = template('const STYLES = STYOBJ;', { sourceType: 'module' }) const styleExpre = buildNode({ STYLES: t.identifier(defautIdenti), STYOBJ: t.identifier(cssObj) }) curPath.replaceWith(styleExpre) }
javascript
{ "resource": "" }
q35599
gruntPrepareRelease
train
function gruntPrepareRelease () { var bower = grunt.file.readJSON('bower.json'); var version = bower.version; if (version !== grunt.config('pkg.version')) { throw new Error('Version mismatch in bower.json'); } function searchForExistingTag () { return exec('git tag -l \"' + version + '\"'); } function setGruntConfig (searchResult) { if ('' !== searchResult.stdout.trim()) { throw new Error('Tag \'' + version + '\' already exists'); } grunt.config('buildTag', ''); grunt.config('buildDir', releaseDirName); } var done = this.async(); ensureCleanMaster() .then(searchForExistingTag) .then(setGruntConfig) .then(function () { done(); }) .catch(handleAsyncError.bind(undefined, done)) .done(); }
javascript
{ "resource": "" }