id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
13,800
splunk/splunk-sdk-javascript
client/splunk.js
function(fieldName, sortAttribute, sortDirection, limit, statsFunction) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Cannot add limit filter on a nonexistent field."); } var f = this.dataModelObject.fieldByName(fieldName); if (!utils.contains(["string", "number", "objectCount"], f.type)) { throw new Error("Cannot add limit filter on " + fieldName + " because it is of type " + f.type); } if ("string" === f.type && !utils.contains(["count", "dc"], statsFunction)) { throw new Error("Stats function for fields of type string must be COUNT or DISTINCT_COUNT; found " + statsFunction); } if ("number" === f.type && !utils.contains(["count", "dc", "average", "sum"], statsFunction)) { throw new Error("Stats function for fields of type number must be one of COUNT, DISTINCT_COUNT, SUM, or AVERAGE; found " + statsFunction); } if ("objectCount" === f.type && !utils.contains(["count"], statsFunction)) { throw new Error("Stats function for fields of type object count must be COUNT; found " + statsFunction); } var filter = { fieldName: fieldName, owner: f.lineage.join("."), type: f.type, attributeName: sortAttribute, attributeOwner: this.dataModelObject.fieldByName(sortAttribute).lineage.join("."), sortDirection: sortDirection, limitAmount: limit, statsFn: statsFunction }; // Assumed "highest" is preferred for when sortDirection is "DEFAULT" filter.limitType = "ASCENDING" === sortDirection ? "lowest" : "highest"; this.filters.push(filter); return this; }
javascript
function(fieldName, sortAttribute, sortDirection, limit, statsFunction) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Cannot add limit filter on a nonexistent field."); } var f = this.dataModelObject.fieldByName(fieldName); if (!utils.contains(["string", "number", "objectCount"], f.type)) { throw new Error("Cannot add limit filter on " + fieldName + " because it is of type " + f.type); } if ("string" === f.type && !utils.contains(["count", "dc"], statsFunction)) { throw new Error("Stats function for fields of type string must be COUNT or DISTINCT_COUNT; found " + statsFunction); } if ("number" === f.type && !utils.contains(["count", "dc", "average", "sum"], statsFunction)) { throw new Error("Stats function for fields of type number must be one of COUNT, DISTINCT_COUNT, SUM, or AVERAGE; found " + statsFunction); } if ("objectCount" === f.type && !utils.contains(["count"], statsFunction)) { throw new Error("Stats function for fields of type object count must be COUNT; found " + statsFunction); } var filter = { fieldName: fieldName, owner: f.lineage.join("."), type: f.type, attributeName: sortAttribute, attributeOwner: this.dataModelObject.fieldByName(sortAttribute).lineage.join("."), sortDirection: sortDirection, limitAmount: limit, statsFn: statsFunction }; // Assumed "highest" is preferred for when sortDirection is "DEFAULT" filter.limitType = "ASCENDING" === sortDirection ? "lowest" : "highest"; this.filters.push(filter); return this; }
[ "function", "(", "fieldName", ",", "sortAttribute", ",", "sortDirection", ",", "limit", ",", "statsFunction", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "hasField", "(", "fieldName", ")", ")", "{", "throw", "new", "Error", "(", "\"Canno...
Add a limit on the events shown in a pivot by sorting them according to some field, then taking the specified number from the beginning or end of the list. @param {String} fieldName The name of field to filter on. @param {String} sortAttribute The name of the field to use for sorting. @param {String} sortDirection The direction to sort events, see class docs for valid types. @param {String} limit The number of values from the sorted list to allow through this filter. @param {String} statsFunction The stats function to use for aggregation before sorting, see class docs for valid types. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "limit", "on", "the", "events", "shown", "in", "a", "pivot", "by", "sorting", "them", "according", "to", "some", "field", "then", "taking", "the", "specified", "number", "from", "the", "beginning", "or", "end", "of", "the", "list", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L6739-L6779
13,801
splunk/splunk-sdk-javascript
client/splunk.js
function(fieldName, label) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if (!utils.contains(["number", "string"], f.type)) { throw new Error("Field was of type " + f.type + ", expected number or string."); } var row = { fieldName: fieldName, owner: f.owner, type: f.type, label: label }; if ("number" === f.type) { row.display = "all"; } this.rows.push(row); return this; }
javascript
function(fieldName, label) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if (!utils.contains(["number", "string"], f.type)) { throw new Error("Field was of type " + f.type + ", expected number or string."); } var row = { fieldName: fieldName, owner: f.owner, type: f.type, label: label }; if ("number" === f.type) { row.display = "all"; } this.rows.push(row); return this; }
[ "function", "(", "fieldName", ",", "label", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "hasField", "(", "fieldName", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+", "fieldName", ")", ";", "}", "var", "f", ...
Add a row split on a numeric or string valued field, splitting on each distinct value of the field. @param {String} fieldName The name of field to split on. @param {String} label A human readable name for this set of rows. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "row", "split", "on", "a", "numeric", "or", "string", "valued", "field", "splitting", "on", "each", "distinct", "value", "of", "the", "field", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L6790-L6813
13,802
splunk/splunk-sdk-javascript
client/splunk.js
function(field, label, ranges) { if (!this.dataModelObject.hasField(field)) { throw new Error("Did not find field " + field); } var f = this.dataModelObject.fieldByName(field); if ("number" !== f.type) { throw new Error("Field was of type " + f.type + ", expected number."); } var updateRanges = {}; if (!utils.isUndefined(ranges.start) && ranges.start !== null) { updateRanges.start = ranges.start; } if (!utils.isUndefined(ranges.end) && ranges.end !== null) { updateRanges.end = ranges.end; } if (!utils.isUndefined(ranges.step) && ranges.step !== null) { updateRanges.size = ranges.step; } if (!utils.isUndefined(ranges.limit) && ranges.limit !== null) { updateRanges.maxNumberOf = ranges.limit; } this.rows.push({ fieldName: field, owner: f.owner, type: f.type, label: label, display: "ranges", ranges: updateRanges }); return this; }
javascript
function(field, label, ranges) { if (!this.dataModelObject.hasField(field)) { throw new Error("Did not find field " + field); } var f = this.dataModelObject.fieldByName(field); if ("number" !== f.type) { throw new Error("Field was of type " + f.type + ", expected number."); } var updateRanges = {}; if (!utils.isUndefined(ranges.start) && ranges.start !== null) { updateRanges.start = ranges.start; } if (!utils.isUndefined(ranges.end) && ranges.end !== null) { updateRanges.end = ranges.end; } if (!utils.isUndefined(ranges.step) && ranges.step !== null) { updateRanges.size = ranges.step; } if (!utils.isUndefined(ranges.limit) && ranges.limit !== null) { updateRanges.maxNumberOf = ranges.limit; } this.rows.push({ fieldName: field, owner: f.owner, type: f.type, label: label, display: "ranges", ranges: updateRanges }); return this; }
[ "function", "(", "field", ",", "label", ",", "ranges", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "hasField", "(", "field", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+", "field", ")", ";", "}", "var", ...
Add a row split on a numeric field, splitting into numeric ranges. This split generates bins with edges equivalent to the classic loop 'for i in <start> to <end> by <step>' but with a maximum number of bins <limit>. This dispatches to the stats and xyseries search commands. See their documentation for more details. @param {String} fieldName The field to split on. @param {String} label A human readable name for this set of rows. @param {Object} options An optional dictionary of collection filtering and pagination options: - `start` (_integer_): The value of the start of the first range, or null to take the lowest value in the events. - `end` (_integer_): The value for the end of the last range, or null to take the highest value in the events. - `step` (_integer_): The the width of each range, or null to have Splunk calculate it. - `limit` (_integer_): The maximum number of ranges to split into, or null for no limit. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "row", "split", "on", "a", "numeric", "field", "splitting", "into", "numeric", "ranges", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L6834-L6866
13,803
splunk/splunk-sdk-javascript
client/splunk.js
function(field, label, trueDisplayValue, falseDisplayValue) { if (!this.dataModelObject.fieldByName(field)) { throw new Error("Did not find field " + field); } var f = this.dataModelObject.fieldByName(field); if ("boolean" !== f.type) { throw new Error("Field was of type " + f.type + ", expected boolean."); } this.rows.push({ fieldName: field, owner: f.owner, type: f.type, label: label, trueLabel: trueDisplayValue, falseLabel: falseDisplayValue }); return this; }
javascript
function(field, label, trueDisplayValue, falseDisplayValue) { if (!this.dataModelObject.fieldByName(field)) { throw new Error("Did not find field " + field); } var f = this.dataModelObject.fieldByName(field); if ("boolean" !== f.type) { throw new Error("Field was of type " + f.type + ", expected boolean."); } this.rows.push({ fieldName: field, owner: f.owner, type: f.type, label: label, trueLabel: trueDisplayValue, falseLabel: falseDisplayValue }); return this; }
[ "function", "(", "field", ",", "label", ",", "trueDisplayValue", ",", "falseDisplayValue", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "fieldByName", "(", "field", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+"...
Add a row split on a boolean valued field. @param {String} fieldName The name of field to split on. @param {String} label A human readable name for this set of rows. @param {String} trueDisplayValue A string to display in the true valued row label. @param {String} falseDisplayValue A string to display in the false valued row label. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "row", "split", "on", "a", "boolean", "valued", "field", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L6879-L6898
13,804
splunk/splunk-sdk-javascript
client/splunk.js
function(fieldName) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if (!utils.contains(["number", "string"], f.type)) { throw new Error("Field was of type " + f.type + ", expected number or string."); } var col = { fieldName: fieldName, owner: f.owner, type: f.type }; if ("number" === f.type) { col.display = "all"; } this.columns.push(col); return this; }
javascript
function(fieldName) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if (!utils.contains(["number", "string"], f.type)) { throw new Error("Field was of type " + f.type + ", expected number or string."); } var col = { fieldName: fieldName, owner: f.owner, type: f.type }; if ("number" === f.type) { col.display = "all"; } this.columns.push(col); return this; }
[ "function", "(", "fieldName", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "hasField", "(", "fieldName", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+", "fieldName", ")", ";", "}", "var", "f", "=", "this", ...
Add a column split on a string or number valued field, producing a column for each distinct value of the field. @param {String} fieldName The name of field to split on. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "column", "split", "on", "a", "string", "or", "number", "valued", "field", "producing", "a", "column", "for", "each", "distinct", "value", "of", "the", "field", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L6942-L6964
13,805
splunk/splunk-sdk-javascript
client/splunk.js
function(fieldName, ranges) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if ("number" !== f.type) { throw new Error("Field was of type " + f.type + ", expected number."); } // In Splunk 6.0.1.1, data models incorrectly expect strings for these fields // instead of numbers. In 6.1, this is fixed and both are accepted. var updatedRanges = {}; if (!utils.isUndefined(ranges.start) && ranges.start !== null) { updatedRanges.start = ranges.start; } if (!utils.isUndefined(ranges.end) && ranges.end !== null) { updatedRanges.end = ranges.end; } if (!utils.isUndefined(ranges.step) && ranges.step !== null) { updatedRanges.size = ranges.step; } if (!utils.isUndefined(ranges.limit) && ranges.limit !== null) { updatedRanges.maxNumberOf = ranges.limit; } this.columns.push({ fieldName: fieldName, owner: f.owner, type: f.type, display: "ranges", ranges: updatedRanges }); return this; }
javascript
function(fieldName, ranges) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if ("number" !== f.type) { throw new Error("Field was of type " + f.type + ", expected number."); } // In Splunk 6.0.1.1, data models incorrectly expect strings for these fields // instead of numbers. In 6.1, this is fixed and both are accepted. var updatedRanges = {}; if (!utils.isUndefined(ranges.start) && ranges.start !== null) { updatedRanges.start = ranges.start; } if (!utils.isUndefined(ranges.end) && ranges.end !== null) { updatedRanges.end = ranges.end; } if (!utils.isUndefined(ranges.step) && ranges.step !== null) { updatedRanges.size = ranges.step; } if (!utils.isUndefined(ranges.limit) && ranges.limit !== null) { updatedRanges.maxNumberOf = ranges.limit; } this.columns.push({ fieldName: fieldName, owner: f.owner, type: f.type, display: "ranges", ranges: updatedRanges }); return this; }
[ "function", "(", "fieldName", ",", "ranges", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "hasField", "(", "fieldName", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+", "fieldName", ")", ";", "}", "var", "f",...
Add a column split on a numeric field, splitting the values into ranges. @param {String} fieldName The field to split on. @param {Object} options An optional dictionary of collection filtering and pagination options: - `start` (_integer_): The value of the start of the first range, or null to take the lowest value in the events. - `end` (_integer_): The value for the end of the last range, or null to take the highest value in the events. - `step` (_integer_): The the width of each range, or null to have Splunk calculate it. - `limit` (_integer_): The maximum number of ranges to split into, or null for no limit. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "column", "split", "on", "a", "numeric", "field", "splitting", "the", "values", "into", "ranges", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L6979-L7013
13,806
splunk/splunk-sdk-javascript
client/splunk.js
function(fieldName, trueDisplayValue, falseDisplayValue) { if (!this.dataModelObject.fieldByName(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if ("boolean" !== f.type) { throw new Error("Field was of type " + f.type + ", expected boolean."); } this.columns.push({ fieldName: fieldName, owner: f.owner, type: f.type, trueLabel: trueDisplayValue, falseLabel: falseDisplayValue }); return this; }
javascript
function(fieldName, trueDisplayValue, falseDisplayValue) { if (!this.dataModelObject.fieldByName(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if ("boolean" !== f.type) { throw new Error("Field was of type " + f.type + ", expected boolean."); } this.columns.push({ fieldName: fieldName, owner: f.owner, type: f.type, trueLabel: trueDisplayValue, falseLabel: falseDisplayValue }); return this; }
[ "function", "(", "fieldName", ",", "trueDisplayValue", ",", "falseDisplayValue", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "fieldByName", "(", "fieldName", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+", "field...
Add a column split on a boolean valued field. @param {String} fieldName The name of field to split on. @param {String} trueDisplayValue A string to display in the true valued column label. @param {String} falseDisplayValue A string to display in the false valued column label. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "column", "split", "on", "a", "boolean", "valued", "field", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7025-L7043
13,807
splunk/splunk-sdk-javascript
client/splunk.js
function(field, binning) { if (!this.dataModelObject.hasField(field)) { throw new Error("Did not find field " + field); } var f = this.dataModelObject.fieldByName(field); if ("timestamp" !== f.type) { throw new Error("Field was of type " + f.type + ", expected timestamp."); } if (!utils.contains(this._binning, binning)) { throw new Error("Invalid binning " + binning + " found. Valid values are: " + this._binning.join(", ")); } this.columns.push({ fieldName: field, owner: f.owner, type: f.type, period: binning }); return this; }
javascript
function(field, binning) { if (!this.dataModelObject.hasField(field)) { throw new Error("Did not find field " + field); } var f = this.dataModelObject.fieldByName(field); if ("timestamp" !== f.type) { throw new Error("Field was of type " + f.type + ", expected timestamp."); } if (!utils.contains(this._binning, binning)) { throw new Error("Invalid binning " + binning + " found. Valid values are: " + this._binning.join(", ")); } this.columns.push({ fieldName: field, owner: f.owner, type: f.type, period: binning }); return this; }
[ "function", "(", "field", ",", "binning", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "hasField", "(", "field", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+", "field", ")", ";", "}", "var", "f", "=", "...
Add a column split on a timestamp valued field, binned by the specified bucket size. @param {String} fieldName The name of field to split on. @param {String} binning The size of bins to use, see class docs for valid types. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "a", "column", "split", "on", "a", "timestamp", "valued", "field", "binned", "by", "the", "specified", "bucket", "size", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7054-L7074
13,808
splunk/splunk-sdk-javascript
client/splunk.js
function(fieldName, label, statsFunction) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if (utils.contains(["string", "ipv4"], f.type) && !utils.contains([ "list", "values", "first", "last", "count", "dc"], statsFunction) ) { throw new Error("Stats function on string and IPv4 fields must be one of:" + " list, distinct_values, first, last, count, or distinct_count; found " + statsFunction); } else if ("number" === f.type && !utils.contains([ "sum", "count", "average", "min", "max", "stdev", "list", "values" ], statsFunction) ) { throw new Error("Stats function on number field must be must be one of:" + " sum, count, average, max, min, stdev, list, or distinct_values; found " + statsFunction ); } else if ("timestamp" === f.type && !utils.contains([ "duration", "earliest", "latest", "list", "values" ], statsFunction) ) { throw new Error("Stats function on timestamp field must be one of:" + " duration, earliest, latest, list, or distinct values; found " + statsFunction ); } else if (utils.contains(["objectCount", "childCount"], f.type) && "count" !== statsFunction ) { throw new Error("Stats function on childcount and objectcount fields must be count; " + "found " + statsFunction); } else if ("boolean" === f.type) { throw new Error("Cannot use boolean valued fields as cell values."); } this.cells.push({ fieldName: fieldName, owner: f.lineage.join("."), type: f.type, label: label, sparkline: false, // Not properly implemented in core yet. value: statsFunction }); return this; }
javascript
function(fieldName, label, statsFunction) { if (!this.dataModelObject.hasField(fieldName)) { throw new Error("Did not find field " + fieldName); } var f = this.dataModelObject.fieldByName(fieldName); if (utils.contains(["string", "ipv4"], f.type) && !utils.contains([ "list", "values", "first", "last", "count", "dc"], statsFunction) ) { throw new Error("Stats function on string and IPv4 fields must be one of:" + " list, distinct_values, first, last, count, or distinct_count; found " + statsFunction); } else if ("number" === f.type && !utils.contains([ "sum", "count", "average", "min", "max", "stdev", "list", "values" ], statsFunction) ) { throw new Error("Stats function on number field must be must be one of:" + " sum, count, average, max, min, stdev, list, or distinct_values; found " + statsFunction ); } else if ("timestamp" === f.type && !utils.contains([ "duration", "earliest", "latest", "list", "values" ], statsFunction) ) { throw new Error("Stats function on timestamp field must be one of:" + " duration, earliest, latest, list, or distinct values; found " + statsFunction ); } else if (utils.contains(["objectCount", "childCount"], f.type) && "count" !== statsFunction ) { throw new Error("Stats function on childcount and objectcount fields must be count; " + "found " + statsFunction); } else if ("boolean" === f.type) { throw new Error("Cannot use boolean valued fields as cell values."); } this.cells.push({ fieldName: fieldName, owner: f.lineage.join("."), type: f.type, label: label, sparkline: false, // Not properly implemented in core yet. value: statsFunction }); return this; }
[ "function", "(", "fieldName", ",", "label", ",", "statsFunction", ")", "{", "if", "(", "!", "this", ".", "dataModelObject", ".", "hasField", "(", "fieldName", ")", ")", "{", "throw", "new", "Error", "(", "\"Did not find field \"", "+", "fieldName", ")", ";...
Add an aggregate to each cell of the pivot. @param {String} fieldName The name of field to aggregate. @param {String} label a human readable name for this aggregate. @param {String} statsFunction The function to use for aggregation, see class docs for valid stats functions. @return {splunkjs.Service.PivotSpecification} The updated pivot specification. @method splunkjs.Service.PivotSpecification
[ "Add", "an", "aggregate", "to", "each", "cell", "of", "the", "pivot", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7086-L7156
13,809
splunk/splunk-sdk-javascript
client/splunk.js
function() { return { dataModel: this.dataModelObject.dataModel.name, baseClass: this.dataModelObject.name, rows: this.rows, columns: this.columns, cells: this.cells, filters: this.filters }; }
javascript
function() { return { dataModel: this.dataModelObject.dataModel.name, baseClass: this.dataModelObject.name, rows: this.rows, columns: this.columns, cells: this.cells, filters: this.filters }; }
[ "function", "(", ")", "{", "return", "{", "dataModel", ":", "this", ".", "dataModelObject", ".", "dataModel", ".", "name", ",", "baseClass", ":", "this", ".", "dataModelObject", ".", "name", ",", "rows", ":", "this", ".", "rows", ",", "columns", ":", "...
Returns a JSON ready object representation of this pivot specification. @return {Object} The JSON ready object representation of this pivot specification. @method splunkjs.Service.PivotSpecification
[ "Returns", "a", "JSON", "ready", "object", "representation", "of", "this", "pivot", "specification", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7165-L7174
13,810
splunk/splunk-sdk-javascript
client/splunk.js
function(callback) { var svc = this.dataModelObject.dataModel.service; var args = { pivot_json: JSON.stringify(this.toJsonObject()) }; if (!utils.isUndefined(this.accelerationNamespace)) { args.namespace = this.accelerationNamespace; } return svc.get(Paths.pivot + "/" + encodeURIComponent(this.dataModelObject.dataModel.name), args, function(err, response) { if (err) { callback(new Error(err.data.messages[0].text), response); return; } if (response.data.entry && response.data.entry[0]) { callback(null, new root.Pivot(svc, response.data.entry[0].content)); } else { callback(new Error("Didn't get a Pivot report back from Splunk"), response); } }); }
javascript
function(callback) { var svc = this.dataModelObject.dataModel.service; var args = { pivot_json: JSON.stringify(this.toJsonObject()) }; if (!utils.isUndefined(this.accelerationNamespace)) { args.namespace = this.accelerationNamespace; } return svc.get(Paths.pivot + "/" + encodeURIComponent(this.dataModelObject.dataModel.name), args, function(err, response) { if (err) { callback(new Error(err.data.messages[0].text), response); return; } if (response.data.entry && response.data.entry[0]) { callback(null, new root.Pivot(svc, response.data.entry[0].content)); } else { callback(new Error("Didn't get a Pivot report back from Splunk"), response); } }); }
[ "function", "(", "callback", ")", "{", "var", "svc", "=", "this", ".", "dataModelObject", ".", "dataModel", ".", "service", ";", "var", "args", "=", "{", "pivot_json", ":", "JSON", ".", "stringify", "(", "this", ".", "toJsonObject", "(", ")", ")", "}",...
Query Splunk for SPL queries corresponding to a pivot report for this data model, defined by this `PivotSpecification`. @example service.dataModels().fetch(function(err, dataModels) { var searches = dataModels.item("internal_audit_logs").objectByName("searches"); var pivotSpec = searches.createPivotSpecification(); // Use of the fluent API pivotSpec.addRowSplit("user", "Executing user") .addRangeColumnSplit("exec_time", {start: 0, end: 12, step: 5, limit: 4}) .addCellValue("search", "Search Query", "values") .pivot(function(pivotErr, pivot) { console.log("Pivot search is:", pivot.search); }); }); @param {Function} callback A function to call when done getting the pivot: `(err, pivot)`. @method splunkjs.Service.PivotSpecification
[ "Query", "Splunk", "for", "SPL", "queries", "corresponding", "to", "a", "pivot", "report", "for", "this", "data", "model", "defined", "by", "this", "PivotSpecification", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7198-L7222
13,811
splunk/splunk-sdk-javascript
client/splunk.js
function(props, parentDataModel) { props = props || {}; props.owner = props.owner || ""; this.dataModel = parentDataModel; this.name = props.objectName; this.displayName = props.displayName; this.parentName = props.parentName; this.lineage = props.lineage.split("."); // Properties exclusive to BaseTransaction if (props.hasOwnProperty("groupByFields")) { this.groupByFields = props.groupByFields; } if (props.hasOwnProperty("objectsToGroup")) { this.objectsToGroup = props.objectsToGroup; } if (props.hasOwnProperty("transactionMaxTimeSpan")) { this.maxSpan = props.transactionMaxTimeSpan; } if (props.hasOwnProperty("transactionMaxPause")) { this.maxPause = props.transactionMaxPause; } // Property exclusive to BaseSearch if (props.hasOwnProperty("baseSearch")) { this.baseSearch = props.baseSearch; } // Parse fields this.fields = {}; for (var i = 0; i < props.fields.length; i++) { this.fields[props.fields[i].fieldName] = new root.DataModelField(props.fields[i]); } // Parse constraints this.constraints = []; for (var j = 0; j < props.constraints.length; j++) { this.constraints.push(new root.DataModelConstraint(props.constraints[j])); } // Parse calculations this.calculations = []; for (var k = 0; k < props.calculations.length; k++) { this.calculations[props.calculations[k].calculationID] = new root.DataModelCalculation(props.calculations[k]); } }
javascript
function(props, parentDataModel) { props = props || {}; props.owner = props.owner || ""; this.dataModel = parentDataModel; this.name = props.objectName; this.displayName = props.displayName; this.parentName = props.parentName; this.lineage = props.lineage.split("."); // Properties exclusive to BaseTransaction if (props.hasOwnProperty("groupByFields")) { this.groupByFields = props.groupByFields; } if (props.hasOwnProperty("objectsToGroup")) { this.objectsToGroup = props.objectsToGroup; } if (props.hasOwnProperty("transactionMaxTimeSpan")) { this.maxSpan = props.transactionMaxTimeSpan; } if (props.hasOwnProperty("transactionMaxPause")) { this.maxPause = props.transactionMaxPause; } // Property exclusive to BaseSearch if (props.hasOwnProperty("baseSearch")) { this.baseSearch = props.baseSearch; } // Parse fields this.fields = {}; for (var i = 0; i < props.fields.length; i++) { this.fields[props.fields[i].fieldName] = new root.DataModelField(props.fields[i]); } // Parse constraints this.constraints = []; for (var j = 0; j < props.constraints.length; j++) { this.constraints.push(new root.DataModelConstraint(props.constraints[j])); } // Parse calculations this.calculations = []; for (var k = 0; k < props.calculations.length; k++) { this.calculations[props.calculations[k].calculationID] = new root.DataModelCalculation(props.calculations[k]); } }
[ "function", "(", "props", ",", "parentDataModel", ")", "{", "props", "=", "props", "||", "{", "}", ";", "props", ".", "owner", "=", "props", ".", "owner", "||", "\"\"", ";", "this", ".", "dataModel", "=", "parentDataModel", ";", "this", ".", "name", ...
Constructor for a data model object. SDK users are not expected to invoke this constructor directly. @constructor @param {Object} props A dictionary of properties to set: - `objectName` (_string_): The name for this data model object. - `displayName` (_string_): A human readable name for this data model object. - `parentName` (_string_): The name of the data model that owns this data model object. - `lineage` (_string_): The lineage of the data model that owns this data model object, items are delimited by a dot. This is converted into an array of strings upon construction. - `fields` (_array_): An array of data model fields. - `constraints` (_array_): An array of data model constraints. - `calculations` (_array_): An array of data model calculations. - `baseSearch` (_string_): The search query wrapped by this data model object; exclusive to BaseSearch (optional) - `groupByFields` (_array_): The fields that will be used to group events into transactions; exclusive to BaseTransaction (optional) - `objectsToGroup` (_array_): Names of the data model objects that should be unioned and split into transactions; exclusive to BaseTransaction (optional) - `maxSpan` (_string_): The maximum time span of a transaction; exclusive to BaseTransaction (optional) - `maxPause` (_string_): The maximum pause time of a transaction; exclusive to BaseTransaction (optional) @param {splunkjs.Service.DataModel} parentDataModel The `DataModel` that owns this data model object. @method splunkjs.Service.DataModelObject
[ "Constructor", "for", "a", "data", "model", "object", ".", "SDK", "users", "are", "not", "expected", "to", "invoke", "this", "constructor", "directly", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7321-L7367
13,812
splunk/splunk-sdk-javascript
client/splunk.js
function() { // merge fields and calculatedFields() var combinedFields = []; for (var f in this.fields) { if (this.fields.hasOwnProperty(f)) { combinedFields[f] = this.fields[f]; } } var calculatedFields = this.calculatedFields(); for (var cf in calculatedFields) { if (calculatedFields.hasOwnProperty(cf)) { combinedFields[cf] = calculatedFields[cf]; } } return combinedFields; }
javascript
function() { // merge fields and calculatedFields() var combinedFields = []; for (var f in this.fields) { if (this.fields.hasOwnProperty(f)) { combinedFields[f] = this.fields[f]; } } var calculatedFields = this.calculatedFields(); for (var cf in calculatedFields) { if (calculatedFields.hasOwnProperty(cf)) { combinedFields[cf] = calculatedFields[cf]; } } return combinedFields; }
[ "function", "(", ")", "{", "// merge fields and calculatedFields()", "var", "combinedFields", "=", "[", "]", ";", "for", "(", "var", "f", "in", "this", ".", "fields", ")", "{", "if", "(", "this", ".", "fields", ".", "hasOwnProperty", "(", "f", ")", ")", ...
Returns an array of data model fields from this data model object's calculations, and this data model object's fields. @return {Array} An array of `splunk.Service.DataModelField` objects which includes this data model object's fields, and the fields from this data model object's calculations. @method splunkjs.Service.DataModelObject
[ "Returns", "an", "array", "of", "data", "model", "fields", "from", "this", "data", "model", "object", "s", "calculations", "and", "this", "data", "model", "object", "s", "fields", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7427-L7445
13,813
splunk/splunk-sdk-javascript
client/splunk.js
function(){ var fields = {}; // Iterate over the calculations, get their fields var keys = this.calculationIDs(); var calculations = this.calculations; for (var i = 0; i < keys.length; i++) { var calculation = calculations[keys[i]]; for (var f = 0; f < calculation.outputFieldNames().length; f++) { fields[calculation.outputFieldNames()[f]] = calculation.outputFields[calculation.outputFieldNames()[f]]; } } return fields; }
javascript
function(){ var fields = {}; // Iterate over the calculations, get their fields var keys = this.calculationIDs(); var calculations = this.calculations; for (var i = 0; i < keys.length; i++) { var calculation = calculations[keys[i]]; for (var f = 0; f < calculation.outputFieldNames().length; f++) { fields[calculation.outputFieldNames()[f]] = calculation.outputFields[calculation.outputFieldNames()[f]]; } } return fields; }
[ "function", "(", ")", "{", "var", "fields", "=", "{", "}", ";", "// Iterate over the calculations, get their fields", "var", "keys", "=", "this", ".", "calculationIDs", "(", ")", ";", "var", "calculations", "=", "this", ".", "calculations", ";", "for", "(", ...
Returns an array of data model fields from this data model object's calculations. @return {Array} An array of `splunk.Service.DataModelField` objects of the fields from this data model object's calculations. @method splunkjs.Service.DataModelObject
[ "Returns", "an", "array", "of", "data", "model", "fields", "from", "this", "data", "model", "object", "s", "calculations", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7470-L7482
13,814
splunk/splunk-sdk-javascript
client/splunk.js
function(earliestTime, callback) { // If earliestTime parameter is not specified, then set callback to its value if (!callback && utils.isFunction(earliestTime)) { callback = earliestTime; earliestTime = undefined; } var query = "| datamodel \"" + this.dataModel.name + "\" " + this.name + " search | tscollect"; var args = earliestTime ? {earliest_time: earliestTime} : {}; this.dataModel.service.search(query, args, callback); }
javascript
function(earliestTime, callback) { // If earliestTime parameter is not specified, then set callback to its value if (!callback && utils.isFunction(earliestTime)) { callback = earliestTime; earliestTime = undefined; } var query = "| datamodel \"" + this.dataModel.name + "\" " + this.name + " search | tscollect"; var args = earliestTime ? {earliest_time: earliestTime} : {}; this.dataModel.service.search(query, args, callback); }
[ "function", "(", "earliestTime", ",", "callback", ")", "{", "// If earliestTime parameter is not specified, then set callback to its value", "if", "(", "!", "callback", "&&", "utils", ".", "isFunction", "(", "earliestTime", ")", ")", "{", "callback", "=", "earliestTime"...
Local acceleration is tsidx acceleration of a data model object that is handled manually by a user. You create a job which generates an index, and then use that index in your pivots on the data model object. The namespace created by the job is 'sid={sid}' where {sid} is the job's sid. You would use it in another job by starting your search query with `| tstats ... from sid={sid} | ...` The tsidx index created by this job is deleted when the job is garbage collected by Splunk. It is the user's responsibility to manage this job, including cancelling it. @example service.dataModels().fetch(function(err, dataModels) { var object = dataModels.item("some_data_model").objectByName("some_object"); object.createLocalAccelerationJob("-1d", function(err, accelerationJob) { console.log("The job has name:", accelerationJob.name); }); }); @param {String} earliestTime A time modifier (e.g., "-2w") setting the earliest time to index. @param {Function} callback A function to call with the search job: `(err, accelerationJob)`. @method splunkjs.Service.DataModelObject
[ "Local", "acceleration", "is", "tsidx", "acceleration", "of", "a", "data", "model", "object", "that", "is", "handled", "manually", "by", "a", "user", ".", "You", "create", "a", "job", "which", "generates", "an", "index", "and", "then", "use", "that", "inde...
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7549-L7560
13,815
splunk/splunk-sdk-javascript
client/splunk.js
function(params, querySuffix, callback) { var query = "| datamodel " + this.dataModel.name + " " + this.name + " search"; // Prepend a space to the querySuffix, or set it to an empty string if null or undefined querySuffix = (querySuffix) ? (" " + querySuffix) : (""); this.dataModel.service.search(query + querySuffix, params, callback); }
javascript
function(params, querySuffix, callback) { var query = "| datamodel " + this.dataModel.name + " " + this.name + " search"; // Prepend a space to the querySuffix, or set it to an empty string if null or undefined querySuffix = (querySuffix) ? (" " + querySuffix) : (""); this.dataModel.service.search(query + querySuffix, params, callback); }
[ "function", "(", "params", ",", "querySuffix", ",", "callback", ")", "{", "var", "query", "=", "\"| datamodel \"", "+", "this", ".", "dataModel", ".", "name", "+", "\" \"", "+", "this", ".", "name", "+", "\" search\"", ";", "// Prepend a space to the querySuff...
Start a search job that applies querySuffix to all the events in this data model object. @example service.dataModels().fetch(function(err, dataModels) { var object = dataModels.item("internal_audit_logs").objectByName("searches"); object.startSearch({}, "| head 5", function(err, job) { console.log("The job has name:", job.name); }); }); @param {Object} params A dictionary of properties for the search job. For a list of available parameters, see <a href="http://dev.splunk.com/view/SP-CAAAEFA#searchjobparams" target="_blank">Search job parameters</a> on Splunk Developer Portal. **Note:** This method throws an error if the `exec_mode=oneshot` parameter is passed in with the properties dictionary. @param {String} querySuffix A search query, starting with a '|' that will be appended to the command to fetch the contents of this data model object (e.g., "| head 3"). @param {Function} callback A function to call with the search job: `(err, job)`. @method splunkjs.Service.DataModelObject
[ "Start", "a", "search", "job", "that", "applies", "querySuffix", "to", "all", "the", "events", "in", "this", "data", "model", "object", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7581-L7586
13,816
splunk/splunk-sdk-javascript
client/splunk.js
function(name) { for (var i = 0; i < this.objects.length; i++) { if (this.objects[i].name === name) { return this.objects[i]; } } return null; }
javascript
function(name) { for (var i = 0; i < this.objects.length; i++) { if (this.objects[i].name === name) { return this.objects[i]; } } return null; }
[ "function", "(", "name", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "objects", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "objects", "[", "i", "]", ".", "name", "===", "name", ")", "{", "re...
Returns a data model object from this data model with the specified name if it exists, null otherwise. @return {Object|null} a data model object. @method splunkjs.Service.DataModel
[ "Returns", "a", "data", "model", "object", "from", "this", "data", "model", "with", "the", "specified", "name", "if", "it", "exists", "null", "otherwise", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7709-L7716
13,817
splunk/splunk-sdk-javascript
client/splunk.js
function(props, callback) { if (utils.isUndefined(callback)) { callback = props; props = {}; } callback = callback || function() {}; if (!props) { callback(new Error("Must specify a props argument to update a data model.")); return; // Exit if props isn't set, to avoid calling the callback twice. } if (props.hasOwnProperty("name")) { callback(new Error("Cannot set 'name' field in 'update'"), this); return; // Exit if the name is set, to avoid calling the callback twice. } var updatedProps = { acceleration: JSON.stringify({ enabled: props.accceleration && props.acceleration.enabled || this.acceleration.enabled, earliest_time: props.accceleration && props.acceleration.earliestTime || this.acceleration.earliestTime, cron_schedule: props.accceleration && props.acceleration.cronSchedule || this.acceleration.cronSchedule }) }; var that = this; return this.post("", updatedProps, function(err, response) { if (err) { callback(err, that); } else { var dataModelNamespace = utils.namespaceFromProperties(response.data.entry[0]); callback(null, new root.DataModel(that.service, response.data.entry[0].name, dataModelNamespace, response.data.entry[0])); } }); }
javascript
function(props, callback) { if (utils.isUndefined(callback)) { callback = props; props = {}; } callback = callback || function() {}; if (!props) { callback(new Error("Must specify a props argument to update a data model.")); return; // Exit if props isn't set, to avoid calling the callback twice. } if (props.hasOwnProperty("name")) { callback(new Error("Cannot set 'name' field in 'update'"), this); return; // Exit if the name is set, to avoid calling the callback twice. } var updatedProps = { acceleration: JSON.stringify({ enabled: props.accceleration && props.acceleration.enabled || this.acceleration.enabled, earliest_time: props.accceleration && props.acceleration.earliestTime || this.acceleration.earliestTime, cron_schedule: props.accceleration && props.acceleration.cronSchedule || this.acceleration.cronSchedule }) }; var that = this; return this.post("", updatedProps, function(err, response) { if (err) { callback(err, that); } else { var dataModelNamespace = utils.namespaceFromProperties(response.data.entry[0]); callback(null, new root.DataModel(that.service, response.data.entry[0].name, dataModelNamespace, response.data.entry[0])); } }); }
[ "function", "(", "props", ",", "callback", ")", "{", "if", "(", "utils", ".", "isUndefined", "(", "callback", ")", ")", "{", "callback", "=", "props", ";", "props", "=", "{", "}", ";", "}", "callback", "=", "callback", "||", "function", "(", ")", "...
Updates the data model on the server, used to update acceleration settings. @param {Object} props A dictionary of properties to update the object with: - `acceleration` (_object_): The acceleration settings for the data model. Valid keys are: `enabled`, `earliestTime`, `cronSchedule`. Any keys not set will be pulled from the acceleration settings already set on this data model. @param {Function} callback A function to call when the data model is updated: `(err, dataModel)`. @method splunkjs.Service.DataModel
[ "Updates", "the", "data", "model", "on", "the", "server", "used", "to", "update", "acceleration", "settings", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7741-L7775
13,818
splunk/splunk-sdk-javascript
client/splunk.js
function(service, namespace) { namespace = namespace || {}; this._super(service, this.path(), namespace); this.create = utils.bind(this, this.create); }
javascript
function(service, namespace) { namespace = namespace || {}; this._super(service, this.path(), namespace); this.create = utils.bind(this, this.create); }
[ "function", "(", "service", ",", "namespace", ")", "{", "namespace", "=", "namespace", "||", "{", "}", ";", "this", ".", "_super", "(", "service", ",", "this", ".", "path", "(", ")", ",", "namespace", ")", ";", "this", ".", "create", "=", "utils", ...
Constructor for `splunkjs.Service.DataModels`. @constructor @param {splunkjs.Service} service A `Service` instance. @param {Object} namespace (Optional) namespace information: - `owner` (_string_): The Splunk username, such as "admin". A value of "nobody" means no specific user. The "-" wildcard means all users. - `app` (_string_): The app context for this resource (such as "search"). The "-" wildcard means all apps. - `sharing` (_string_): A mode that indicates how the resource is shared. The sharing mode can be "user", "app", "global", or "system". @method splunkjs.Service.DataModels
[ "Constructor", "for", "splunkjs", ".", "Service", ".", "DataModels", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7809-L7813
13,819
splunk/splunk-sdk-javascript
client/splunk.js
function(name, params, callback) { // If we get (name, callback) instead of (name, params, callback) // do the necessary variable swap if (utils.isFunction(params) && !callback) { callback = params; params = {}; } params = params || {}; callback = callback || function(){}; name = name.replace(/ /g, "_"); var that = this; return this.post("", {name: name, description: JSON.stringify(params)}, function(err, response) { if (err) { callback(err); } else { var dataModel = new root.DataModel(that.service, response.data.entry[0].name, that.namespace, response.data.entry[0]); callback(null, dataModel); } }); }
javascript
function(name, params, callback) { // If we get (name, callback) instead of (name, params, callback) // do the necessary variable swap if (utils.isFunction(params) && !callback) { callback = params; params = {}; } params = params || {}; callback = callback || function(){}; name = name.replace(/ /g, "_"); var that = this; return this.post("", {name: name, description: JSON.stringify(params)}, function(err, response) { if (err) { callback(err); } else { var dataModel = new root.DataModel(that.service, response.data.entry[0].name, that.namespace, response.data.entry[0]); callback(null, dataModel); } }); }
[ "function", "(", "name", ",", "params", ",", "callback", ")", "{", "// If we get (name, callback) instead of (name, params, callback)", "// do the necessary variable swap", "if", "(", "utils", ".", "isFunction", "(", "params", ")", "&&", "!", "callback", ")", "{", "ca...
Creates a new `DataModel` object with the given name and parameters. It is preferred that you create data models through the Splunk Enterprise with a browser. @param {String} name The name of the data model to create. If it contains spaces they will be replaced with underscores. @param {Object} params A dictionary of properties. @param {Function} callback A function to call with the new `DataModel` object: `(err, createdDataModel)`. @method splunkjs.Service.DataModels
[ "Creates", "a", "new", "DataModel", "object", "with", "the", "given", "name", "and", "parameters", ".", "It", "is", "preferred", "that", "you", "create", "data", "models", "through", "the", "Splunk", "Enterprise", "with", "a", "browser", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7827-L7849
13,820
splunk/splunk-sdk-javascript
client/splunk.js
function(callback) { callback = callback || function() {}; var that = this; var params = { count: this._pagesize, offset: this._offset }; return this._endpoint(params, function(err, results) { if (err) { callback(err); } else { var numResults = (results.rows ? results.rows.length : 0); that._offset += numResults; callback(null, results, numResults > 0); } }); }
javascript
function(callback) { callback = callback || function() {}; var that = this; var params = { count: this._pagesize, offset: this._offset }; return this._endpoint(params, function(err, results) { if (err) { callback(err); } else { var numResults = (results.rows ? results.rows.length : 0); that._offset += numResults; callback(null, results, numResults > 0); } }); }
[ "function", "(", "callback", ")", "{", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "var", "that", "=", "this", ";", "var", "params", "=", "{", "count", ":", "this", ".", "_pagesize", ",", "offset", ":", "this", ".", "_of...
Fetches the next page from the endpoint.
[ "Fetches", "the", "next", "page", "from", "the", "endpoint", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L7879-L7898
13,821
splunk/splunk-sdk-javascript
client/splunk.js
EventWriter
function EventWriter(output, error) { this._out = utils.isUndefined(output) ? process.stdout : output; this._err = utils.isUndefined(error) ? process.stderr : error; // Has the opening <stream> tag been written yet? this._headerWritten = false; }
javascript
function EventWriter(output, error) { this._out = utils.isUndefined(output) ? process.stdout : output; this._err = utils.isUndefined(error) ? process.stderr : error; // Has the opening <stream> tag been written yet? this._headerWritten = false; }
[ "function", "EventWriter", "(", "output", ",", "error", ")", "{", "this", ".", "_out", "=", "utils", ".", "isUndefined", "(", "output", ")", "?", "process", ".", "stdout", ":", "output", ";", "this", ".", "_err", "=", "utils", ".", "isUndefined", "(", ...
`EventWriter` writes events and error messages to Splunk from a modular input. Its two important methods are `writeEvent`, which takes an `Event` object, and `log`, which takes a severity and an error message. @param {Object} output A stream to output data, defaults to `process.stdout` @param {Object} error A stream to output errors, defaults to `process.stderr` @class splunkjs.ModularInputs.EventWriter
[ "EventWriter", "writes", "events", "and", "error", "messages", "to", "Splunk", "from", "a", "modular", "input", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L12034-L12040
13,822
splunk/splunk-sdk-javascript
client/splunk.js
Scheme
function Scheme(title) { this.title = utils.isUndefined(title) ? "" : title; // Set the defaults. this.description = null; this.useExternalValidation = true; this.useSingleInstance = false; this.streamingMode = Scheme.streamingModeXML; // List of Argument objects, each to be represented by an <arg> tag. this.args = []; }
javascript
function Scheme(title) { this.title = utils.isUndefined(title) ? "" : title; // Set the defaults. this.description = null; this.useExternalValidation = true; this.useSingleInstance = false; this.streamingMode = Scheme.streamingModeXML; // List of Argument objects, each to be represented by an <arg> tag. this.args = []; }
[ "function", "Scheme", "(", "title", ")", "{", "this", ".", "title", "=", "utils", ".", "isUndefined", "(", "title", ")", "?", "\"\"", ":", "title", ";", "// Set the defaults.", "this", ".", "description", "=", "null", ";", "this", ".", "useExternalValidati...
Class representing the metadata for a modular input kind. A `Scheme` specifies a title, description, several options of how Splunk should run modular inputs of this kind, and a set of arguments that define a particular modular input's properties. The primary use of `Scheme` is to abstract away the construction of XML to feed to Splunk. @example var s = new Scheme(); var myFullScheme = new Scheme("fullScheme"); myFullScheme.description = "This is how you set the other properties"; myFullScheme.useExternalValidation = true; myFullScheme.useSingleInstance = false; myFullScheme.streamingMode = Scheme.streamingModeSimple; @param {String} The identifier for this Scheme in Splunk. @class splunkjs.ModularInputs.Scheme
[ "Class", "representing", "the", "metadata", "for", "a", "modular", "input", "kind", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L12388-L12399
13,823
splunk/splunk-sdk-javascript
client/splunk.js
stringifyArray
function stringifyArray(arr, prefix) { var ret = []; if (!prefix) throw new TypeError('stringify expects an object'); for (var i = 0; i < arr.length; i++) { ret.push(stringify(arr[i], prefix + '[]')); } return ret.join('&'); }
javascript
function stringifyArray(arr, prefix) { var ret = []; if (!prefix) throw new TypeError('stringify expects an object'); for (var i = 0; i < arr.length; i++) { ret.push(stringify(arr[i], prefix + '[]')); } return ret.join('&'); }
[ "function", "stringifyArray", "(", "arr", ",", "prefix", ")", "{", "var", "ret", "=", "[", "]", ";", "if", "(", "!", "prefix", ")", "throw", "new", "TypeError", "(", "'stringify expects an object'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i...
Stringify the given `arr`. @param {Array} arr @param {String} prefix @return {String} @api private
[ "Stringify", "the", "given", "arr", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L13533-L13540
13,824
splunk/splunk-sdk-javascript
client/splunk.js
lastBraceInKey
function lastBraceInKey(str) { var len = str.length , brace , c; for (var i = 0; i < len; ++i) { c = str[i]; if (']' == c) brace = false; if ('[' == c) brace = true; if ('=' == c && !brace) return i; } }
javascript
function lastBraceInKey(str) { var len = str.length , brace , c; for (var i = 0; i < len; ++i) { c = str[i]; if (']' == c) brace = false; if ('[' == c) brace = true; if ('=' == c && !brace) return i; } }
[ "function", "lastBraceInKey", "(", "str", ")", "{", "var", "len", "=", "str", ".", "length", ",", "brace", ",", "c", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "++", "i", ")", "{", "c", "=", "str", "[", "i", "]", ";",...
Locate last brace in `str` within the key. @param {String} str @return {Number} @api private
[ "Locate", "last", "brace", "in", "str", "within", "the", "key", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/client/splunk.js#L13594-L13604
13,825
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a, b) { c = this; if (!b) { return c.options[a]; } else { c._u(a, b); } }
javascript
function(a, b) { c = this; if (!b) { return c.options[a]; } else { c._u(a, b); } }
[ "function", "(", "a", ",", "b", ")", "{", "c", "=", "this", ";", "if", "(", "!", "b", ")", "{", "return", "c", ".", "options", "[", "a", "]", ";", "}", "else", "{", "c", ".", "_u", "(", "a", ",", "b", ")", ";", "}", "}" ]
Get or set options @param key:string @param options:object
[ "Get", "or", "set", "options" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L52-L59
13,826
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function( a, b ) { this.id = b.attr('id'); this.instances = []; this.element = b; this.options = jQuery.extend(this.options, a); this._create(); if ( this._init ) { this._init(); } }
javascript
function( a, b ) { this.id = b.attr('id'); this.instances = []; this.element = b; this.options = jQuery.extend(this.options, a); this._create(); if ( this._init ) { this._init(); } }
[ "function", "(", "a", ",", "b", ")", "{", "this", ".", "id", "=", "b", ".", "attr", "(", "'id'", ")", ";", "this", ".", "instances", "=", "[", "]", ";", "this", ".", "element", "=", "b", ";", "this", ".", "options", "=", "jQuery", ".", "exten...
Setup plugin basics, Set the jQuery UI Widget this.element, so extensions will work on both plugins
[ "Setup", "plugin", "basics", "Set", "the", "jQuery", "UI", "Widget", "this", ".", "element", "so", "extensions", "will", "work", "on", "both", "plugins" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L65-L74
13,827
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a, b) { var map = this.get('map'); jQuery.extend(this.options, { 'center': map.getCenter(), 'mapTypeId': map.getMapTypeId(), 'zoom': map.getZoom() } ); if (a && b) { this.options[a] = b; } map.setOptions(this.options); // FIXME: Temp fix for bounds... if (!(a && b)) { var c = map.getBounds(); if (c) { map.panToBounds(c); } } }
javascript
function(a, b) { var map = this.get('map'); jQuery.extend(this.options, { 'center': map.getCenter(), 'mapTypeId': map.getMapTypeId(), 'zoom': map.getZoom() } ); if (a && b) { this.options[a] = b; } map.setOptions(this.options); // FIXME: Temp fix for bounds... if (!(a && b)) { var c = map.getBounds(); if (c) { map.panToBounds(c); } } }
[ "function", "(", "a", ",", "b", ")", "{", "var", "map", "=", "this", ".", "get", "(", "'map'", ")", ";", "jQuery", ".", "extend", "(", "this", ".", "options", ",", "{", "'center'", ":", "map", ".", "getCenter", "(", ")", ",", "'mapTypeId'", ":", ...
Set map options @param key:string (optional) @param value:object (optional)
[ "Set", "map", "options" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L97-L111
13,828
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a) { this.get('bounds', new google.maps.LatLngBounds()).extend(this._latLng(a)); this.get('map').fitBounds(this.get('bounds')); }
javascript
function(a) { this.get('bounds', new google.maps.LatLngBounds()).extend(this._latLng(a)); this.get('map').fitBounds(this.get('bounds')); }
[ "function", "(", "a", ")", "{", "this", ".", "get", "(", "'bounds'", ",", "new", "google", ".", "maps", ".", "LatLngBounds", "(", ")", ")", ".", "extend", "(", "this", ".", "_latLng", "(", "a", ")", ")", ";", "this", ".", "get", "(", "'map'", "...
Adds a latitude longitude pair to the bounds. @param position:google.maps.LatLng/string
[ "Adds", "a", "latitude", "longitude", "pair", "to", "the", "bounds", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L117-L120
13,829
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a, b, c) { var d = this.get('map'); var c = c || google.maps.Marker; a.position = (a.position) ? this._latLng(a.position) : null; var e = new c( jQuery.extend({'map': d, 'bounds': false}, a) ); var f = this.get('markers', []); if ( e.id ) { f[e.id] = e; } else { f.push(e); } if ( e.bounds ) { this.addBounds(e.getPosition()); } this._call(b, d, e); return $(e); }
javascript
function(a, b, c) { var d = this.get('map'); var c = c || google.maps.Marker; a.position = (a.position) ? this._latLng(a.position) : null; var e = new c( jQuery.extend({'map': d, 'bounds': false}, a) ); var f = this.get('markers', []); if ( e.id ) { f[e.id] = e; } else { f.push(e); } if ( e.bounds ) { this.addBounds(e.getPosition()); } this._call(b, d, e); return $(e); }
[ "function", "(", "a", ",", "b", ",", "c", ")", "{", "var", "d", "=", "this", ".", "get", "(", "'map'", ")", ";", "var", "c", "=", "c", "||", "google", ".", "maps", ".", "Marker", ";", "a", ".", "position", "=", "(", "a", ".", "position", ")...
Adds a Marker to the map @param markerOptions:google.maps.MarkerOptions (optional) @param callback:function(map:google.maps.Map, marker:google.maps.Marker) (optional) @param marker:function (optional) @return $(google.maps.Marker) @see http://code.google.com/intl/sv-SE/apis/maps/documentation/javascript/reference.html#MarkerOptions
[ "Adds", "a", "Marker", "to", "the", "map" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L140-L156
13,830
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a, b) { var c = new google.maps.InfoWindow(a); this._call(b, c); return $(c); }
javascript
function(a, b) { var c = new google.maps.InfoWindow(a); this._call(b, c); return $(c); }
[ "function", "(", "a", ",", "b", ")", "{", "var", "c", "=", "new", "google", ".", "maps", ".", "InfoWindow", "(", "a", ")", ";", "this", ".", "_call", "(", "b", ",", "c", ")", ";", "return", "$", "(", "c", ")", ";", "}" ]
Adds an InfoWindow to the map @param infoWindowOptions:google.maps.InfoWindowOptions (optional) @param callback:function(InfoWindow:google.maps.InfoWindowOptions) (optional) @return $(google.maps.InfoWindowOptions) @see http://code.google.com/intl/sv-SE/apis/maps/documentation/javascript/reference.html#InfoWindowOptions
[ "Adds", "an", "InfoWindow", "to", "the", "map" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L165-L169
13,831
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a, b) { var c = this.instances[this.id]; if (!c[a]) { if ( a.indexOf('>') > -1 ) { var e = a.replace(/ /g, '').split('>'); for ( var i = 0; i < e.length; i++ ) { if ( !c[e[i]] ) { if (b) { c[e[i]] = ( (i + 1) < e.length ) ? [] : b; } else { return null; } } c = c[e[i]]; } return c; } else if ( b && !c[a] ) { this.set(a, b); } } return c[a]; }
javascript
function(a, b) { var c = this.instances[this.id]; if (!c[a]) { if ( a.indexOf('>') > -1 ) { var e = a.replace(/ /g, '').split('>'); for ( var i = 0; i < e.length; i++ ) { if ( !c[e[i]] ) { if (b) { c[e[i]] = ( (i + 1) < e.length ) ? [] : b; } else { return null; } } c = c[e[i]]; } return c; } else if ( b && !c[a] ) { this.set(a, b); } } return c[a]; }
[ "function", "(", "a", ",", "b", ")", "{", "var", "c", "=", "this", ".", "instances", "[", "this", ".", "id", "]", ";", "if", "(", "!", "c", "[", "a", "]", ")", "{", "if", "(", "a", ".", "indexOf", "(", "'>'", ")", ">", "-", "1", ")", "{...
Returns an instance property by key. Has the ability to set an object if the property does not exist @param key:string @param value:object(optional)
[ "Returns", "an", "instance", "property", "by", "key", ".", "Has", "the", "ability", "to", "set", "an", "object", "if", "the", "property", "does", "not", "exist" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L212-L233
13,832
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a, b) { this.get('iw', new google.maps.InfoWindow).setOptions(a); this.get('iw').open(this.get('map'), this._unwrap(b)); }
javascript
function(a, b) { this.get('iw', new google.maps.InfoWindow).setOptions(a); this.get('iw').open(this.get('map'), this._unwrap(b)); }
[ "function", "(", "a", ",", "b", ")", "{", "this", ".", "get", "(", "'iw'", ",", "new", "google", ".", "maps", ".", "InfoWindow", ")", ".", "setOptions", "(", "a", ")", ";", "this", ".", "get", "(", "'iw'", ")", ".", "open", "(", "this", ".", ...
Triggers an InfoWindow to open @param infoWindowOptions:google.maps.InfoWindowOptions @param marker:google.maps.Marker (optional) @see http://code.google.com/intl/sv-SE/apis/maps/documentation/javascript/reference.html#InfoWindowOptions
[ "Triggers", "an", "InfoWindow", "to", "open" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L241-L244
13,833
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function() { this.clear('markers'); this.clear('services'); this.clear('overlays'); var a = this.instances[this.id]; for ( b in a ) { a[b] = null; } }
javascript
function() { this.clear('markers'); this.clear('services'); this.clear('overlays'); var a = this.instances[this.id]; for ( b in a ) { a[b] = null; } }
[ "function", "(", ")", "{", "this", ".", "clear", "(", "'markers'", ")", ";", "this", ".", "clear", "(", "'services'", ")", ";", "this", ".", "clear", "(", "'overlays'", ")", ";", "var", "a", "=", "this", ".", "instances", "[", "this", ".", "id", ...
Destroys the plugin.
[ "Destroys", "the", "plugin", "." ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L266-L274
13,834
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a) { if ( $.isFunction(a) ) { a.apply(this, Array.prototype.slice.call(arguments, 1)); } }
javascript
function(a) { if ( $.isFunction(a) ) { a.apply(this, Array.prototype.slice.call(arguments, 1)); } }
[ "function", "(", "a", ")", "{", "if", "(", "$", ".", "isFunction", "(", "a", ")", ")", "{", "a", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}", "}" ]
Helper method for calling a function @param callback
[ "Helper", "method", "for", "calling", "a", "function" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L280-L284
13,835
splunk/splunk-sdk-javascript
examples/browser/minisplunk/jquery.fn.gmap.js
function(a) { if ( a instanceof google.maps.LatLng ) { return a; } else { var b = a.replace(/ /g,'').split(','); return new google.maps.LatLng(b[0], b[1]); } }
javascript
function(a) { if ( a instanceof google.maps.LatLng ) { return a; } else { var b = a.replace(/ /g,'').split(','); return new google.maps.LatLng(b[0], b[1]); } }
[ "function", "(", "a", ")", "{", "if", "(", "a", "instanceof", "google", ".", "maps", ".", "LatLng", ")", "{", "return", "a", ";", "}", "else", "{", "var", "b", "=", "a", ".", "replace", "(", "/", " ", "/", "g", ",", "''", ")", ".", "split", ...
Helper method for google.maps.Latlng @param callback
[ "Helper", "method", "for", "google", ".", "maps", ".", "Latlng" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/browser/minisplunk/jquery.fn.gmap.js#L290-L297
13,836
splunk/splunk-sdk-javascript
bin/cli.js
function(sourceDir, newDirLocation, opts) { if (!opts || !opts.preserve) { try { if(fs.statSync(newDirLocation).isDirectory()) { exports.rmdirSyncRecursive(newDirLocation); } } catch(e) { } } /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ var checkDir = fs.statSync(sourceDir); try { fs.mkdirSync(newDirLocation, checkDir.mode); } catch (e) { //if the directory already exists, that's okay if (e.code !== 'EEXIST') { throw e; } } var files = fs.readdirSync(sourceDir); for(var i = 0; i < files.length; i++) { var currFile = fs.lstatSync(sourceDir + "/" + files[i]); if(currFile.isDirectory()) { /* recursion this thing right on back. */ copyDirectoryRecursiveSync(sourceDir + "/" + files[i], newDirLocation + "/" + files[i], opts); } else if(currFile.isSymbolicLink()) { var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]); fs.symlinkSync(symlinkFull, newDirLocation + "/" + files[i]); } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ var contents = fs.readFileSync(sourceDir + "/" + files[i]); fs.writeFileSync(newDirLocation + "/" + files[i], contents); } } }
javascript
function(sourceDir, newDirLocation, opts) { if (!opts || !opts.preserve) { try { if(fs.statSync(newDirLocation).isDirectory()) { exports.rmdirSyncRecursive(newDirLocation); } } catch(e) { } } /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ var checkDir = fs.statSync(sourceDir); try { fs.mkdirSync(newDirLocation, checkDir.mode); } catch (e) { //if the directory already exists, that's okay if (e.code !== 'EEXIST') { throw e; } } var files = fs.readdirSync(sourceDir); for(var i = 0; i < files.length; i++) { var currFile = fs.lstatSync(sourceDir + "/" + files[i]); if(currFile.isDirectory()) { /* recursion this thing right on back. */ copyDirectoryRecursiveSync(sourceDir + "/" + files[i], newDirLocation + "/" + files[i], opts); } else if(currFile.isSymbolicLink()) { var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]); fs.symlinkSync(symlinkFull, newDirLocation + "/" + files[i]); } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ var contents = fs.readFileSync(sourceDir + "/" + files[i]); fs.writeFileSync(newDirLocation + "/" + files[i], contents); } } }
[ "function", "(", "sourceDir", ",", "newDirLocation", ",", "opts", ")", "{", "if", "(", "!", "opts", "||", "!", "opts", ".", "preserve", ")", "{", "try", "{", "if", "(", "fs", ".", "statSync", "(", "newDirLocation", ")", ".", "isDirectory", "(", ")", ...
Taken from wrench.js
[ "Taken", "from", "wrench", ".", "js" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/bin/cli.js#L208-L250
13,837
splunk/splunk-sdk-javascript
examples/node/search.js
function(job, done) { Async.whilst( function() { return !job.properties().isDone; }, function(iterationDone) { job.fetch(function(err, job) { if (err) { callback(err); } else { // If the user asked for verbose output, // then write out the status of the search var properties = job.properties(); if (isVerbose) { var progress = (properties.doneProgress * 100.0) + "%"; var scanned = properties.scanCount; var matched = properties.eventCount; var results = properties.resultCount; var stats = "-- " + progress + " done | " + scanned + " scanned | " + matched + " matched | " + results + " results"; print("\r" + stats + " "); } Async.sleep(1000, iterationDone); } }); }, function(err) { if (isVerbose) { print("\r"); } done(err, job); } ); }
javascript
function(job, done) { Async.whilst( function() { return !job.properties().isDone; }, function(iterationDone) { job.fetch(function(err, job) { if (err) { callback(err); } else { // If the user asked for verbose output, // then write out the status of the search var properties = job.properties(); if (isVerbose) { var progress = (properties.doneProgress * 100.0) + "%"; var scanned = properties.scanCount; var matched = properties.eventCount; var results = properties.resultCount; var stats = "-- " + progress + " done | " + scanned + " scanned | " + matched + " matched | " + results + " results"; print("\r" + stats + " "); } Async.sleep(1000, iterationDone); } }); }, function(err) { if (isVerbose) { print("\r"); } done(err, job); } ); }
[ "function", "(", "job", ",", "done", ")", "{", "Async", ".", "whilst", "(", "function", "(", ")", "{", "return", "!", "job", ".", "properties", "(", ")", ".", "isDone", ";", "}", ",", "function", "(", "iterationDone", ")", "{", "job", ".", "fetch",...
Poll until the search is complete
[ "Poll", "until", "the", "search", "is", "complete" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/node/search.js#L62-L98
13,838
splunk/splunk-sdk-javascript
examples/node/results.js
function(results) { for(var i = 0; i < results.rows.length; i++) { console.log("Result " + (i + 1) + ": "); var row = results.rows[i]; for(var j = 0; j < results.fields.length; j++) { var field = results.fields[j]; var value = row[j]; console.log(" " + field + " = " + value); } } }
javascript
function(results) { for(var i = 0; i < results.rows.length; i++) { console.log("Result " + (i + 1) + ": "); var row = results.rows[i]; for(var j = 0; j < results.fields.length; j++) { var field = results.fields[j]; var value = row[j]; console.log(" " + field + " = " + value); } } }
[ "function", "(", "results", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "results", ".", "rows", ".", "length", ";", "i", "++", ")", "{", "console", ".", "log", "(", "\"Result \"", "+", "(", "i", "+", "1", ")", "+", "\": \"", ")...
Print the result rows
[ "Print", "the", "result", "rows" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/node/results.js#L24-L35
13,839
splunk/splunk-sdk-javascript
examples/node/results.js
function(results) { var rows = []; var cols = results.columns; var mapFirst = function(col) { return col.shift(); }; while(cols.length > 0 && cols[0].length > 0) { rows.push(cols.map(mapFirst)); } results.rows = rows; return results; }
javascript
function(results) { var rows = []; var cols = results.columns; var mapFirst = function(col) { return col.shift(); }; while(cols.length > 0 && cols[0].length > 0) { rows.push(cols.map(mapFirst)); } results.rows = rows; return results; }
[ "function", "(", "results", ")", "{", "var", "rows", "=", "[", "]", ";", "var", "cols", "=", "results", ".", "columns", ";", "var", "mapFirst", "=", "function", "(", "col", ")", "{", "return", "col", ".", "shift", "(", ")", ";", "}", ";", "while"...
Instead of trying to print the column-major format, we just transpose it
[ "Instead", "of", "trying", "to", "print", "the", "column", "-", "major", "format", "we", "just", "transpose", "it" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/node/results.js#L39-L51
13,840
splunk/splunk-sdk-javascript
examples/node/results.js
function(results) { if (results) { var isRows = !!results.rows; var numResults = (results.rows ? results.rows.length : (results.columns[0] || []).length); console.log("====== " + numResults + " RESULTS (preview: " + !!results.preview + ") ======"); // If it is in column-major form, transpose it. if (!isRows) { results = transpose(results); } printRows(results); } }
javascript
function(results) { if (results) { var isRows = !!results.rows; var numResults = (results.rows ? results.rows.length : (results.columns[0] || []).length); console.log("====== " + numResults + " RESULTS (preview: " + !!results.preview + ") ======"); // If it is in column-major form, transpose it. if (!isRows) { results = transpose(results); } printRows(results); } }
[ "function", "(", "results", ")", "{", "if", "(", "results", ")", "{", "var", "isRows", "=", "!", "!", "results", ".", "rows", ";", "var", "numResults", "=", "(", "results", ".", "rows", "?", "results", ".", "rows", ".", "length", ":", "(", "results...
Print the results
[ "Print", "the", "results" ]
9aec5443860926654c2ab8ee3bf198a407c53b07
https://github.com/splunk/splunk-sdk-javascript/blob/9aec5443860926654c2ab8ee3bf198a407c53b07/examples/node/results.js#L54-L68
13,841
lampaa/com.lampa.startapp
www/startApp.manually.js
function(params, extra) { var output = [params]; if(extra != undefined) { output.push(extra); } else { output.push(null); } return { start: function(completeCallback, errorCallback, messageCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; messageCallback = messageCallback || function() {}; exec(function(result) { if(result === "OK") { completeCallback(result); } else { var requestCode = result["_ACTION_requestCode_"]; delete result["_ACTION_requestCode_"]; var resultCode = result["_ACTION_resultCode_"]; delete result["_ACTION_resultCode_"]; messageCallback(result, requestCode, resultCode); } }, errorCallback, "startApp", "start", output); }, check: function(completeCallback, errorCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; exec(completeCallback, errorCallback, "startApp", "check", output); }, receiver: function(completeCallback, errorCallback, messageCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; messageCallback = messageCallback || function() {}; exec(function(result) { if(/\d+/.test(result)) { completeCallback(result); } else { var action = result["_ACTION_VALUE_FORMAT_"]; delete result["_ACTION_VALUE_FORMAT_"]; messageCallback(action, result); } }, errorCallback, "startApp", "receiver", output); } } }
javascript
function(params, extra) { var output = [params]; if(extra != undefined) { output.push(extra); } else { output.push(null); } return { start: function(completeCallback, errorCallback, messageCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; messageCallback = messageCallback || function() {}; exec(function(result) { if(result === "OK") { completeCallback(result); } else { var requestCode = result["_ACTION_requestCode_"]; delete result["_ACTION_requestCode_"]; var resultCode = result["_ACTION_resultCode_"]; delete result["_ACTION_resultCode_"]; messageCallback(result, requestCode, resultCode); } }, errorCallback, "startApp", "start", output); }, check: function(completeCallback, errorCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; exec(completeCallback, errorCallback, "startApp", "check", output); }, receiver: function(completeCallback, errorCallback, messageCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; messageCallback = messageCallback || function() {}; exec(function(result) { if(/\d+/.test(result)) { completeCallback(result); } else { var action = result["_ACTION_VALUE_FORMAT_"]; delete result["_ACTION_VALUE_FORMAT_"]; messageCallback(action, result); } }, errorCallback, "startApp", "receiver", output); } } }
[ "function", "(", "params", ",", "extra", ")", "{", "var", "output", "=", "[", "params", "]", ";", "if", "(", "extra", "!=", "undefined", ")", "{", "output", ".", "push", "(", "extra", ")", ";", "}", "else", "{", "output", ".", "push", "(", "null"...
Set application params @param {Mixed} params params, view documentation https://github.com/lampaa/com.lampa.startapp @param {Mixed} extra Extra fields @param {Function} errorCallback The callback that is called when an error occurred when the program starts.
[ "Set", "application", "params" ]
2fa54b40316e45411e457d4227b4c409f15227b0
https://github.com/lampaa/com.lampa.startapp/blob/2fa54b40316e45411e457d4227b4c409f15227b0/www/startApp.manually.js#L22-L77
13,842
raml2html/raml2html
index.js
render
function render(source, config, options) { config = config || {}; config.raml2HtmlVersion = pjson.version; // Check if option is old boolean `validation` to keep backward compatibility if (typeof options === 'boolean') { options = { validate: options, }; } if (options === undefined) { options = { validate: false, }; } return raml2obj .parse(source, { validate: options.validate, extensionsAndOverlays: options.extensionsAndOverlays, }) .then(ramlObj => { if (config.processRamlObj) { return config.processRamlObj(ramlObj, config, options).then(html => { if (config.postProcessHtml) { return config.postProcessHtml(html, config, options); } return html; }); } return ramlObj; }); }
javascript
function render(source, config, options) { config = config || {}; config.raml2HtmlVersion = pjson.version; // Check if option is old boolean `validation` to keep backward compatibility if (typeof options === 'boolean') { options = { validate: options, }; } if (options === undefined) { options = { validate: false, }; } return raml2obj .parse(source, { validate: options.validate, extensionsAndOverlays: options.extensionsAndOverlays, }) .then(ramlObj => { if (config.processRamlObj) { return config.processRamlObj(ramlObj, config, options).then(html => { if (config.postProcessHtml) { return config.postProcessHtml(html, config, options); } return html; }); } return ramlObj; }); }
[ "function", "render", "(", "source", ",", "config", ",", "options", ")", "{", "config", "=", "config", "||", "{", "}", ";", "config", ".", "raml2HtmlVersion", "=", "pjson", ".", "version", ";", "// Check if option is old boolean `validation` to keep backward compati...
Render the source RAML object using the config's processOutput function The config object should contain at least the following property: processRamlObj: function that takes the raw RAML object and returns a promise with the rendered HTML @param {(String|Object)} source - The source RAML file. Can be a filename, url, or an already-parsed RAML object. @param {Object} config @param {Object} options @param {Function} config.processRamlObj @returns a promise
[ "Render", "the", "source", "RAML", "object", "using", "the", "config", "s", "processOutput", "function" ]
3f0c479bb2ec7280a72ca953fca7eb965dbf28c9
https://github.com/raml2html/raml2html/blob/3f0c479bb2ec7280a72ca953fca7eb965dbf28c9/index.js#L25-L59
13,843
stovmascript/react-native-version
index.js
getPlistFilenames
function getPlistFilenames(xcode) { return unique( flattenDeep( xcode.document.projects.map(project => { return project.targets.filter(Boolean).map(target => { return target.buildConfigurationsList.buildConfigurations.map( config => { return config.ast.value.get("buildSettings").get("INFOPLIST_FILE") .text; } ); }); }) ) ); }
javascript
function getPlistFilenames(xcode) { return unique( flattenDeep( xcode.document.projects.map(project => { return project.targets.filter(Boolean).map(target => { return target.buildConfigurationsList.buildConfigurations.map( config => { return config.ast.value.get("buildSettings").get("INFOPLIST_FILE") .text; } ); }); }) ) ); }
[ "function", "getPlistFilenames", "(", "xcode", ")", "{", "return", "unique", "(", "flattenDeep", "(", "xcode", ".", "document", ".", "projects", ".", "map", "(", "project", "=>", "{", "return", "project", ".", "targets", ".", "filter", "(", "Boolean", ")",...
Returns Info.plist filenames @private @param {Xcode} xcode Opened Xcode project file @return {Array} Plist filenames
[ "Returns", "Info", ".", "plist", "filenames" ]
0ff1d9a95d0a6c98ea24a0a46a3b3319b7945e21
https://github.com/stovmascript/react-native-version/blob/0ff1d9a95d0a6c98ea24a0a46a3b3319b7945e21/index.js#L47-L62
13,844
stovmascript/react-native-version
index.js
isExpoProject
function isExpoProject(projPath) { try { let module = resolveFrom(projPath, "expo"); let appInfo = require(`${projPath}/app.json`); return !!(module && appInfo.expo); } catch (err) { return false; } }
javascript
function isExpoProject(projPath) { try { let module = resolveFrom(projPath, "expo"); let appInfo = require(`${projPath}/app.json`); return !!(module && appInfo.expo); } catch (err) { return false; } }
[ "function", "isExpoProject", "(", "projPath", ")", "{", "try", "{", "let", "module", "=", "resolveFrom", "(", "projPath", ",", "\"expo\"", ")", ";", "let", "appInfo", "=", "require", "(", "`", "${", "projPath", "}", "`", ")", ";", "return", "!", "!", ...
Determines whether the project is an Expo app or a plain React Native app @private @return {Boolean} true if the project is an Expo app
[ "Determines", "whether", "the", "project", "is", "an", "Expo", "app", "or", "a", "plain", "React", "Native", "app" ]
0ff1d9a95d0a6c98ea24a0a46a3b3319b7945e21
https://github.com/stovmascript/react-native-version/blob/0ff1d9a95d0a6c98ea24a0a46a3b3319b7945e21/index.js#L69-L78
13,845
stovmascript/react-native-version
util.js
log
function log(msg, silent) { if (!silent) { console.log("[RNV]", chalk[msg.style || "reset"](msg.text)); } }
javascript
function log(msg, silent) { if (!silent) { console.log("[RNV]", chalk[msg.style || "reset"](msg.text)); } }
[ "function", "log", "(", "msg", ",", "silent", ")", "{", "if", "(", "!", "silent", ")", "{", "console", ".", "log", "(", "\"[RNV]\"", ",", "chalk", "[", "msg", ".", "style", "||", "\"reset\"", "]", "(", "msg", ".", "text", ")", ")", ";", "}", "}...
Logs a message into the console with style @param {Object} msg Object containing the message text and chalk style @param {boolean} silent Whether log should be quiet
[ "Logs", "a", "message", "into", "the", "console", "with", "style" ]
0ff1d9a95d0a6c98ea24a0a46a3b3319b7945e21
https://github.com/stovmascript/react-native-version/blob/0ff1d9a95d0a6c98ea24a0a46a3b3319b7945e21/util.js#L17-L21
13,846
videojs/videojs-vr
src/orbit-orientation-controls.js
Quat2Angle
function Quat2Angle(x, y, z, w) { const test = x * y + z * w; // singularity at north pole if (test > 0.499) { const yaw = 2 * Math.atan2(x, w); const pitch = Math.PI / 2; const roll = 0; return new THREE.Vector3(pitch, roll, yaw); } // singularity at south pole if (test < -0.499) { const yaw = -2 * Math.atan2(x, w); const pitch = -Math.PI / 2; const roll = 0; return new THREE.Vector3(pitch, roll, yaw); } const sqx = x * x; const sqy = y * y; const sqz = z * z; const yaw = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); const pitch = Math.asin(2 * test); const roll = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); return new THREE.Vector3(pitch, roll, yaw); }
javascript
function Quat2Angle(x, y, z, w) { const test = x * y + z * w; // singularity at north pole if (test > 0.499) { const yaw = 2 * Math.atan2(x, w); const pitch = Math.PI / 2; const roll = 0; return new THREE.Vector3(pitch, roll, yaw); } // singularity at south pole if (test < -0.499) { const yaw = -2 * Math.atan2(x, w); const pitch = -Math.PI / 2; const roll = 0; return new THREE.Vector3(pitch, roll, yaw); } const sqx = x * x; const sqy = y * y; const sqz = z * z; const yaw = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); const pitch = Math.asin(2 * test); const roll = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); return new THREE.Vector3(pitch, roll, yaw); }
[ "function", "Quat2Angle", "(", "x", ",", "y", ",", "z", ",", "w", ")", "{", "const", "test", "=", "x", "*", "y", "+", "z", "*", "w", ";", "// singularity at north pole", "if", "(", "test", ">", "0.499", ")", "{", "const", "yaw", "=", "2", "*", ...
Convert a quaternion to an angle Taken from https://stackoverflow.com/a/35448946 Thanks P. Ellul
[ "Convert", "a", "quaternion", "to", "an", "angle" ]
b2ee7945e30fb8f913cc555d03120fd4b467f5b5
https://github.com/videojs/videojs-vr/blob/b2ee7945e30fb8f913cc555d03120fd4b467f5b5/src/orbit-orientation-controls.js#L11-L40
13,847
tommoor/react-emoji-render
src/unicodeToCodepoint.js
toCodePoint
function toCodePoint(input, separator = "-") { const codePoints = []; for (let codePoint of input) { codePoints.push(codePoint.codePointAt(0).toString(16)); } return codePoints.join(separator); }
javascript
function toCodePoint(input, separator = "-") { const codePoints = []; for (let codePoint of input) { codePoints.push(codePoint.codePointAt(0).toString(16)); } return codePoints.join(separator); }
[ "function", "toCodePoint", "(", "input", ",", "separator", "=", "\"-\"", ")", "{", "const", "codePoints", "=", "[", "]", ";", "for", "(", "let", "codePoint", "of", "input", ")", "{", "codePoints", ".", "push", "(", "codePoint", ".", "codePointAt", "(", ...
convert utf16 into code points
[ "convert", "utf16", "into", "code", "points" ]
7122d0fbe91766cd4836c123c8dd3944c1af1ffd
https://github.com/tommoor/react-emoji-render/blob/7122d0fbe91766cd4836c123c8dd3944c1af1ffd/src/unicodeToCodepoint.js#L11-L17
13,848
ngVue/ngVue
src/plugins/filters.js
registerFilters
function registerFilters (filters) { if (isArray(filters)) { lazyStringFilters = lazyStringFilters.concat(filters) } else if (isObject(filters)) { Object.keys(filters).forEach(name => { addFilter(name, filters[name]) }) } }
javascript
function registerFilters (filters) { if (isArray(filters)) { lazyStringFilters = lazyStringFilters.concat(filters) } else if (isObject(filters)) { Object.keys(filters).forEach(name => { addFilter(name, filters[name]) }) } }
[ "function", "registerFilters", "(", "filters", ")", "{", "if", "(", "isArray", "(", "filters", ")", ")", "{", "lazyStringFilters", "=", "lazyStringFilters", ".", "concat", "(", "filters", ")", "}", "else", "if", "(", "isObject", "(", "filters", ")", ")", ...
register a list of ng filters to ngVue
[ "register", "a", "list", "of", "ng", "filters", "to", "ngVue" ]
0ceb8a7b025aea1de86ab4e7175e7e6057dfb8fa
https://github.com/ngVue/ngVue/blob/0ceb8a7b025aea1de86ab4e7175e7e6057dfb8fa/src/plugins/filters.js#L27-L35
13,849
lynndylanhurley/redux-auth
dummy/src/server.js
getMarkup
function getMarkup(webserver, provider) { var markup = renderToString(provider), styles = ""; if (process.env.NODE_ENV === "production") { styles = `<link href="${webserver}/dist/main.css" rel="stylesheet"></link>`; } return `<!doctype html> <html> <head> <title>Redux Auth – Isomorphic Example</title> <script> window.__API_URL__ = "${global.__API_URL__}"; </script> ${styles} </head> <body> <div id="react-root">${markup}</div> <script src="${webserver}/dist/client.js"></script> </body> </html>`; }
javascript
function getMarkup(webserver, provider) { var markup = renderToString(provider), styles = ""; if (process.env.NODE_ENV === "production") { styles = `<link href="${webserver}/dist/main.css" rel="stylesheet"></link>`; } return `<!doctype html> <html> <head> <title>Redux Auth – Isomorphic Example</title> <script> window.__API_URL__ = "${global.__API_URL__}"; </script> ${styles} </head> <body> <div id="react-root">${markup}</div> <script src="${webserver}/dist/client.js"></script> </body> </html>`; }
[ "function", "getMarkup", "(", "webserver", ",", "provider", ")", "{", "var", "markup", "=", "renderToString", "(", "provider", ")", ",", "styles", "=", "\"\"", ";", "if", "(", "process", ".", "env", ".", "NODE_ENV", "===", "\"production\"", ")", "{", "st...
base html template
[ "base", "html", "template" ]
dc27f381cb7d16fcd4c812c7c1a2f9f921d73164
https://github.com/lynndylanhurley/redux-auth/blob/dc27f381cb7d16fcd4c812c7c1a2f9f921d73164/dummy/src/server.js#L16-L38
13,850
MABelanger/jslib-html5-camera-photo
src/demo/AppSimpleVanillaJs.js
takePhoto
function takePhoto () { let sizeFactor = 1; let imageType = IMAGE_TYPES.JPG; let imageCompression = 1; let config = { sizeFactor, imageType, imageCompression }; let dataUri = cameraPhoto.getDataUri(config); imgElement.src = dataUri; }
javascript
function takePhoto () { let sizeFactor = 1; let imageType = IMAGE_TYPES.JPG; let imageCompression = 1; let config = { sizeFactor, imageType, imageCompression }; let dataUri = cameraPhoto.getDataUri(config); imgElement.src = dataUri; }
[ "function", "takePhoto", "(", ")", "{", "let", "sizeFactor", "=", "1", ";", "let", "imageType", "=", "IMAGE_TYPES", ".", "JPG", ";", "let", "imageCompression", "=", "1", ";", "let", "config", "=", "{", "sizeFactor", ",", "imageType", ",", "imageCompression...
function called by the buttons.
[ "function", "called", "by", "the", "buttons", "." ]
dafa2f415caf4d0728743aae69285707c4c21ab9
https://github.com/MABelanger/jslib-html5-camera-photo/blob/dafa2f415caf4d0728743aae69285707c4c21ab9/src/demo/AppSimpleVanillaJs.js#L56-L69
13,851
BenjaminBrandmeier/angular2-image-gallery
browserstack/browserstack_local.conf.js
function () { require('ts-node').register({ project: 'e2e/tsconfig.e2e.json' }); console.log("Connecting local"); return new Promise(function (resolve, reject) { exports.bs_local = new browserstack.Local(); exports.bs_local.start({'key': exports.config.capabilities['browserstack.key']}, function (error) { if (error) return reject(error); console.log('Connected. Now testing...'); resolve(); }); }); }
javascript
function () { require('ts-node').register({ project: 'e2e/tsconfig.e2e.json' }); console.log("Connecting local"); return new Promise(function (resolve, reject) { exports.bs_local = new browserstack.Local(); exports.bs_local.start({'key': exports.config.capabilities['browserstack.key']}, function (error) { if (error) return reject(error); console.log('Connected. Now testing...'); resolve(); }); }); }
[ "function", "(", ")", "{", "require", "(", "'ts-node'", ")", ".", "register", "(", "{", "project", ":", "'e2e/tsconfig.e2e.json'", "}", ")", ";", "console", ".", "log", "(", "\"Connecting local\"", ")", ";", "return", "new", "Promise", "(", "function", "("...
Code to start browserstack local before start of test
[ "Code", "to", "start", "browserstack", "local", "before", "start", "of", "test" ]
504629c02516ae058c73433d1b5184f98ca47733
https://github.com/BenjaminBrandmeier/angular2-image-gallery/blob/504629c02516ae058c73433d1b5184f98ca47733/browserstack/browserstack_local.conf.js#L21-L35
13,852
mongodb-js/mongodb-core
lib/utils.js
relayEvents
function relayEvents(listener, emitter, events) { events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); }
javascript
function relayEvents(listener, emitter, events) { events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); }
[ "function", "relayEvents", "(", "listener", ",", "emitter", ",", "events", ")", "{", "events", ".", "forEach", "(", "eventName", "=>", "listener", ".", "on", "(", "eventName", ",", "event", "=>", "emitter", ".", "emit", "(", "eventName", ",", "event", ")...
Relays events for a given listener and emitter @param {EventEmitter} listener the EventEmitter to listen to the events from @param {EventEmitter} emitter the EventEmitter to relay the events to
[ "Relays", "events", "for", "a", "given", "listener", "and", "emitter" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/utils.js#L33-L35
13,853
mongodb-js/mongodb-core
lib/utils.js
retrieveEJSON
function retrieveEJSON() { let EJSON = null; try { EJSON = requireOptional('mongodb-extjson'); } catch (error) {} // eslint-disable-line if (!EJSON) { EJSON = { parse: noEJSONError, deserialize: noEJSONError, serialize: noEJSONError, stringify: noEJSONError, setBSONModule: noEJSONError, BSON: noEJSONError }; } return EJSON; }
javascript
function retrieveEJSON() { let EJSON = null; try { EJSON = requireOptional('mongodb-extjson'); } catch (error) {} // eslint-disable-line if (!EJSON) { EJSON = { parse: noEJSONError, deserialize: noEJSONError, serialize: noEJSONError, stringify: noEJSONError, setBSONModule: noEJSONError, BSON: noEJSONError }; } return EJSON; }
[ "function", "retrieveEJSON", "(", ")", "{", "let", "EJSON", "=", "null", ";", "try", "{", "EJSON", "=", "requireOptional", "(", "'mongodb-extjson'", ")", ";", "}", "catch", "(", "error", ")", "{", "}", "// eslint-disable-line", "if", "(", "!", "EJSON", "...
Facilitate loading EJSON optionally
[ "Facilitate", "loading", "EJSON", "optionally" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/utils.js#L59-L76
13,854
mongodb-js/mongodb-core
lib/utils.js
maxWireVersion
function maxWireVersion(topologyOrServer) { if (topologyOrServer.ismaster) { return topologyOrServer.ismaster.maxWireVersion; } if (topologyOrServer.description) { return topologyOrServer.description.maxWireVersion; } return null; }
javascript
function maxWireVersion(topologyOrServer) { if (topologyOrServer.ismaster) { return topologyOrServer.ismaster.maxWireVersion; } if (topologyOrServer.description) { return topologyOrServer.description.maxWireVersion; } return null; }
[ "function", "maxWireVersion", "(", "topologyOrServer", ")", "{", "if", "(", "topologyOrServer", ".", "ismaster", ")", "{", "return", "topologyOrServer", ".", "ismaster", ".", "maxWireVersion", ";", "}", "if", "(", "topologyOrServer", ".", "description", ")", "{"...
A helper function for determining `maxWireVersion` between legacy and new topology instances @private @param {(Topology|Server)} topologyOrServer
[ "A", "helper", "function", "for", "determining", "maxWireVersion", "between", "legacy", "and", "new", "topology", "instances" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/utils.js#L85-L95
13,855
mongodb-js/mongodb-core
lib/sdam/server_selectors.js
writableServerSelector
function writableServerSelector() { return function(topologyDescription, servers) { return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); }; }
javascript
function writableServerSelector() { return function(topologyDescription, servers) { return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); }; }
[ "function", "writableServerSelector", "(", ")", "{", "return", "function", "(", "topologyDescription", ",", "servers", ")", "{", "return", "latencyWindowReducer", "(", "topologyDescription", ",", "servers", ".", "filter", "(", "s", "=>", "s", ".", "isWritable", ...
Returns a server selector that selects for writable servers
[ "Returns", "a", "server", "selector", "that", "selects", "for", "writable", "servers" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/sdam/server_selectors.js#L14-L18
13,856
mongodb-js/mongodb-core
lib/sdam/server_selectors.js
tagSetMatch
function tagSetMatch(tagSet, serverTags) { const keys = Object.keys(tagSet); const serverTagKeys = Object.keys(serverTags); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { return false; } } return true; }
javascript
function tagSetMatch(tagSet, serverTags) { const keys = Object.keys(tagSet); const serverTagKeys = Object.keys(serverTags); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { return false; } } return true; }
[ "function", "tagSetMatch", "(", "tagSet", ",", "serverTags", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "tagSet", ")", ";", "const", "serverTagKeys", "=", "Object", ".", "keys", "(", "serverTags", ")", ";", "for", "(", "let", "i", "=",...
Determines whether a server's tags match a given set of tags @param {String[]} tagSet The requested tag set to match @param {String[]} serverTags The server's tags
[ "Determines", "whether", "a", "server", "s", "tags", "match", "a", "given", "set", "of", "tags" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/sdam/server_selectors.js#L81-L92
13,857
mongodb-js/mongodb-core
lib/sdam/server_selectors.js
tagSetReducer
function tagSetReducer(readPreference, servers) { if ( readPreference.tags == null || (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) ) { return servers; } for (let i = 0; i < readPreference.tags.length; ++i) { const tagSet = readPreference.tags[i]; const serversMatchingTagset = servers.reduce((matched, server) => { if (tagSetMatch(tagSet, server.tags)) matched.push(server); return matched; }, []); if (serversMatchingTagset.length) { return serversMatchingTagset; } } return []; }
javascript
function tagSetReducer(readPreference, servers) { if ( readPreference.tags == null || (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) ) { return servers; } for (let i = 0; i < readPreference.tags.length; ++i) { const tagSet = readPreference.tags[i]; const serversMatchingTagset = servers.reduce((matched, server) => { if (tagSetMatch(tagSet, server.tags)) matched.push(server); return matched; }, []); if (serversMatchingTagset.length) { return serversMatchingTagset; } } return []; }
[ "function", "tagSetReducer", "(", "readPreference", ",", "servers", ")", "{", "if", "(", "readPreference", ".", "tags", "==", "null", "||", "(", "Array", ".", "isArray", "(", "readPreference", ".", "tags", ")", "&&", "readPreference", ".", "tags", ".", "le...
Reduces a set of server descriptions based on tags requested by the read preference @param {ReadPreference} readPreference The read preference providing the requested tags @param {ServerDescription[]} servers The list of server descriptions to reduce @return {ServerDescription[]} The list of servers matching the requested tags
[ "Reduces", "a", "set", "of", "server", "descriptions", "based", "on", "tags", "requested", "by", "the", "read", "preference" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/sdam/server_selectors.js#L101-L122
13,858
mongodb-js/mongodb-core
lib/auth/defaultAuthProviders.js
defaultAuthProviders
function defaultAuthProviders(bson) { return { mongocr: new MongoCR(bson), x509: new X509(bson), plain: new Plain(bson), gssapi: new GSSAPI(bson), sspi: new SSPI(bson), 'scram-sha-1': new ScramSHA1(bson), 'scram-sha-256': new ScramSHA256(bson) }; }
javascript
function defaultAuthProviders(bson) { return { mongocr: new MongoCR(bson), x509: new X509(bson), plain: new Plain(bson), gssapi: new GSSAPI(bson), sspi: new SSPI(bson), 'scram-sha-1': new ScramSHA1(bson), 'scram-sha-256': new ScramSHA256(bson) }; }
[ "function", "defaultAuthProviders", "(", "bson", ")", "{", "return", "{", "mongocr", ":", "new", "MongoCR", "(", "bson", ")", ",", "x509", ":", "new", "X509", "(", "bson", ")", ",", "plain", ":", "new", "Plain", "(", "bson", ")", ",", "gssapi", ":", ...
Returns the default authentication providers. @param {BSON} bson Bson definition @returns {Object} a mapping of auth names to auth types
[ "Returns", "the", "default", "authentication", "providers", "." ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/auth/defaultAuthProviders.js#L17-L27
13,859
mongodb-js/mongodb-core
lib/connection/pool.js
canCompress
function canCompress(command) { const commandDoc = command instanceof Msg ? command.command : command.query; const commandName = Object.keys(commandDoc)[0]; return uncompressibleCommands.indexOf(commandName) === -1; }
javascript
function canCompress(command) { const commandDoc = command instanceof Msg ? command.command : command.query; const commandName = Object.keys(commandDoc)[0]; return uncompressibleCommands.indexOf(commandName) === -1; }
[ "function", "canCompress", "(", "command", ")", "{", "const", "commandDoc", "=", "command", "instanceof", "Msg", "?", "command", ".", "command", ":", "command", ".", "query", ";", "const", "commandName", "=", "Object", ".", "keys", "(", "commandDoc", ")", ...
Return whether a command contains an uncompressible command term Will return true if command contains no uncompressible command terms
[ "Return", "whether", "a", "command", "contains", "an", "uncompressible", "command", "term", "Will", "return", "true", "if", "command", "contains", "no", "uncompressible", "command", "terms" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/connection/pool.js#L953-L957
13,860
mongodb-js/mongodb-core
lib/connection/pool.js
remove
function remove(connection, connections) { for (var i = 0; i < connections.length; i++) { if (connections[i] === connection) { connections.splice(i, 1); return true; } } }
javascript
function remove(connection, connections) { for (var i = 0; i < connections.length; i++) { if (connections[i] === connection) { connections.splice(i, 1); return true; } } }
[ "function", "remove", "(", "connection", ",", "connections", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "connections", ".", "length", ";", "i", "++", ")", "{", "if", "(", "connections", "[", "i", "]", "===", "connection", ")", "{", ...
Remove connection method
[ "Remove", "connection", "method" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/connection/pool.js#L960-L967
13,861
mongodb-js/mongodb-core
lib/connection/utils.js
retrieveSnappy
function retrieveSnappy() { var snappy = null; try { snappy = require_optional('snappy'); } catch (error) {} // eslint-disable-line if (!snappy) { snappy = { compress: noSnappyWarning, uncompress: noSnappyWarning, compressSync: noSnappyWarning, uncompressSync: noSnappyWarning }; } return snappy; }
javascript
function retrieveSnappy() { var snappy = null; try { snappy = require_optional('snappy'); } catch (error) {} // eslint-disable-line if (!snappy) { snappy = { compress: noSnappyWarning, uncompress: noSnappyWarning, compressSync: noSnappyWarning, uncompressSync: noSnappyWarning }; } return snappy; }
[ "function", "retrieveSnappy", "(", ")", "{", "var", "snappy", "=", "null", ";", "try", "{", "snappy", "=", "require_optional", "(", "'snappy'", ")", ";", "}", "catch", "(", "error", ")", "{", "}", "// eslint-disable-line", "if", "(", "!", "snappy", ")", ...
Facilitate loading Snappy optionally
[ "Facilitate", "loading", "Snappy", "optionally" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/connection/utils.js#L37-L51
13,862
mongodb-js/mongodb-core
lib/uri_parser.js
matchesParentDomain
function matchesParentDomain(srvAddress, parentDomain) { const regex = /^.*?\./; const srv = `.${srvAddress.replace(regex, '')}`; const parent = `.${parentDomain.replace(regex, '')}`; return srv.endsWith(parent); }
javascript
function matchesParentDomain(srvAddress, parentDomain) { const regex = /^.*?\./; const srv = `.${srvAddress.replace(regex, '')}`; const parent = `.${parentDomain.replace(regex, '')}`; return srv.endsWith(parent); }
[ "function", "matchesParentDomain", "(", "srvAddress", ",", "parentDomain", ")", "{", "const", "regex", "=", "/", "^.*?\\.", "/", ";", "const", "srv", "=", "`", "${", "srvAddress", ".", "replace", "(", "regex", ",", "''", ")", "}", "`", ";", "const", "p...
Determines whether a provided address matches the provided parent domain in order to avoid certain attack vectors. @param {String} srvAddress The address to check against a domain @param {String} parentDomain The domain to check the provided address against @return {Boolean} Whether the provided address matches the parent domain
[ "Determines", "whether", "a", "provided", "address", "matches", "the", "provided", "parent", "domain", "in", "order", "to", "avoid", "certain", "attack", "vectors", "." ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/uri_parser.js#L22-L27
13,863
mongodb-js/mongodb-core
lib/uri_parser.js
parseSrvConnectionString
function parseSrvConnectionString(uri, options, callback) { const result = URL.parse(uri, true); if (result.hostname.split('.').length < 3) { return callback(new MongoParseError('URI does not have hostname, domain name and tld')); } result.domainLength = result.hostname.split('.').length; if (result.pathname && result.pathname.match(',')) { return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); } if (result.port) { return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); } // Resolve the SRV record and use the result as the list of hosts to connect to. const lookupAddress = result.host; dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { if (err) return callback(err); if (addresses.length === 0) { return callback(new MongoParseError('No addresses found at host')); } for (let i = 0; i < addresses.length; i++) { if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { return callback( new MongoParseError('Server record does not share hostname with parent URI') ); } } // Convert the original URL to a non-SRV URL. result.protocol = 'mongodb'; result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); // Default to SSL true if it's not specified. if ( !('ssl' in options) && (!result.search || !('ssl' in result.query) || result.query.ssl === null) ) { result.query.ssl = true; } // Resolve TXT record and add options from there if they exist. dns.resolveTxt(lookupAddress, (err, record) => { if (err) { if (err.code !== 'ENODATA') { return callback(err); } record = null; } if (record) { if (record.length > 1) { return callback(new MongoParseError('Multiple text records not allowed')); } record = qs.parse(record[0].join('')); if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { return callback( new MongoParseError('Text record must only set `authSource` or `replicaSet`') ); } Object.assign(result.query, record); } // Set completed options back into the URL object. result.search = qs.stringify(result.query); const finalString = URL.format(result); parseConnectionString(finalString, options, callback); }); }); }
javascript
function parseSrvConnectionString(uri, options, callback) { const result = URL.parse(uri, true); if (result.hostname.split('.').length < 3) { return callback(new MongoParseError('URI does not have hostname, domain name and tld')); } result.domainLength = result.hostname.split('.').length; if (result.pathname && result.pathname.match(',')) { return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); } if (result.port) { return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); } // Resolve the SRV record and use the result as the list of hosts to connect to. const lookupAddress = result.host; dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { if (err) return callback(err); if (addresses.length === 0) { return callback(new MongoParseError('No addresses found at host')); } for (let i = 0; i < addresses.length; i++) { if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { return callback( new MongoParseError('Server record does not share hostname with parent URI') ); } } // Convert the original URL to a non-SRV URL. result.protocol = 'mongodb'; result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); // Default to SSL true if it's not specified. if ( !('ssl' in options) && (!result.search || !('ssl' in result.query) || result.query.ssl === null) ) { result.query.ssl = true; } // Resolve TXT record and add options from there if they exist. dns.resolveTxt(lookupAddress, (err, record) => { if (err) { if (err.code !== 'ENODATA') { return callback(err); } record = null; } if (record) { if (record.length > 1) { return callback(new MongoParseError('Multiple text records not allowed')); } record = qs.parse(record[0].join('')); if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { return callback( new MongoParseError('Text record must only set `authSource` or `replicaSet`') ); } Object.assign(result.query, record); } // Set completed options back into the URL object. result.search = qs.stringify(result.query); const finalString = URL.format(result); parseConnectionString(finalString, options, callback); }); }); }
[ "function", "parseSrvConnectionString", "(", "uri", ",", "options", ",", "callback", ")", "{", "const", "result", "=", "URL", ".", "parse", "(", "uri", ",", "true", ")", ";", "if", "(", "result", ".", "hostname", ".", "split", "(", "'.'", ")", ".", "...
Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal connection string. @param {string} uri The connection string to parse @param {object} options Optional user provided connection string options @param {function} callback
[ "Lookup", "a", "mongodb", "+", "srv", "connection", "string", "combine", "the", "parts", "and", "reparse", "it", "as", "a", "normal", "connection", "string", "." ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/uri_parser.js#L37-L113
13,864
mongodb-js/mongodb-core
lib/uri_parser.js
parseQueryStringItemValue
function parseQueryStringItemValue(key, value) { if (Array.isArray(value)) { // deduplicate and simplify arrays value = value.filter((v, idx) => value.indexOf(v) === idx); if (value.length === 1) value = value[0]; } else if (value.indexOf(':') > 0) { value = value.split(',').reduce((result, pair) => { const parts = pair.split(':'); result[parts[0]] = parseQueryStringItemValue(key, parts[1]); return result; }, {}); } else if (value.indexOf(',') > 0) { value = value.split(',').map(v => { return parseQueryStringItemValue(key, v); }); } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { value = value.toLowerCase() === 'true'; } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { const numericValue = parseFloat(value); if (!Number.isNaN(numericValue)) { value = parseFloat(value); } } return value; }
javascript
function parseQueryStringItemValue(key, value) { if (Array.isArray(value)) { // deduplicate and simplify arrays value = value.filter((v, idx) => value.indexOf(v) === idx); if (value.length === 1) value = value[0]; } else if (value.indexOf(':') > 0) { value = value.split(',').reduce((result, pair) => { const parts = pair.split(':'); result[parts[0]] = parseQueryStringItemValue(key, parts[1]); return result; }, {}); } else if (value.indexOf(',') > 0) { value = value.split(',').map(v => { return parseQueryStringItemValue(key, v); }); } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { value = value.toLowerCase() === 'true'; } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { const numericValue = parseFloat(value); if (!Number.isNaN(numericValue)) { value = parseFloat(value); } } return value; }
[ "function", "parseQueryStringItemValue", "(", "key", ",", "value", ")", "{", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "// deduplicate and simplify arrays", "value", "=", "value", ".", "filter", "(", "(", "v", ",", "idx", ")", "=>", ...
Parses a query string item according to the connection string spec @param {string} key The key for the parsed value @param {Array|String} value The value to parse @return {Array|Object|String} The parsed value
[ "Parses", "a", "query", "string", "item", "according", "to", "the", "connection", "string", "spec" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/uri_parser.js#L122-L147
13,865
mongodb-js/mongodb-core
lib/uri_parser.js
applyConnectionStringOption
function applyConnectionStringOption(obj, key, value, options) { // simple key translation if (key === 'journal') { key = 'j'; } else if (key === 'wtimeoutms') { key = 'wtimeout'; } // more complicated translation if (BOOLEAN_OPTIONS.has(key)) { value = value === 'true' || value === true; } else if (key === 'appname') { value = decodeURIComponent(value); } else if (key === 'readconcernlevel') { obj['readConcernLevel'] = value; key = 'readconcern'; value = { level: value }; } // simple validation if (key === 'compressors') { value = Array.isArray(value) ? value : [value]; if (!value.every(c => c === 'snappy' || c === 'zlib')) { throw new MongoParseError( 'Value for `compressors` must be at least one of: `snappy`, `zlib`' ); } } if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { throw new MongoParseError( 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' ); } if (key === 'readpreference' && !ReadPreference.isValid(value)) { throw new MongoParseError( 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' ); } if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); } // special cases if (key === 'compressors' || key === 'zlibcompressionlevel') { obj.compression = obj.compression || {}; obj = obj.compression; } if (key === 'authmechanismproperties') { if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; } } if (key === 'readpreferencetags' && Array.isArray(value)) { value = splitArrayOfMultipleReadPreferenceTags(value); } // set the actual value if (options.caseTranslate && CASE_TRANSLATION[key]) { obj[CASE_TRANSLATION[key]] = value; return; } obj[key] = value; }
javascript
function applyConnectionStringOption(obj, key, value, options) { // simple key translation if (key === 'journal') { key = 'j'; } else if (key === 'wtimeoutms') { key = 'wtimeout'; } // more complicated translation if (BOOLEAN_OPTIONS.has(key)) { value = value === 'true' || value === true; } else if (key === 'appname') { value = decodeURIComponent(value); } else if (key === 'readconcernlevel') { obj['readConcernLevel'] = value; key = 'readconcern'; value = { level: value }; } // simple validation if (key === 'compressors') { value = Array.isArray(value) ? value : [value]; if (!value.every(c => c === 'snappy' || c === 'zlib')) { throw new MongoParseError( 'Value for `compressors` must be at least one of: `snappy`, `zlib`' ); } } if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { throw new MongoParseError( 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' ); } if (key === 'readpreference' && !ReadPreference.isValid(value)) { throw new MongoParseError( 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' ); } if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); } // special cases if (key === 'compressors' || key === 'zlibcompressionlevel') { obj.compression = obj.compression || {}; obj = obj.compression; } if (key === 'authmechanismproperties') { if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; } } if (key === 'readpreferencetags' && Array.isArray(value)) { value = splitArrayOfMultipleReadPreferenceTags(value); } // set the actual value if (options.caseTranslate && CASE_TRANSLATION[key]) { obj[CASE_TRANSLATION[key]] = value; return; } obj[key] = value; }
[ "function", "applyConnectionStringOption", "(", "obj", ",", "key", ",", "value", ",", "options", ")", "{", "// simple key translation", "if", "(", "key", "===", "'journal'", ")", "{", "key", "=", "'j'", ";", "}", "else", "if", "(", "key", "===", "'wtimeout...
Sets the value for `key`, allowing for any required translation @param {object} obj The object to set the key on @param {string} key The key to set the value for @param {*} value The value to set @param {object} options The options used for option parsing
[ "Sets", "the", "value", "for", "key", "allowing", "for", "any", "required", "translation" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/uri_parser.js#L221-L292
13,866
mongodb-js/mongodb-core
lib/uri_parser.js
applyAuthExpectations
function applyAuthExpectations(parsed) { if (parsed.options == null) { return; } const options = parsed.options; const authSource = options.authsource || options.authSource; if (authSource != null) { parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); } const authMechanism = options.authmechanism || options.authMechanism; if (authMechanism != null) { if ( USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && (!parsed.auth || parsed.auth.username == null) ) { throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); } if (authMechanism === 'GSSAPI') { if (authSource != null && authSource !== '$external') { throw new MongoParseError( `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` ); } parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } if (authMechanism === 'MONGODB-X509') { if (parsed.auth && parsed.auth.password != null) { throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); } if (authSource != null && authSource !== '$external') { throw new MongoParseError( `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` ); } parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } if (authMechanism === 'PLAIN') { if (parsed.auth && parsed.auth.db == null) { parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } } } // default to `admin` if nothing else was resolved if (parsed.auth && parsed.auth.db == null) { parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); } return parsed; }
javascript
function applyAuthExpectations(parsed) { if (parsed.options == null) { return; } const options = parsed.options; const authSource = options.authsource || options.authSource; if (authSource != null) { parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); } const authMechanism = options.authmechanism || options.authMechanism; if (authMechanism != null) { if ( USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && (!parsed.auth || parsed.auth.username == null) ) { throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); } if (authMechanism === 'GSSAPI') { if (authSource != null && authSource !== '$external') { throw new MongoParseError( `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` ); } parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } if (authMechanism === 'MONGODB-X509') { if (parsed.auth && parsed.auth.password != null) { throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); } if (authSource != null && authSource !== '$external') { throw new MongoParseError( `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` ); } parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } if (authMechanism === 'PLAIN') { if (parsed.auth && parsed.auth.db == null) { parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } } } // default to `admin` if nothing else was resolved if (parsed.auth && parsed.auth.db == null) { parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); } return parsed; }
[ "function", "applyAuthExpectations", "(", "parsed", ")", "{", "if", "(", "parsed", ".", "options", "==", "null", ")", "{", "return", ";", "}", "const", "options", "=", "parsed", ".", "options", ";", "const", "authSource", "=", "options", ".", "authsource",...
Modifies the parsed connection string object taking into account expectations we have for authentication-related options. @param {object} parsed The parsed connection string result @return The parsed connection string result possibly modified for auth expectations
[ "Modifies", "the", "parsed", "connection", "string", "object", "taking", "into", "account", "expectations", "we", "have", "for", "authentication", "-", "related", "options", "." ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/uri_parser.js#L323-L380
13,867
mongodb-js/mongodb-core
lib/uri_parser.js
checkTLSOptions
function checkTLSOptions(queryString) { const queryStringKeys = Object.keys(queryString); if ( queryStringKeys.indexOf('tlsInsecure') !== -1 && (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) ) { throw new MongoParseError( 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' ); } const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); if (tlsValue != null && sslValue != null) { if (tlsValue !== sslValue) { throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); } } }
javascript
function checkTLSOptions(queryString) { const queryStringKeys = Object.keys(queryString); if ( queryStringKeys.indexOf('tlsInsecure') !== -1 && (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) ) { throw new MongoParseError( 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' ); } const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); if (tlsValue != null && sslValue != null) { if (tlsValue !== sslValue) { throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); } } }
[ "function", "checkTLSOptions", "(", "queryString", ")", "{", "const", "queryStringKeys", "=", "Object", ".", "keys", "(", "queryString", ")", ";", "if", "(", "queryStringKeys", ".", "indexOf", "(", "'tlsInsecure'", ")", "!==", "-", "1", "&&", "(", "queryStri...
Checks a query string for invalid tls options according to the URI options spec. @param {string} queryString The query string to check @throws {MongoParseError}
[ "Checks", "a", "query", "string", "for", "invalid", "tls", "options", "according", "to", "the", "URI", "options", "spec", "." ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/uri_parser.js#L421-L441
13,868
mongodb-js/mongodb-core
lib/topologies/replset.js
function(self, server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); // Execute ismaster // Set the socketTimeout for a monitoring message to a low number // Ensuring ismaster calls are timed out quickly server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { server.destroy({ force: true }); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // Set the last updatedTime var hrTime = process.hrtime(); // Calculate the last update time server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1] / 1000); // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: server.name }); // Remove server from the state self.s.replicaSetState.remove(server); } else { // Update the server ismaster server.ismaster = r.result; // Check if we have a lastWriteDate convert it to MS // and store on the server instance for later use if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); } // Do we have a brand new server if (server.lastIsMasterMS === -1) { server.lastIsMasterMS = latencyMS; } else if (server.lastIsMasterMS) { // After the first measurement, average RTT MUST be computed using an // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. // If the prior average is denoted old_rtt, then the new average (new_rtt) is // computed from a new RTT measurement (x) using the following formula: // alpha = 0.2 // new_rtt = alpha * x + (1 - alpha) * old_rtt server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; } if (self.s.replicaSetState.update(server)) { // Primary lastIsMaster store it if (server.lastIsMaster() && server.lastIsMaster().ismaster) { self.ismaster = server.lastIsMaster(); } } // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: server.name }); } // Calculate the staleness for this server self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); // Callback cb(err, r); } ); }
javascript
function(self, server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); // Execute ismaster // Set the socketTimeout for a monitoring message to a low number // Ensuring ismaster calls are timed out quickly server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { server.destroy({ force: true }); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // Set the last updatedTime var hrTime = process.hrtime(); // Calculate the last update time server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1] / 1000); // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: server.name }); // Remove server from the state self.s.replicaSetState.remove(server); } else { // Update the server ismaster server.ismaster = r.result; // Check if we have a lastWriteDate convert it to MS // and store on the server instance for later use if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); } // Do we have a brand new server if (server.lastIsMasterMS === -1) { server.lastIsMasterMS = latencyMS; } else if (server.lastIsMasterMS) { // After the first measurement, average RTT MUST be computed using an // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. // If the prior average is denoted old_rtt, then the new average (new_rtt) is // computed from a new RTT measurement (x) using the following formula: // alpha = 0.2 // new_rtt = alpha * x + (1 - alpha) * old_rtt server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; } if (self.s.replicaSetState.update(server)) { // Primary lastIsMaster store it if (server.lastIsMaster() && server.lastIsMaster().ismaster) { self.ismaster = server.lastIsMaster(); } } // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: server.name }); } // Calculate the staleness for this server self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); // Callback cb(err, r); } ); }
[ "function", "(", "self", ",", "server", ",", "cb", ")", "{", "// Measure running time", "var", "start", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "// Emit the server heartbeat start", "emitSDAMEvent", "(", "self", ",", "'serverHeartbeatStarted...
Ping the server
[ "Ping", "the", "server" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/replset.js#L390-L478
13,869
mongodb-js/mongodb-core
lib/topologies/replset.js
function(host, self, options) { // If this is not the initial scan // Is this server already being monitoried, then skip monitoring if (!options.haInterval) { for (var i = 0; i < self.intervalIds.length; i++) { if (self.intervalIds[i].__host === host) { return; } } } // Get the haInterval var _process = options.haInterval ? Timeout : Interval; var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; // Create the interval var intervalId = new _process(function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { // clearInterval(intervalId); intervalId.stop(); return; } // Do we already have server connection available for this host var _server = self.s.replicaSetState.get(host); // Check if we have a known server connection and reuse if (_server) { // Ping the server return pingServer(self, _server, function(err) { if (err) { // NOTE: should something happen here? return; } if (self.state === DESTROYED || self.state === UNREFERENCED) { intervalId.stop(); return; } // Filter out all called intervaliIds self.intervalIds = self.intervalIds.filter(function(intervalId) { return intervalId.isRunning(); }); // Initial sweep if (_process === Timeout) { if ( self.state === CONNECTING && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Emit connected sign process.nextTick(function() { self.emit('connect', self); }); // Start topology interval check topologyMonitor(self, {}); } } else { if ( self.state === DISCONNECTED && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Rexecute any stalled operation rexecuteOperations(self); // Emit connected sign process.nextTick(function() { self.emit('reconnect', self); }); } } if ( self.initialConnectState.connect && !self.initialConnectState.fullsetup && self.s.replicaSetState.hasPrimaryAndSecondary() ) { // Set initial connect state self.initialConnectState.fullsetup = true; self.initialConnectState.all = true; process.nextTick(function() { self.emit('fullsetup', self); self.emit('all', self); }); } }); } }, _haInterval); // Start the interval intervalId.start(); // Add the intervalId host name intervalId.__host = host; // Add the intervalId to our list of intervalIds self.intervalIds.push(intervalId); }
javascript
function(host, self, options) { // If this is not the initial scan // Is this server already being monitoried, then skip monitoring if (!options.haInterval) { for (var i = 0; i < self.intervalIds.length; i++) { if (self.intervalIds[i].__host === host) { return; } } } // Get the haInterval var _process = options.haInterval ? Timeout : Interval; var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; // Create the interval var intervalId = new _process(function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { // clearInterval(intervalId); intervalId.stop(); return; } // Do we already have server connection available for this host var _server = self.s.replicaSetState.get(host); // Check if we have a known server connection and reuse if (_server) { // Ping the server return pingServer(self, _server, function(err) { if (err) { // NOTE: should something happen here? return; } if (self.state === DESTROYED || self.state === UNREFERENCED) { intervalId.stop(); return; } // Filter out all called intervaliIds self.intervalIds = self.intervalIds.filter(function(intervalId) { return intervalId.isRunning(); }); // Initial sweep if (_process === Timeout) { if ( self.state === CONNECTING && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Emit connected sign process.nextTick(function() { self.emit('connect', self); }); // Start topology interval check topologyMonitor(self, {}); } } else { if ( self.state === DISCONNECTED && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Rexecute any stalled operation rexecuteOperations(self); // Emit connected sign process.nextTick(function() { self.emit('reconnect', self); }); } } if ( self.initialConnectState.connect && !self.initialConnectState.fullsetup && self.s.replicaSetState.hasPrimaryAndSecondary() ) { // Set initial connect state self.initialConnectState.fullsetup = true; self.initialConnectState.all = true; process.nextTick(function() { self.emit('fullsetup', self); self.emit('all', self); }); } }); } }, _haInterval); // Start the interval intervalId.start(); // Add the intervalId host name intervalId.__host = host; // Add the intervalId to our list of intervalIds self.intervalIds.push(intervalId); }
[ "function", "(", "host", ",", "self", ",", "options", ")", "{", "// If this is not the initial scan", "// Is this server already being monitoried, then skip monitoring", "if", "(", "!", "options", ".", "haInterval", ")", "{", "for", "(", "var", "i", "=", "0", ";", ...
Each server is monitored in parallel in their own timeout loop
[ "Each", "server", "is", "monitored", "in", "parallel", "in", "their", "own", "timeout", "loop" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/replset.js#L481-L587
13,870
mongodb-js/mongodb-core
lib/topologies/replset.js
executeReconnect
function executeReconnect(self) { return function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { return; } connectNewServers(self, self.s.replicaSetState.unknownServers, function() { var monitoringFrequencey = self.s.replicaSetState.hasPrimary() ? _haInterval : self.s.minHeartbeatFrequencyMS; // Create a timeout self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); }); }; }
javascript
function executeReconnect(self) { return function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { return; } connectNewServers(self, self.s.replicaSetState.unknownServers, function() { var monitoringFrequencey = self.s.replicaSetState.hasPrimary() ? _haInterval : self.s.minHeartbeatFrequencyMS; // Create a timeout self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); }); }; }
[ "function", "executeReconnect", "(", "self", ")", "{", "return", "function", "(", ")", "{", "if", "(", "self", ".", "state", "===", "DESTROYED", "||", "self", ".", "state", "===", "UNREFERENCED", ")", "{", "return", ";", "}", "connectNewServers", "(", "s...
Run the reconnect process
[ "Run", "the", "reconnect", "process" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/replset.js#L643-L658
13,871
mongodb-js/mongodb-core
lib/topologies/replset.js
emitSDAMEvent
function emitSDAMEvent(self, event, description) { if (self.listeners(event).length > 0) { self.emit(event, description); } }
javascript
function emitSDAMEvent(self, event, description) { if (self.listeners(event).length > 0) { self.emit(event, description); } }
[ "function", "emitSDAMEvent", "(", "self", ",", "event", ",", "description", ")", "{", "if", "(", "self", ".", "listeners", "(", "event", ")", ".", "length", ">", "0", ")", "{", "self", ".", "emit", "(", "event", ",", "description", ")", ";", "}", "...
Emit event if it exists @method
[ "Emit", "event", "if", "it", "exists" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/replset.js#L884-L888
13,872
mongodb-js/mongodb-core
lib/topologies/replset.js
executeWriteOperation
function executeWriteOperation(args, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // TODO: once we drop Node 4, use destructuring either here or in arguments. const self = args.self; const op = args.op; const ns = args.ns; const ops = args.ops; if (self.state === DESTROYED) { return callback(new MongoError(f('topology was destroyed'))); } const willRetryWrite = !args.retrying && !!options.retryWrites && options.session && isRetryableWritesSupported(self) && !options.session.inTransaction(); if (!self.s.replicaSetState.hasPrimary()) { if (self.s.disconnectHandler) { // Not connected but we have a disconnecthandler return self.s.disconnectHandler.add(op, ns, ops, options, callback); } else if (!willRetryWrite) { // No server returned we had an error return callback(new MongoError('no primary server found')); } } const handler = (err, result) => { if (!err) return callback(null, result); if (!isRetryableError(err)) { return callback(err); } if (willRetryWrite) { const newArgs = Object.assign({}, args, { retrying: true }); return executeWriteOperation(newArgs, options, callback); } // Per SDAM, remove primary from replicaset if (self.s.replicaSetState.primary) { self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); } return callback(err); }; if (callback.operationId) { handler.operationId = callback.operationId; } // increment and assign txnNumber if (willRetryWrite) { options.session.incrementTransactionNumber(); options.willRetryWrite = willRetryWrite; } self.s.replicaSetState.primary[op](ns, ops, options, handler); }
javascript
function executeWriteOperation(args, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // TODO: once we drop Node 4, use destructuring either here or in arguments. const self = args.self; const op = args.op; const ns = args.ns; const ops = args.ops; if (self.state === DESTROYED) { return callback(new MongoError(f('topology was destroyed'))); } const willRetryWrite = !args.retrying && !!options.retryWrites && options.session && isRetryableWritesSupported(self) && !options.session.inTransaction(); if (!self.s.replicaSetState.hasPrimary()) { if (self.s.disconnectHandler) { // Not connected but we have a disconnecthandler return self.s.disconnectHandler.add(op, ns, ops, options, callback); } else if (!willRetryWrite) { // No server returned we had an error return callback(new MongoError('no primary server found')); } } const handler = (err, result) => { if (!err) return callback(null, result); if (!isRetryableError(err)) { return callback(err); } if (willRetryWrite) { const newArgs = Object.assign({}, args, { retrying: true }); return executeWriteOperation(newArgs, options, callback); } // Per SDAM, remove primary from replicaset if (self.s.replicaSetState.primary) { self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); } return callback(err); }; if (callback.operationId) { handler.operationId = callback.operationId; } // increment and assign txnNumber if (willRetryWrite) { options.session.incrementTransactionNumber(); options.willRetryWrite = willRetryWrite; } self.s.replicaSetState.primary[op](ns, ops, options, handler); }
[ "function", "executeWriteOperation", "(", "args", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "(", "callback", "=", "options", ")", ",", "(", "options", "=", "{", "}", ")", ";", "options", "=", "...
Execute write operation
[ "Execute", "write", "operation" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/replset.js#L1123-L1184
13,873
mongodb-js/mongodb-core
lib/auth/scram.js
xor
function xor(a, b) { if (!Buffer.isBuffer(a)) a = Buffer.from(a); if (!Buffer.isBuffer(b)) b = Buffer.from(b); const length = Math.max(a.length, b.length); const res = []; for (let i = 0; i < length; i += 1) { res.push(a[i] ^ b[i]); } return Buffer.from(res).toString('base64'); }
javascript
function xor(a, b) { if (!Buffer.isBuffer(a)) a = Buffer.from(a); if (!Buffer.isBuffer(b)) b = Buffer.from(b); const length = Math.max(a.length, b.length); const res = []; for (let i = 0; i < length; i += 1) { res.push(a[i] ^ b[i]); } return Buffer.from(res).toString('base64'); }
[ "function", "xor", "(", "a", ",", "b", ")", "{", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "a", ")", ")", "a", "=", "Buffer", ".", "from", "(", "a", ")", ";", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "b", ")", ")", "b", "=", ...
XOR two buffers
[ "XOR", "two", "buffers" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/auth/scram.js#L43-L54
13,874
mongodb-js/mongodb-core
lib/error.js
isRetryableError
function isRetryableError(error) { return ( RETRYABLE_ERROR_CODES.has(error.code) || error instanceof MongoNetworkError || error.message.match(/not master/) || error.message.match(/node is recovering/) ); }
javascript
function isRetryableError(error) { return ( RETRYABLE_ERROR_CODES.has(error.code) || error instanceof MongoNetworkError || error.message.match(/not master/) || error.message.match(/node is recovering/) ); }
[ "function", "isRetryableError", "(", "error", ")", "{", "return", "(", "RETRYABLE_ERROR_CODES", ".", "has", "(", "error", ".", "code", ")", "||", "error", "instanceof", "MongoNetworkError", "||", "error", ".", "message", ".", "match", "(", "/", "not master", ...
Determines whether an error is something the driver should attempt to retry @param {MongoError|Error} error
[ "Determines", "whether", "an", "error", "is", "something", "the", "driver", "should", "attempt", "to", "retry" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/error.js#L146-L153
13,875
mongodb-js/mongodb-core
lib/sdam/server_description.js
parseServerType
function parseServerType(ismaster) { if (!ismaster || !ismaster.ok) { return ServerType.Unknown; } if (ismaster.isreplicaset) { return ServerType.RSGhost; } if (ismaster.msg && ismaster.msg === 'isdbgrid') { return ServerType.Mongos; } if (ismaster.setName) { if (ismaster.hidden) { return ServerType.RSOther; } else if (ismaster.ismaster) { return ServerType.RSPrimary; } else if (ismaster.secondary) { return ServerType.RSSecondary; } else if (ismaster.arbiterOnly) { return ServerType.RSArbiter; } else { return ServerType.RSOther; } } return ServerType.Standalone; }
javascript
function parseServerType(ismaster) { if (!ismaster || !ismaster.ok) { return ServerType.Unknown; } if (ismaster.isreplicaset) { return ServerType.RSGhost; } if (ismaster.msg && ismaster.msg === 'isdbgrid') { return ServerType.Mongos; } if (ismaster.setName) { if (ismaster.hidden) { return ServerType.RSOther; } else if (ismaster.ismaster) { return ServerType.RSPrimary; } else if (ismaster.secondary) { return ServerType.RSSecondary; } else if (ismaster.arbiterOnly) { return ServerType.RSArbiter; } else { return ServerType.RSOther; } } return ServerType.Standalone; }
[ "function", "parseServerType", "(", "ismaster", ")", "{", "if", "(", "!", "ismaster", "||", "!", "ismaster", ".", "ok", ")", "{", "return", "ServerType", ".", "Unknown", ";", "}", "if", "(", "ismaster", ".", "isreplicaset", ")", "{", "return", "ServerTyp...
Parses an `ismaster` message and determines the server type @param {Object} ismaster The `ismaster` message to parse @return {ServerType}
[ "Parses", "an", "ismaster", "message", "and", "determines", "the", "server", "type" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/sdam/server_description.js#L116-L144
13,876
mongodb-js/mongodb-core
lib/sdam/topology.js
destroyServer
function destroyServer(server, topology, callback) { LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); server.destroy(() => { topology.emit( 'serverClosed', new monitoring.ServerClosedEvent(topology.s.id, server.description.address) ); if (typeof callback === 'function') callback(null, null); }); }
javascript
function destroyServer(server, topology, callback) { LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); server.destroy(() => { topology.emit( 'serverClosed', new monitoring.ServerClosedEvent(topology.s.id, server.description.address) ); if (typeof callback === 'function') callback(null, null); }); }
[ "function", "destroyServer", "(", "server", ",", "topology", ",", "callback", ")", "{", "LOCAL_SERVER_EVENTS", ".", "forEach", "(", "event", "=>", "server", ".", "removeAllListeners", "(", "event", ")", ")", ";", "server", ".", "destroy", "(", "(", ")", "=...
Destroys a server, and removes all event listeners from the instance @param {Server} server
[ "Destroys", "a", "server", "and", "removes", "all", "event", "listeners", "from", "the", "instance" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/sdam/topology.js#L652-L663
13,877
mongodb-js/mongodb-core
lib/sdam/topology.js
parseStringSeedlist
function parseStringSeedlist(seedlist) { return seedlist.split(',').map(seed => ({ host: seed.split(':')[0], port: seed.split(':')[1] || 27017 })); }
javascript
function parseStringSeedlist(seedlist) { return seedlist.split(',').map(seed => ({ host: seed.split(':')[0], port: seed.split(':')[1] || 27017 })); }
[ "function", "parseStringSeedlist", "(", "seedlist", ")", "{", "return", "seedlist", ".", "split", "(", "','", ")", ".", "map", "(", "seed", "=>", "(", "{", "host", ":", "seed", ".", "split", "(", "':'", ")", "[", "0", "]", ",", "port", ":", "seed",...
Parses a basic seedlist in string form @param {string} seedlist The seedlist to parse
[ "Parses", "a", "basic", "seedlist", "in", "string", "form" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/sdam/topology.js#L670-L675
13,878
mongodb-js/mongodb-core
lib/sdam/topology.js
resetServerState
function resetServerState(server, error, options) { options = Object.assign({}, { clearPool: false }, options); function resetState() { server.emit( 'descriptionReceived', new ServerDescription(server.description.address, null, { error }) ); } if (options.clearPool && server.pool) { server.pool.reset(() => resetState()); return; } resetState(); }
javascript
function resetServerState(server, error, options) { options = Object.assign({}, { clearPool: false }, options); function resetState() { server.emit( 'descriptionReceived', new ServerDescription(server.description.address, null, { error }) ); } if (options.clearPool && server.pool) { server.pool.reset(() => resetState()); return; } resetState(); }
[ "function", "resetServerState", "(", "server", ",", "error", ",", "options", ")", "{", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "{", "clearPool", ":", "false", "}", ",", "options", ")", ";", "function", "resetState", "(", ")", "{", ...
Resets the internal state of this server to `Unknown` by simulating an empty ismaster @private @param {Server} server @param {MongoError} error The error that caused the state reset @param {object} [options] Optional settings @param {boolean} [options.clearPool=false] Pool should be cleared out on state reset
[ "Resets", "the", "internal", "state", "of", "this", "server", "to", "Unknown", "by", "simulating", "an", "empty", "ismaster" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/sdam/topology.js#L930-L946
13,879
mongodb-js/mongodb-core
lib/topologies/mongos.js
function(seedlist, options) { options = options || {}; // Get replSet Id this.id = id++; // Internal state this.s = { options: Object.assign({}, options), // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // Logger instance logger: Logger('Mongos', options), // Seedlist seedlist: seedlist, // Ha interval haInterval: options.haInterval ? options.haInterval : 10000, // Disconnect handler disconnectHandler: options.disconnectHandler, // Server selection index index: 0, // Connect function options passed in connectOptions: {}, // Are we running in debug mode debug: typeof options.debug === 'boolean' ? options.debug : false, // localThresholdMS localThresholdMS: options.localThresholdMS || 15, // Client info clientInfo: createClientInfo(options) }; // Set the client info this.s.options.clientInfo = createClientInfo(options); // Log info warning if the socketTimeout < haInterval as it will cause // a lot of recycled connections to happen. if ( this.s.logger.isWarn() && this.s.options.socketTimeout !== 0 && this.s.options.socketTimeout < this.s.haInterval ) { this.s.logger.warn( f( 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', this.s.options.socketTimeout, this.s.haInterval ) ); } // Disconnected state this.state = DISCONNECTED; // Current proxies we are connecting to this.connectingProxies = []; // Currently connected proxies this.connectedProxies = []; // Disconnected proxies this.disconnectedProxies = []; // Index of proxy to run operations against this.index = 0; // High availability timeout id this.haTimeoutId = null; // Last ismaster this.ismaster = null; // Description of the Replicaset this.topologyDescription = { topologyType: 'Unknown', servers: [] }; // Highest clusterTime seen in responses from the current deployment this.clusterTime = null; // Add event listener EventEmitter.call(this); }
javascript
function(seedlist, options) { options = options || {}; // Get replSet Id this.id = id++; // Internal state this.s = { options: Object.assign({}, options), // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // Logger instance logger: Logger('Mongos', options), // Seedlist seedlist: seedlist, // Ha interval haInterval: options.haInterval ? options.haInterval : 10000, // Disconnect handler disconnectHandler: options.disconnectHandler, // Server selection index index: 0, // Connect function options passed in connectOptions: {}, // Are we running in debug mode debug: typeof options.debug === 'boolean' ? options.debug : false, // localThresholdMS localThresholdMS: options.localThresholdMS || 15, // Client info clientInfo: createClientInfo(options) }; // Set the client info this.s.options.clientInfo = createClientInfo(options); // Log info warning if the socketTimeout < haInterval as it will cause // a lot of recycled connections to happen. if ( this.s.logger.isWarn() && this.s.options.socketTimeout !== 0 && this.s.options.socketTimeout < this.s.haInterval ) { this.s.logger.warn( f( 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', this.s.options.socketTimeout, this.s.haInterval ) ); } // Disconnected state this.state = DISCONNECTED; // Current proxies we are connecting to this.connectingProxies = []; // Currently connected proxies this.connectedProxies = []; // Disconnected proxies this.disconnectedProxies = []; // Index of proxy to run operations against this.index = 0; // High availability timeout id this.haTimeoutId = null; // Last ismaster this.ismaster = null; // Description of the Replicaset this.topologyDescription = { topologyType: 'Unknown', servers: [] }; // Highest clusterTime seen in responses from the current deployment this.clusterTime = null; // Add event listener EventEmitter.call(this); }
[ "function", "(", "seedlist", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// Get replSet Id", "this", ".", "id", "=", "id", "++", ";", "// Internal state", "this", ".", "s", "=", "{", "options", ":", "Object", ".", "assign...
Creates a new Mongos instance @class @param {array} seedlist A list of seeds for the replicaset @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors @param {number} [options.size=5] Server connection pool size @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection @param {boolean} [options.noDelay=true] TCP Connection no delay @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting @param {number} [options.socketTimeout=0] TCP Socket timeout setting @param {boolean} [options.ssl=false] Use SSL for connection @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. @param {Buffer} [options.ca] SSL Certificate store binary buffer @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer @param {Buffer} [options.cert] SSL Certificate binary buffer @param {Buffer} [options.key] SSL Key file binary buffer @param {string} [options.passphrase] SSL Certificate pass phrase @param {string} [options.servername=null] String containing the server name requested via TLS SNI. @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology @return {Mongos} A cursor instance @fires Mongos#connect @fires Mongos#reconnect @fires Mongos#joined @fires Mongos#left @fires Mongos#failed @fires Mongos#fullsetup @fires Mongos#all @fires Mongos#serverHeartbeatStarted @fires Mongos#serverHeartbeatSucceeded @fires Mongos#serverHeartbeatFailed @fires Mongos#topologyOpening @fires Mongos#topologyClosed @fires Mongos#topologyDescriptionChanged @property {string} type the topology type. @property {string} parserType the parser type used (c++ or js).
[ "Creates", "a", "new", "Mongos", "instance" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/mongos.js#L123-L219
13,880
mongodb-js/mongodb-core
lib/topologies/mongos.js
pingServer
function pingServer(_self, _server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); // Execute ismaster _server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { // Move from connectingProxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); _server.destroy(); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name }); // Move from connected proxies to disconnected proxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); } else { // Update the server ismaster _server.ismaster = r.result; _server.lastIsMasterMS = latencyMS; // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name }); } cb(err, r); } ); }
javascript
function pingServer(_self, _server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); // Execute ismaster _server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { // Move from connectingProxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); _server.destroy(); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name }); // Move from connected proxies to disconnected proxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); } else { // Update the server ismaster _server.ismaster = r.result; _server.lastIsMasterMS = latencyMS; // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name }); } cb(err, r); } ); }
[ "function", "pingServer", "(", "_self", ",", "_server", ",", "cb", ")", "{", "// Measure running time", "var", "start", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "// Emit the server heartbeat start", "emitSDAMEvent", "(", "self", ",", "'serv...
If the count is zero schedule a new fast
[ "If", "the", "count", "is", "zero", "schedule", "a", "new", "fast" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/mongos.js#L676-L730
13,881
mongodb-js/mongodb-core
lib/topologies/shared.js
resolveClusterTime
function resolveClusterTime(topology, $clusterTime) { if (topology.clusterTime == null) { topology.clusterTime = $clusterTime; } else { if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { topology.clusterTime = $clusterTime; } } }
javascript
function resolveClusterTime(topology, $clusterTime) { if (topology.clusterTime == null) { topology.clusterTime = $clusterTime; } else { if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { topology.clusterTime = $clusterTime; } } }
[ "function", "resolveClusterTime", "(", "topology", ",", "$clusterTime", ")", "{", "if", "(", "topology", ".", "clusterTime", "==", "null", ")", "{", "topology", ".", "clusterTime", "=", "$clusterTime", ";", "}", "else", "{", "if", "(", "$clusterTime", ".", ...
Shared function to determine clusterTime for a given topology @param {*} topology @param {*} clusterTime
[ "Shared", "function", "to", "determine", "clusterTime", "for", "a", "given", "topology" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/shared.js#L366-L374
13,882
mongodb-js/mongodb-core
lib/topologies/shared.js
function(topology) { const maxWireVersion = topology.lastIsMaster().maxWireVersion; if (maxWireVersion < RETRYABLE_WIRE_VERSION) { return false; } if (!topology.logicalSessionTimeoutMinutes) { return false; } if (topologyType(topology) === TopologyType.Single) { return false; } return true; }
javascript
function(topology) { const maxWireVersion = topology.lastIsMaster().maxWireVersion; if (maxWireVersion < RETRYABLE_WIRE_VERSION) { return false; } if (!topology.logicalSessionTimeoutMinutes) { return false; } if (topologyType(topology) === TopologyType.Single) { return false; } return true; }
[ "function", "(", "topology", ")", "{", "const", "maxWireVersion", "=", "topology", ".", "lastIsMaster", "(", ")", ".", "maxWireVersion", ";", "if", "(", "maxWireVersion", "<", "RETRYABLE_WIRE_VERSION", ")", "{", "return", "false", ";", "}", "if", "(", "!", ...
Determines whether the provided topology supports retryable writes @param {Mongos|Replset} topology
[ "Determines", "whether", "the", "provided", "topology", "supports", "retryable", "writes" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/shared.js#L423-L438
13,883
mongodb-js/mongodb-core
lib/topologies/replset_state.js
function(readPreference, servers) { if (readPreference.tags == null) return servers; var filteredServers = []; var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; // Iterate over the tags for (var j = 0; j < tagsArray.length; j++) { var tags = tagsArray[j]; // Iterate over all the servers for (var i = 0; i < servers.length; i++) { var serverTag = servers[i].lastIsMaster().tags || {}; // Did we find the a matching server var found = true; // Check if the server is valid for (var name in tags) { if (serverTag[name] !== tags[name]) { found = false; } } // Add to candidate list if (found) { filteredServers.push(servers[i]); } } } // Returned filtered servers return filteredServers; }
javascript
function(readPreference, servers) { if (readPreference.tags == null) return servers; var filteredServers = []; var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; // Iterate over the tags for (var j = 0; j < tagsArray.length; j++) { var tags = tagsArray[j]; // Iterate over all the servers for (var i = 0; i < servers.length; i++) { var serverTag = servers[i].lastIsMaster().tags || {}; // Did we find the a matching server var found = true; // Check if the server is valid for (var name in tags) { if (serverTag[name] !== tags[name]) { found = false; } } // Add to candidate list if (found) { filteredServers.push(servers[i]); } } } // Returned filtered servers return filteredServers; }
[ "function", "(", "readPreference", ",", "servers", ")", "{", "if", "(", "readPreference", ".", "tags", "==", "null", ")", "return", "servers", ";", "var", "filteredServers", "=", "[", "]", ";", "var", "tagsArray", "=", "Array", ".", "isArray", "(", "read...
Filter serves by tags
[ "Filter", "serves", "by", "tags" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/replset_state.js#L837-L868
13,884
mongodb-js/mongodb-core
lib/topologies/server.js
function(options) { options = options || {}; // Add event listener EventEmitter.call(this); // Server instance id this.id = id++; // Internal state this.s = { // Options options: options, // Logger logger: Logger('Server', options), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Pool pool: null, // Disconnect handler disconnectHandler: options.disconnectHandler, // Monitor thread (keeps the connection alive) monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, // Is the server in a topology inTopology: !!options.parent, // Monitoring timeout monitoringInterval: typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, // Topology id topologyId: -1, compression: { compressors: createCompressionInfo(options) }, // Optional parent topology parent: options.parent }; // If this is a single deployment we need to track the clusterTime here if (!this.s.parent) { this.s.clusterTime = null; } // Curent ismaster this.ismaster = null; // Current ping time this.lastIsMasterMS = -1; // The monitoringProcessId this.monitoringProcessId = null; // Initial connection this.initialConnect = true; // Default type this._type = 'server'; // Set the client info this.clientInfo = createClientInfo(options); // Max Stalleness values // last time we updated the ismaster state this.lastUpdateTime = 0; // Last write time this.lastWriteDate = 0; // Stalleness this.staleness = 0; }
javascript
function(options) { options = options || {}; // Add event listener EventEmitter.call(this); // Server instance id this.id = id++; // Internal state this.s = { // Options options: options, // Logger logger: Logger('Server', options), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Pool pool: null, // Disconnect handler disconnectHandler: options.disconnectHandler, // Monitor thread (keeps the connection alive) monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, // Is the server in a topology inTopology: !!options.parent, // Monitoring timeout monitoringInterval: typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, // Topology id topologyId: -1, compression: { compressors: createCompressionInfo(options) }, // Optional parent topology parent: options.parent }; // If this is a single deployment we need to track the clusterTime here if (!this.s.parent) { this.s.clusterTime = null; } // Curent ismaster this.ismaster = null; // Current ping time this.lastIsMasterMS = -1; // The monitoringProcessId this.monitoringProcessId = null; // Initial connection this.initialConnect = true; // Default type this._type = 'server'; // Set the client info this.clientInfo = createClientInfo(options); // Max Stalleness values // last time we updated the ismaster state this.lastUpdateTime = 0; // Last write time this.lastWriteDate = 0; // Stalleness this.staleness = 0; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// Add event listener", "EventEmitter", ".", "call", "(", "this", ")", ";", "// Server instance id", "this", ".", "id", "=", "id", "++", ";", "// Internal state", "this", ...
Creates a new Server instance @class @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection @param {number} [options.reconnectTries=30] Server attempt to reconnect #times @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors @param {string} options.host The server host @param {number} options.port The server port @param {number} [options.size=5] Server connection pool size @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled @param {boolean} [options.noDelay=true] TCP Connection no delay @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting @param {number} [options.socketTimeout=360000] TCP Socket timeout setting @param {boolean} [options.ssl=false] Use SSL for connection @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. @param {Buffer} [options.ca] SSL Certificate store binary buffer @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer @param {Buffer} [options.cert] SSL Certificate binary buffer @param {Buffer} [options.key] SSL Key file binary buffer @param {string} [options.passphrase] SSL Certificate pass phrase @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates @param {string} [options.servername=null] String containing the server name requested via TLS SNI. @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology @return {Server} A cursor instance @fires Server#connect @fires Server#close @fires Server#error @fires Server#timeout @fires Server#parseError @fires Server#reconnect @fires Server#reconnectFailed @fires Server#serverHeartbeatStarted @fires Server#serverHeartbeatSucceeded @fires Server#serverHeartbeatFailed @fires Server#topologyOpening @fires Server#topologyClosed @fires Server#topologyDescriptionChanged @property {string} type the topology type. @property {string} parserType the parser type used (c++ or js).
[ "Creates", "a", "new", "Server", "instance" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/topologies/server.js#L107-L186
13,885
mongodb-js/mongodb-core
lib/wireprotocol/shared.js
function(message) { return { length: message.readInt32LE(0), requestId: message.readInt32LE(4), responseTo: message.readInt32LE(8), opCode: message.readInt32LE(12) }; }
javascript
function(message) { return { length: message.readInt32LE(0), requestId: message.readInt32LE(4), responseTo: message.readInt32LE(8), opCode: message.readInt32LE(12) }; }
[ "function", "(", "message", ")", "{", "return", "{", "length", ":", "message", ".", "readInt32LE", "(", "0", ")", ",", "requestId", ":", "message", ".", "readInt32LE", "(", "4", ")", ",", "responseTo", ":", "message", ".", "readInt32LE", "(", "8", ")",...
Parses the header of a wire protocol message
[ "Parses", "the", "header", "of", "a", "wire", "protocol", "message" ]
bcb87caa89f5841272955fb4b320f75d632856f7
https://github.com/mongodb-js/mongodb-core/blob/bcb87caa89f5841272955fb4b320f75d632856f7/lib/wireprotocol/shared.js#L45-L52
13,886
DoctorMcKay/node-steam-user
components/connection_protocols/tcp.js
TCPConnection
function TCPConnection(user) { this.user = user; // Pick a CM randomly if (!user._cmList || !user._cmList.tcp_servers) { throw new Error("Nothing to connect to: " + (user._cmList ? "no TCP server list" : "no CM list")); } let tcpCm = user._cmList.tcp_servers[Math.floor(Math.random() * user._cmList.tcp_servers.length)]; user.emit('debug', 'Connecting to TCP CM: ' + tcpCm); let cmParts = tcpCm.split(':'); let cmHost = cmParts[0]; let cmPort = parseInt(cmParts[1], 10); if (user.options.httpProxy) { let url = URL.parse(user.options.httpProxy); url.method = 'CONNECT'; url.path = tcpCm; url.localAddress = user.options.localAddress; url.localPort = user.options.localPort; if (url.auth) { url.headers = {"Proxy-Authorization": "Basic " + (new Buffer(url.auth, 'utf8')).toString('base64')}; delete url.auth; } let connectionEstablished = false; let req = HTTP.request(url); req.end(); req.setTimeout(user.options.proxyTimeout || 5000); req.on('connect', (res, socket) => { if (connectionEstablished) { // somehow we're already connected, or we aborted socket.end(); return; } connectionEstablished = true; req.setTimeout(0); // disable timeout if (res.statusCode != 200) { this.user.emit('error', new Error('HTTP CONNECT ' + res.statusCode + ' ' + res.statusMessage)); return; } this.stream = socket; this._setupStream(); }); req.on('timeout', () => { connectionEstablished = true; this.user.emit('error', new Error('Proxy connection timed out')); }); req.on('error', (err) => { connectionEstablished = true; this.user.emit('error', err); }); } else { let socket = new Socket(); this.stream = socket; this._setupStream(); socket.connect({ "port": cmPort, "host": cmHost, "localAddress": user.options.localAddress, "localPort": user.options.localPort }); this.stream.setTimeout(this.user._connectTimeout); } }
javascript
function TCPConnection(user) { this.user = user; // Pick a CM randomly if (!user._cmList || !user._cmList.tcp_servers) { throw new Error("Nothing to connect to: " + (user._cmList ? "no TCP server list" : "no CM list")); } let tcpCm = user._cmList.tcp_servers[Math.floor(Math.random() * user._cmList.tcp_servers.length)]; user.emit('debug', 'Connecting to TCP CM: ' + tcpCm); let cmParts = tcpCm.split(':'); let cmHost = cmParts[0]; let cmPort = parseInt(cmParts[1], 10); if (user.options.httpProxy) { let url = URL.parse(user.options.httpProxy); url.method = 'CONNECT'; url.path = tcpCm; url.localAddress = user.options.localAddress; url.localPort = user.options.localPort; if (url.auth) { url.headers = {"Proxy-Authorization": "Basic " + (new Buffer(url.auth, 'utf8')).toString('base64')}; delete url.auth; } let connectionEstablished = false; let req = HTTP.request(url); req.end(); req.setTimeout(user.options.proxyTimeout || 5000); req.on('connect', (res, socket) => { if (connectionEstablished) { // somehow we're already connected, or we aborted socket.end(); return; } connectionEstablished = true; req.setTimeout(0); // disable timeout if (res.statusCode != 200) { this.user.emit('error', new Error('HTTP CONNECT ' + res.statusCode + ' ' + res.statusMessage)); return; } this.stream = socket; this._setupStream(); }); req.on('timeout', () => { connectionEstablished = true; this.user.emit('error', new Error('Proxy connection timed out')); }); req.on('error', (err) => { connectionEstablished = true; this.user.emit('error', err); }); } else { let socket = new Socket(); this.stream = socket; this._setupStream(); socket.connect({ "port": cmPort, "host": cmHost, "localAddress": user.options.localAddress, "localPort": user.options.localPort }); this.stream.setTimeout(this.user._connectTimeout); } }
[ "function", "TCPConnection", "(", "user", ")", "{", "this", ".", "user", "=", "user", ";", "// Pick a CM randomly", "if", "(", "!", "user", ".", "_cmList", "||", "!", "user", ".", "_cmList", ".", "tcp_servers", ")", "{", "throw", "new", "Error", "(", "...
Create a new TCP connection, and connect @param {SteamUser} user @constructor
[ "Create", "a", "new", "TCP", "connection", "and", "connect" ]
a58d91287cde03873a26cd12fee64fbd6ff3edd7
https://github.com/DoctorMcKay/node-steam-user/blob/a58d91287cde03873a26cd12fee64fbd6ff3edd7/components/connection_protocols/tcp.js#L19-L90
13,887
DoctorMcKay/node-steam-user
components/chat.js
toChatID
function toChatID(steamID) { steamID = Helpers.steamID(steamID); if (steamID.type == SteamID.Type.CLAN) { steamID.type = SteamID.Type.CHAT; steamID.instance |= SteamID.ChatInstanceFlags.Clan; } return steamID; }
javascript
function toChatID(steamID) { steamID = Helpers.steamID(steamID); if (steamID.type == SteamID.Type.CLAN) { steamID.type = SteamID.Type.CHAT; steamID.instance |= SteamID.ChatInstanceFlags.Clan; } return steamID; }
[ "function", "toChatID", "(", "steamID", ")", "{", "steamID", "=", "Helpers", ".", "steamID", "(", "steamID", ")", ";", "if", "(", "steamID", ".", "type", "==", "SteamID", ".", "Type", ".", "CLAN", ")", "{", "steamID", ".", "type", "=", "SteamID", "."...
Private functions If steamID is a clan ID, converts to the appropriate chat ID. Otherwise, returns it untouched. @param {SteamID} steamID @returns SteamID
[ "Private", "functions", "If", "steamID", "is", "a", "clan", "ID", "converts", "to", "the", "appropriate", "chat", "ID", ".", "Otherwise", "returns", "it", "untouched", "." ]
a58d91287cde03873a26cd12fee64fbd6ff3edd7
https://github.com/DoctorMcKay/node-steam-user/blob/a58d91287cde03873a26cd12fee64fbd6ff3edd7/components/chat.js#L512-L521
13,888
DoctorMcKay/node-steam-user
components/chat.js
fromChatID
function fromChatID(steamID) { steamID = Helpers.steamID(steamID); if (steamID.isGroupChat()) { steamID.type = SteamID.Type.CLAN; steamID.instance &= ~SteamID.ChatInstanceFlags.Clan; } return steamID; }
javascript
function fromChatID(steamID) { steamID = Helpers.steamID(steamID); if (steamID.isGroupChat()) { steamID.type = SteamID.Type.CLAN; steamID.instance &= ~SteamID.ChatInstanceFlags.Clan; } return steamID; }
[ "function", "fromChatID", "(", "steamID", ")", "{", "steamID", "=", "Helpers", ".", "steamID", "(", "steamID", ")", ";", "if", "(", "steamID", ".", "isGroupChat", "(", ")", ")", "{", "steamID", ".", "type", "=", "SteamID", ".", "Type", ".", "CLAN", "...
If steamID is a clan chat ID, converts to the appropriate clan ID. Otherwise, returns it untouched. @param {SteamID} steamID @returns SteamID
[ "If", "steamID", "is", "a", "clan", "chat", "ID", "converts", "to", "the", "appropriate", "clan", "ID", ".", "Otherwise", "returns", "it", "untouched", "." ]
a58d91287cde03873a26cd12fee64fbd6ff3edd7
https://github.com/DoctorMcKay/node-steam-user/blob/a58d91287cde03873a26cd12fee64fbd6ff3edd7/components/chat.js#L528-L537
13,889
DoctorMcKay/node-steam-user
components/chat.js
decomposeChatFlags
function decomposeChatFlags(chat, chatFlags) { chat.private = !!(chatFlags & SteamUser.EChatFlags.Locked); chat.invisibleToFriends = !!(chatFlags & SteamUser.EChatFlags.InvisibleToFriends); chat.officersOnlyChat = !!(chatFlags & SteamUser.EChatFlags.Moderated); chat.unjoinable = !!(chatFlags & SteamUser.EChatFlags.Unjoinable); }
javascript
function decomposeChatFlags(chat, chatFlags) { chat.private = !!(chatFlags & SteamUser.EChatFlags.Locked); chat.invisibleToFriends = !!(chatFlags & SteamUser.EChatFlags.InvisibleToFriends); chat.officersOnlyChat = !!(chatFlags & SteamUser.EChatFlags.Moderated); chat.unjoinable = !!(chatFlags & SteamUser.EChatFlags.Unjoinable); }
[ "function", "decomposeChatFlags", "(", "chat", ",", "chatFlags", ")", "{", "chat", ".", "private", "=", "!", "!", "(", "chatFlags", "&", "SteamUser", ".", "EChatFlags", ".", "Locked", ")", ";", "chat", ".", "invisibleToFriends", "=", "!", "!", "(", "chat...
Converts chat flags into properties on a chat room object @param {Object} chat @param {number} chatFlags
[ "Converts", "chat", "flags", "into", "properties", "on", "a", "chat", "room", "object" ]
a58d91287cde03873a26cd12fee64fbd6ff3edd7
https://github.com/DoctorMcKay/node-steam-user/blob/a58d91287cde03873a26cd12fee64fbd6ff3edd7/components/chat.js#L544-L549
13,890
DoctorMcKay/node-steam-user
components/chatroom.js
processChatRoomSummaryPair
function processChatRoomSummaryPair(summaryPair, preProcessed) { if (!preProcessed) { summaryPair = preProcessObject(summaryPair); } summaryPair.group_state = processUserChatGroupState(summaryPair.user_chat_group_state, true); summaryPair.group_summary = processChatGroupSummary(summaryPair.group_summary, true); delete summaryPair.user_chat_group_state; return summaryPair; }
javascript
function processChatRoomSummaryPair(summaryPair, preProcessed) { if (!preProcessed) { summaryPair = preProcessObject(summaryPair); } summaryPair.group_state = processUserChatGroupState(summaryPair.user_chat_group_state, true); summaryPair.group_summary = processChatGroupSummary(summaryPair.group_summary, true); delete summaryPair.user_chat_group_state; return summaryPair; }
[ "function", "processChatRoomSummaryPair", "(", "summaryPair", ",", "preProcessed", ")", "{", "if", "(", "!", "preProcessed", ")", "{", "summaryPair", "=", "preProcessObject", "(", "summaryPair", ")", ";", "}", "summaryPair", ".", "group_state", "=", "processUserCh...
Process a chat room summary pair. @param {object} summaryPair @param {boolean} [preProcessed=false] @returns {object}
[ "Process", "a", "chat", "room", "summary", "pair", "." ]
a58d91287cde03873a26cd12fee64fbd6ff3edd7
https://github.com/DoctorMcKay/node-steam-user/blob/a58d91287cde03873a26cd12fee64fbd6ff3edd7/components/chatroom.js#L678-L687
13,891
DoctorMcKay/node-steam-user
components/chatroom.js
processChatGroupSummary
function processChatGroupSummary(groupSummary, preProcessed) { if (!preProcessed) { groupSummary = preProcessObject(groupSummary); } if (groupSummary.top_members) { groupSummary.top_members = groupSummary.top_members.map(accountid => SteamID.fromIndividualAccountID(accountid)); } return groupSummary; }
javascript
function processChatGroupSummary(groupSummary, preProcessed) { if (!preProcessed) { groupSummary = preProcessObject(groupSummary); } if (groupSummary.top_members) { groupSummary.top_members = groupSummary.top_members.map(accountid => SteamID.fromIndividualAccountID(accountid)); } return groupSummary; }
[ "function", "processChatGroupSummary", "(", "groupSummary", ",", "preProcessed", ")", "{", "if", "(", "!", "preProcessed", ")", "{", "groupSummary", "=", "preProcessObject", "(", "groupSummary", ")", ";", "}", "if", "(", "groupSummary", ".", "top_members", ")", ...
Process a chat group summary. @param {object} groupSummary @param {boolean} [preProcessed=false] @returns {object}
[ "Process", "a", "chat", "group", "summary", "." ]
a58d91287cde03873a26cd12fee64fbd6ff3edd7
https://github.com/DoctorMcKay/node-steam-user/blob/a58d91287cde03873a26cd12fee64fbd6ff3edd7/components/chatroom.js#L695-L705
13,892
DoctorMcKay/node-steam-user
components/chatroom.js
preProcessObject
function preProcessObject(obj) { for (let key in obj) { if (!obj.hasOwnProperty(key)) { continue; } let val = obj[key]; if (key.match(/^steamid_/) && typeof val === 'string' && val != '0') { obj[key] = new SteamID(val.toString()); } else if (key == 'timestamp' || key.match(/^time_/) || key.match(/_timestamp$/)) { if (val === 0) { obj[key] = null; } else if (val !== null) { obj[key] = new Date(val * 1000); } } else if (key == 'clanid' && typeof val === 'number') { let id = new SteamID(); id.universe = SteamID.Universe.PUBLIC; id.type = SteamID.Type.CLAN; id.instance = SteamID.Instance.ALL; id.accountid = val; obj[key] = id; } else if ((key == 'accountid' || key.match(/^accountid_/) || key.match(/_accountid$/)) && (typeof val === 'number' || val === null)) { let newKey = key == 'accountid' ? 'steamid' : key.replace('accountid_', 'steamid_').replace('_accountid', '_steamid'); obj[newKey] = val === 0 || val === null ? null : SteamID.fromIndividualAccountID(val); delete obj[key]; } else if (key.includes('avatar_sha')) { let url = null; if (obj[key] && obj[key].length) { url = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/chaticons/"; url += obj[key][0].toString(16) + '/'; url += obj[key][1].toString(16) + '/'; url += obj[key][2].toString(16) + '/'; url += obj[key].toString('hex') + '_256.jpg'; } obj[key.replace('avatar_sha', 'avatar_url')] = url; } else if (key.match(/^can_/) && obj[key] === null) { obj[key] = false; } else if (isDataObject(val)) { obj[key] = preProcessObject(val); } else if (Array.isArray(val) && val.every(isDataObject)) { obj[key] = val.map(v => preProcessObject(v)); } } return obj; }
javascript
function preProcessObject(obj) { for (let key in obj) { if (!obj.hasOwnProperty(key)) { continue; } let val = obj[key]; if (key.match(/^steamid_/) && typeof val === 'string' && val != '0') { obj[key] = new SteamID(val.toString()); } else if (key == 'timestamp' || key.match(/^time_/) || key.match(/_timestamp$/)) { if (val === 0) { obj[key] = null; } else if (val !== null) { obj[key] = new Date(val * 1000); } } else if (key == 'clanid' && typeof val === 'number') { let id = new SteamID(); id.universe = SteamID.Universe.PUBLIC; id.type = SteamID.Type.CLAN; id.instance = SteamID.Instance.ALL; id.accountid = val; obj[key] = id; } else if ((key == 'accountid' || key.match(/^accountid_/) || key.match(/_accountid$/)) && (typeof val === 'number' || val === null)) { let newKey = key == 'accountid' ? 'steamid' : key.replace('accountid_', 'steamid_').replace('_accountid', '_steamid'); obj[newKey] = val === 0 || val === null ? null : SteamID.fromIndividualAccountID(val); delete obj[key]; } else if (key.includes('avatar_sha')) { let url = null; if (obj[key] && obj[key].length) { url = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/chaticons/"; url += obj[key][0].toString(16) + '/'; url += obj[key][1].toString(16) + '/'; url += obj[key][2].toString(16) + '/'; url += obj[key].toString('hex') + '_256.jpg'; } obj[key.replace('avatar_sha', 'avatar_url')] = url; } else if (key.match(/^can_/) && obj[key] === null) { obj[key] = false; } else if (isDataObject(val)) { obj[key] = preProcessObject(val); } else if (Array.isArray(val) && val.every(isDataObject)) { obj[key] = val.map(v => preProcessObject(v)); } } return obj; }
[ "function", "preProcessObject", "(", "obj", ")", "{", "for", "(", "let", "key", "in", "obj", ")", "{", "if", "(", "!", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "continue", ";", "}", "let", "val", "=", "obj", "[", "key", "]", ";", ...
Pre-process a generic chat object. @param {object} obj @returns {object}
[ "Pre", "-", "process", "a", "generic", "chat", "object", "." ]
a58d91287cde03873a26cd12fee64fbd6ff3edd7
https://github.com/DoctorMcKay/node-steam-user/blob/a58d91287cde03873a26cd12fee64fbd6ff3edd7/components/chatroom.js#L763-L810
13,893
choojs/bankai
lib/graph-document.js
extractFonts
function extractFonts (state) { var list = String(state.list.buffer).split(',') var res = list.filter(function (font) { var extname = path.extname(font) return extname === '.woff' || extname === '.woff2' || extname === '.eot' || extname === '.ttf' }) return res }
javascript
function extractFonts (state) { var list = String(state.list.buffer).split(',') var res = list.filter(function (font) { var extname = path.extname(font) return extname === '.woff' || extname === '.woff2' || extname === '.eot' || extname === '.ttf' }) return res }
[ "function", "extractFonts", "(", "state", ")", "{", "var", "list", "=", "String", "(", "state", ".", "list", ".", "buffer", ")", ".", "split", "(", "','", ")", "var", "res", "=", "list", ".", "filter", "(", "function", "(", "font", ")", "{", "var",...
Specific to the document node's layout
[ "Specific", "to", "the", "document", "node", "s", "layout" ]
29cb370f3901316f66e9ee582d3a62305051b5be
https://github.com/choojs/bankai/blob/29cb370f3901316f66e9ee582d3a62305051b5be/lib/graph-document.js#L261-L274
13,894
choojs/bankai
lib/track-dir.js
init
function init (dirname, done) { dirname = path.join(basedir, dirname) fs.access(dirname, function (err) { if (err) return done() readdir(dirname, function (err, _list) { if (err) return done(err) list = list.concat(_list) done() }) }) }
javascript
function init (dirname, done) { dirname = path.join(basedir, dirname) fs.access(dirname, function (err) { if (err) return done() readdir(dirname, function (err, _list) { if (err) return done(err) list = list.concat(_list) done() }) }) }
[ "function", "init", "(", "dirname", ",", "done", ")", "{", "dirname", "=", "path", ".", "join", "(", "basedir", ",", "dirname", ")", "fs", ".", "access", "(", "dirname", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "done"...
Run only once at the start of the pass.
[ "Run", "only", "once", "at", "the", "start", "of", "the", "pass", "." ]
29cb370f3901316f66e9ee582d3a62305051b5be
https://github.com/choojs/bankai/blob/29cb370f3901316f66e9ee582d3a62305051b5be/lib/track-dir.js#L74-L84
13,895
kentcdodds/match-sorter
src/index.js
matchSorter
function matchSorter(items, value, options = {}) { // not performing any search/sort if value(search term) is empty if (!value) return items const {keys, threshold = rankings.MATCHES} = options const matchedItems = items.reduce(reduceItemsToRanked, []) return matchedItems.sort(sortRankedItems).map(({item}) => item) function reduceItemsToRanked(matches, item, index) { const {rank, keyIndex, keyThreshold = threshold} = getHighestRanking( item, keys, value, options, ) if (rank >= keyThreshold) { matches.push({item, rank, index, keyIndex}) } return matches } }
javascript
function matchSorter(items, value, options = {}) { // not performing any search/sort if value(search term) is empty if (!value) return items const {keys, threshold = rankings.MATCHES} = options const matchedItems = items.reduce(reduceItemsToRanked, []) return matchedItems.sort(sortRankedItems).map(({item}) => item) function reduceItemsToRanked(matches, item, index) { const {rank, keyIndex, keyThreshold = threshold} = getHighestRanking( item, keys, value, options, ) if (rank >= keyThreshold) { matches.push({item, rank, index, keyIndex}) } return matches } }
[ "function", "matchSorter", "(", "items", ",", "value", ",", "options", "=", "{", "}", ")", "{", "// not performing any search/sort if value(search term) is empty", "if", "(", "!", "value", ")", "return", "items", "const", "{", "keys", ",", "threshold", "=", "ran...
Takes an array of items and a value and returns a new array with the items that match the given value @param {Array} items - the items to sort @param {String} value - the value to use for ranking @param {Object} options - Some options to configure the sorter @return {Array} - the new sorted array
[ "Takes", "an", "array", "of", "items", "and", "a", "value", "and", "returns", "a", "new", "array", "with", "the", "items", "that", "match", "the", "given", "value" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L40-L60
13,896
kentcdodds/match-sorter
src/index.js
getHighestRanking
function getHighestRanking(item, keys, value, options) { if (!keys) { return { rank: getMatchRanking(item, value, options), keyIndex: -1, keyThreshold: options.threshold, } } const valuesToRank = getAllValuesToRank(item, keys) return valuesToRank.reduce( ({rank, keyIndex, keyThreshold}, {itemValue, attributes}, i) => { let newRank = getMatchRanking(itemValue, value, options) const {minRanking, maxRanking, threshold} = attributes if (newRank < minRanking && newRank >= rankings.MATCHES) { newRank = minRanking } else if (newRank > maxRanking) { newRank = maxRanking } if (newRank > rank) { rank = newRank keyIndex = i keyThreshold = threshold } return {rank, keyIndex, keyThreshold} }, {rank: rankings.NO_MATCH, keyIndex: -1, keyThreshold: options.threshold}, ) }
javascript
function getHighestRanking(item, keys, value, options) { if (!keys) { return { rank: getMatchRanking(item, value, options), keyIndex: -1, keyThreshold: options.threshold, } } const valuesToRank = getAllValuesToRank(item, keys) return valuesToRank.reduce( ({rank, keyIndex, keyThreshold}, {itemValue, attributes}, i) => { let newRank = getMatchRanking(itemValue, value, options) const {minRanking, maxRanking, threshold} = attributes if (newRank < minRanking && newRank >= rankings.MATCHES) { newRank = minRanking } else if (newRank > maxRanking) { newRank = maxRanking } if (newRank > rank) { rank = newRank keyIndex = i keyThreshold = threshold } return {rank, keyIndex, keyThreshold} }, {rank: rankings.NO_MATCH, keyIndex: -1, keyThreshold: options.threshold}, ) }
[ "function", "getHighestRanking", "(", "item", ",", "keys", ",", "value", ",", "options", ")", "{", "if", "(", "!", "keys", ")", "{", "return", "{", "rank", ":", "getMatchRanking", "(", "item", ",", "value", ",", "options", ")", ",", "keyIndex", ":", ...
Gets the highest ranking for value for the given item based on its values for the given keys @param {*} item - the item to rank @param {Array} keys - the keys to get values from the item for the ranking @param {String} value - the value to rank against @param {Object} options - options to control the ranking @return {{rank: Number, keyIndex: Number, keyThreshold: Number}} - the highest ranking
[ "Gets", "the", "highest", "ranking", "for", "value", "for", "the", "given", "item", "based", "on", "its", "values", "for", "the", "given", "keys" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L70-L97
13,897
kentcdodds/match-sorter
src/index.js
getMatchRanking
function getMatchRanking(testString, stringToRank, options) { /* eslint complexity:[2, 12] */ testString = prepareValueForComparison(testString, options) stringToRank = prepareValueForComparison(stringToRank, options) // too long if (stringToRank.length > testString.length) { return rankings.NO_MATCH } // case sensitive equals if (testString === stringToRank) { return rankings.CASE_SENSITIVE_EQUAL } const caseRank = getCaseRanking(testString) const isPartial = isPartialOfCase(testString, stringToRank, caseRank) const isCasedAcronym = isCaseAcronym(testString, stringToRank, caseRank) // Lower casing before further comparison testString = testString.toLowerCase() stringToRank = stringToRank.toLowerCase() // case insensitive equals if (testString === stringToRank) { return rankings.EQUAL + caseRank } // starts with if (testString.indexOf(stringToRank) === 0) { return rankings.STARTS_WITH + caseRank } // word starts with if (testString.indexOf(` ${stringToRank}`) !== -1) { return rankings.WORD_STARTS_WITH + caseRank } // is a part inside a cased string if (isPartial) { return rankings.STRING_CASE + caseRank } // is acronym for a cased string if (caseRank > 0 && isCasedAcronym) { return rankings.STRING_CASE_ACRONYM + caseRank } // contains if (testString.indexOf(stringToRank) !== -1) { return rankings.CONTAINS + caseRank } else if (stringToRank.length === 1) { // If the only character in the given stringToRank // isn't even contained in the testString, then // it's definitely not a match. return rankings.NO_MATCH } // acronym if (getAcronym(testString).indexOf(stringToRank) !== -1) { return rankings.ACRONYM + caseRank } // will return a number between rankings.MATCHES and // rankings.MATCHES + 1 depending on how close of a match it is. return getClosenessRanking(testString, stringToRank) }
javascript
function getMatchRanking(testString, stringToRank, options) { /* eslint complexity:[2, 12] */ testString = prepareValueForComparison(testString, options) stringToRank = prepareValueForComparison(stringToRank, options) // too long if (stringToRank.length > testString.length) { return rankings.NO_MATCH } // case sensitive equals if (testString === stringToRank) { return rankings.CASE_SENSITIVE_EQUAL } const caseRank = getCaseRanking(testString) const isPartial = isPartialOfCase(testString, stringToRank, caseRank) const isCasedAcronym = isCaseAcronym(testString, stringToRank, caseRank) // Lower casing before further comparison testString = testString.toLowerCase() stringToRank = stringToRank.toLowerCase() // case insensitive equals if (testString === stringToRank) { return rankings.EQUAL + caseRank } // starts with if (testString.indexOf(stringToRank) === 0) { return rankings.STARTS_WITH + caseRank } // word starts with if (testString.indexOf(` ${stringToRank}`) !== -1) { return rankings.WORD_STARTS_WITH + caseRank } // is a part inside a cased string if (isPartial) { return rankings.STRING_CASE + caseRank } // is acronym for a cased string if (caseRank > 0 && isCasedAcronym) { return rankings.STRING_CASE_ACRONYM + caseRank } // contains if (testString.indexOf(stringToRank) !== -1) { return rankings.CONTAINS + caseRank } else if (stringToRank.length === 1) { // If the only character in the given stringToRank // isn't even contained in the testString, then // it's definitely not a match. return rankings.NO_MATCH } // acronym if (getAcronym(testString).indexOf(stringToRank) !== -1) { return rankings.ACRONYM + caseRank } // will return a number between rankings.MATCHES and // rankings.MATCHES + 1 depending on how close of a match it is. return getClosenessRanking(testString, stringToRank) }
[ "function", "getMatchRanking", "(", "testString", ",", "stringToRank", ",", "options", ")", "{", "/* eslint complexity:[2, 12] */", "testString", "=", "prepareValueForComparison", "(", "testString", ",", "options", ")", "stringToRank", "=", "prepareValueForComparison", "(...
Gives a rankings score based on how well the two strings match. @param {String} testString - the string to test against @param {String} stringToRank - the string to rank @param {Object} options - options for the match (like keepDiacritics for comparison) @returns {Number} the ranking for how well stringToRank matches testString
[ "Gives", "a", "rankings", "score", "based", "on", "how", "well", "the", "two", "strings", "match", "." ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L106-L172
13,898
kentcdodds/match-sorter
src/index.js
getCaseRanking
function getCaseRanking(testString) { const containsUpperCase = testString.toLowerCase() !== testString const containsDash = testString.indexOf('-') >= 0 const containsUnderscore = testString.indexOf('_') >= 0 if (!containsUpperCase && !containsUnderscore && containsDash) { return caseRankings.KEBAB } if (!containsUpperCase && containsUnderscore && !containsDash) { return caseRankings.SNAKE } if (containsUpperCase && !containsDash && !containsUnderscore) { const startsWithUpperCase = testString[0].toUpperCase() === testString[0] if (startsWithUpperCase) { return caseRankings.PASCAL } return caseRankings.CAMEL } return caseRankings.NO_CASE }
javascript
function getCaseRanking(testString) { const containsUpperCase = testString.toLowerCase() !== testString const containsDash = testString.indexOf('-') >= 0 const containsUnderscore = testString.indexOf('_') >= 0 if (!containsUpperCase && !containsUnderscore && containsDash) { return caseRankings.KEBAB } if (!containsUpperCase && containsUnderscore && !containsDash) { return caseRankings.SNAKE } if (containsUpperCase && !containsDash && !containsUnderscore) { const startsWithUpperCase = testString[0].toUpperCase() === testString[0] if (startsWithUpperCase) { return caseRankings.PASCAL } return caseRankings.CAMEL } return caseRankings.NO_CASE }
[ "function", "getCaseRanking", "(", "testString", ")", "{", "const", "containsUpperCase", "=", "testString", ".", "toLowerCase", "(", ")", "!==", "testString", "const", "containsDash", "=", "testString", ".", "indexOf", "(", "'-'", ")", ">=", "0", "const", "con...
Returns a score base on the case of the testString @param {String} testString - the string to test against @returns {Number} the number of the ranking, based on the case between 0 and 1 for how the testString matches the case
[ "Returns", "a", "score", "base", "on", "the", "case", "of", "the", "testString" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L198-L221
13,899
kentcdodds/match-sorter
src/index.js
isCaseAcronym
function isCaseAcronym(testString, stringToRank, caseRank) { let splitValue = null switch (caseRank) { case caseRankings.SNAKE: splitValue = '_' break case caseRankings.KEBAB: splitValue = '-' break case caseRankings.PASCAL: case caseRankings.CAMEL: splitValue = /(?=[A-Z])/ break default: splitValue = null } const splitTestString = testString.split(splitValue) return stringToRank .toLowerCase() .split('') .reduce((correct, char, charIndex) => { const splitItem = splitTestString[charIndex] return correct && splitItem && splitItem[0].toLowerCase() === char }, true) }
javascript
function isCaseAcronym(testString, stringToRank, caseRank) { let splitValue = null switch (caseRank) { case caseRankings.SNAKE: splitValue = '_' break case caseRankings.KEBAB: splitValue = '-' break case caseRankings.PASCAL: case caseRankings.CAMEL: splitValue = /(?=[A-Z])/ break default: splitValue = null } const splitTestString = testString.split(splitValue) return stringToRank .toLowerCase() .split('') .reduce((correct, char, charIndex) => { const splitItem = splitTestString[charIndex] return correct && splitItem && splitItem[0].toLowerCase() === char }, true) }
[ "function", "isCaseAcronym", "(", "testString", ",", "stringToRank", ",", "caseRank", ")", "{", "let", "splitValue", "=", "null", "switch", "(", "caseRank", ")", "{", "case", "caseRankings", ".", "SNAKE", ":", "splitValue", "=", "'_'", "break", "case", "case...
Check if stringToRank is an acronym for a partial case @example // returns true isCaseAcronym('super_duper_file', 'sdf', caseRankings.SNAKE) @param {String} testString - the string to test against @param {String} stringToRank - the acronym to test @param {Number} caseRank - the ranking of the case @returns {Boolean} whether the stringToRank is an acronym for the testString
[ "Check", "if", "stringToRank", "is", "an", "acronym", "for", "a", "partial", "case" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L265-L290