_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...
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,...
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)...
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...
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); ...
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); ...
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...
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...
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]]; ...
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),...
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_callbac...
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,...
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; } publi...
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 })); ret...
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) {...
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); } ...
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; //...
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...
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.remov...
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 & ...
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....
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]; ...
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 ...
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/ws...
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 = buffer...
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 !== '') { ...
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, asso...
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 radi...
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); } fo...
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') } // Defau...
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 (...
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(ho...
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) => ...
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 platfor...
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 e...
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 t...
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.d...
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 serverRespon...
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; ...
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....
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 ...
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 serve...
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 ) { ...
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.f...
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(...
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, ...
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 && er...
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); ...
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 + "...
javascript
{ "resource": "" }
q35591
RegionOfInterestConfig
train
function RegionOfInterestConfig(regionOfInterestConfigDict){ if(!(this instanceof RegionOfInterestConfig)) return new RegionOfInterestConfig(regionOfInterestConfigDict) regionOfInterestConfigDict = regionOfInterestConfigDict || {} // Check regionOfInterestConfigDict has the required fields // // checkT...
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 ...
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.start...
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.valu...
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...
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 e...
javascript
{ "resource": "" }