_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q4300
getTickOfSingleValue
train
function getTickOfSingleValue(value, tickCount, allowDecimals) { let step = 1; // calculate the middle value of ticks let middle = new Decimal(value); if (!middle.isint() && allowDecimals) { const absVal = Math.abs(value); if (absVal < 1) { // The step should be a float number when the difference is smaller than 1 step = new Decimal(10).pow(Arithmetic.getDigitCount(value) - 1); middle =
javascript
{ "resource": "" }
q4301
calculateStep
train
function calculateStep(min, max, tickCount, allowDecimals, correctionFactor = 0) { // dirty hack (for recharts' test) if (!Number.isFinite((max - min) / (tickCount - 1))) { return { step: new Decimal(0), tickMin: new Decimal(0), tickMax: new Decimal(0), }; } // The step which is easy to understand between two ticks const step = getFormatStep( new Decimal(max).sub(min).div(tickCount - 1), allowDecimals, correctionFactor, ); // A medial value of ticks let middle; // When 0 is inside the interval, 0 should be a tick if (min <= 0 && max >= 0) { middle = new Decimal(0); } else { // calculate the middle value middle = new Decimal(min).add(max).div(2); // minus modulo value middle = middle.sub(new Decimal(middle).mod(step)); } let belowCount = Math.ceil(middle.sub(min).div(step).toNumber()); let upCount = Math.ceil(new Decimal(max).sub(middle).div(step) .toNumber()); const scaleCount = belowCount + upCount + 1; if (scaleCount > tickCount) {
javascript
{ "resource": "" }
q4302
getNiceTickValuesFn
train
function getNiceTickValuesFn([min, max], tickCount = 6, allowDecimals = true) { // More than two ticks should be return const count = Math.max(tickCount, 2); const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { const values = cormax === Infinity ? [cormin, ...range(0, tickCount - 1).map(() => Infinity)] : [...range(0, tickCount - 1).map(() => -Infinity), cormax]; return min > max ? reverse(values) : values; }
javascript
{ "resource": "" }
q4303
getTickValuesFn
train
function getTickValuesFn([min, max], tickCount = 6, allowDecimals = true) { // More than two ticks should be return const count = Math.max(tickCount, 2); const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { return [min, max]; } if (cormin === cormax) { return getTickOfSingleValue(cormin, tickCount, allowDecimals); } const step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0); const fn =
javascript
{ "resource": "" }
q4304
getTickValuesFixedDomainFn
train
function getTickValuesFixedDomainFn([min, max], tickCount, allowDecimals = true) { // More than two ticks should be return const [cormin, cormax] = getValidInterval([min, max]); if (cormin === -Infinity || cormax === Infinity) { return [min, max]; } if (cormin ===
javascript
{ "resource": "" }
q4305
List
train
function List(props) { var tag = props.type.toLowerCase() === 'bullet' ? 'ul' : 'ol'; var attrs = getCoreProps(props);
javascript
{ "resource": "" }
q4306
getNodeProps
train
function getNodeProps(node, key, opts, renderer) { var props = { key: key }, undef; // `sourcePos` is true if the user wants source information (line/column info from markdown source) if (opts.sourcePos && node.sourcepos) { props['data-sourcepos'] = flattenPosition(node.sourcepos); } var type = normalizeTypeName(node.type); switch (type) { case 'html_inline': case 'html_block': props.isBlock = type === 'html_block'; props.escapeHtml = opts.escapeHtml; props.skipHtml = opts.skipHtml; break; case 'code_block': var codeInfo = node.info ? node.info.split(/ +/) : []; if (codeInfo.length > 0 && codeInfo[0].length > 0) { props.language = codeInfo[0]; props.codeinfo = codeInfo; } break; case 'code': props.children = node.literal; props.inline = true; break; case 'heading': props.level = node.level; break; case 'softbreak': props.softBreak = opts.softBreak; break; case 'link': props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination; props.title
javascript
{ "resource": "" }
q4307
BRDA
train
function BRDA (lineNumber, blockNumber, branchNumber, hits) { this.lineNumber
javascript
{ "resource": "" }
q4308
findDA
train
function findDA (source, lineNumber) { for (var i = 0; i < source.length; i++)
javascript
{ "resource": "" }
q4309
findBRDA
train
function findBRDA (source, blockNumber, branchNumber, lineNumber) { for (var i = 0; i < source.length; i++) { var brda = source[i] if (brda.blockNumber === blockNumber && brda.branchNumber
javascript
{ "resource": "" }
q4310
findCoverageFile
train
function findCoverageFile (source, filename) { for (var i = 0; i < source.length; i++)
javascript
{ "resource": "" }
q4311
parseSF
train
function parseSF (lcov, prefixSplit) { // If the filepath contains a ':', we want to preserve it. prefixSplit.shift() var currentFileName = prefixSplit.join(':')
javascript
{ "resource": "" }
q4312
parseDA
train
function parseDA (currentCoverageFile, prefixSplit) { var numberSplit = splitNumbers(prefixSplit) var lineNumber = parseInt(numberSplit[0], 10) var hits = parseInt(numberSplit[1], 10) var existingDA =
javascript
{ "resource": "" }
q4313
parseBRDA
train
function parseBRDA (currentCoverageFile, prefixSplit) { var numberSplit = splitNumbers(prefixSplit) var lineNumber = parseInt(numberSplit[0], 10) var blockNumber = parseInt(numberSplit[1], 10) var branchNumber = parseInt(numberSplit[2], 10) var existingBRDA = findBRDA(currentCoverageFile.BRDARecords, blockNumber, branchNumber, lineNumber) // Special case, hits might be a '-'. This means that the code block // where the branch was contained was never executed at all (as opposed //
javascript
{ "resource": "" }
q4314
processFile
train
function processFile (data, lcov) { var lines = data.split(/\r?\n/) var currentCoverageFile = null for (var i = 0, l = lines.length; i < l; i++) { var line = lines[i] if (line === 'end_of_record' || line === '') { currentCoverageFile = null continue } var prefixSplit = line.split(':')
javascript
{ "resource": "" }
q4315
JUnitXmlReporter
train
function JUnitXmlReporter(savePath, consolidate, useDotNotation) { this.savePath = savePath || ''; this.consolidate = typeof consolidate === 'undefined' ? true : consolidate;
javascript
{ "resource": "" }
q4316
train
function(version) { var current = [version.major, version.minor, version.patch].join('.'); var required = '>= 1.6.0'; if (!semver.satisfies(current, required)) { exports.halt(); grunt.log.writeln(); grunt.log.errorlns( 'In order for this task to work properly, PhantomJS version ' +
javascript
{ "resource": "" }
q4317
train
function() { if(!_self.waitingForResponse && _self.queue.length) { _self.waitingForResponse = true; var cmd = _self.queue.shift(); if(_self.conn) { _self.conn.removeAllListeners('data'); _self.conn.addListener('data', function(data) { Debug.log('response:');
javascript
{ "resource": "" }
q4318
SignerProvider
train
function SignerProvider(path, options) { if (!(this instanceof SignerProvider)) { throw new Error('[ethjs-provider-signer] the SignerProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new SignerProvider(...));`).'); } if (typeof options !== 'object') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'privateKey' property specified, you provided type ${typeof options}.`); } if (typeof options.signTransaction !== 'function') { throw new Error(`[ethjs-provider-signer] the SignerProvider requires an options object be provided with the 'signTransaction' property specified, you provided type ${typeof options.privateKey} (e.g. 'const eth =
javascript
{ "resource": "" }
q4319
generateArgs
train
function generateArgs(test, title, fields, index){ var formatting = fields.concat(), args = (formatting.unshift(title), formatting); for (var i = 1; i <= args.length - 1; i++) { if (args[i] === 'x') { args[i] = index;
javascript
{ "resource": "" }
q4320
wrap
train
function wrap(body, extKeys) { const wrapper = [ '(function (exports, require, module, __filename, __dirname', ') { ', '\n});' ]; extKeys = extKeys ? `,
javascript
{ "resource": "" }
q4321
_getCalleeFilename
train
function _getCalleeFilename(calls) { calls = (calls|0) + 3; // 3 is a number of inner calls
javascript
{ "resource": "" }
q4322
train
function(subset, key) { return [ key.nRow(), key.nCol(),
javascript
{ "resource": "" }
q4323
train
function(joinDf, indicatorValues) { var boolInd =
javascript
{ "resource": "" }
q4324
dfFromMatrixHelper
train
function dfFromMatrixHelper(matrix, startRow, colNames) { var nCol = colNames.size(); var nRow = matrix.length - startRow; var columns = allocArray(nCol); var j; for (j = 0; j < nCol; j++) { columns[j] = allocArray(nRow); } for (var i = 0; i < nRow; i++) { var rowArray = matrix[i + startRow]; if (rowArray.length !== nCol) {
javascript
{ "resource": "" }
q4325
rightAlign
train
function rightAlign(strVec) { var maxWidth = strVec.nChar().max(); var padding = jd.rep(' ', maxWidth).strJoin('');
javascript
{ "resource": "" }
q4326
makeRowIds
train
function makeRowIds(numRows, maxLines) { var printVec = jd.seq(numRows)._toTruncatedPrintVector(maxLines); return printVec.map(function(str) {
javascript
{ "resource": "" }
q4327
toPrintString
train
function toPrintString(value) { if (isUndefined(value)) { return 'undefined'; } else if (value === null) { return 'null'; } else if (Number.isNaN(value)) { return 'NaN'; } else { var str = coerceToStr(value); var lines = str.split('\n', 2); if (lines.length > 1) {
javascript
{ "resource": "" }
q4328
validatePrintMax
train
function validatePrintMax(candidate, lowerBound, label) { if (typeof candidate !== 'number' || Number.isNaN(candidate)) { throw new Error('"' + label + '" must be a number');
javascript
{ "resource": "" }
q4329
fractionDigits
train
function fractionDigits(number) { var splitArr = number.toString().split('.');
javascript
{ "resource": "" }
q4330
packVector
train
function packVector(vector, includeMetadata) { includeMetadata = isUndefined(includeMetadata) ? true : includeMetadata; var dtype = vector.dtype; if (vector.dtype === 'date') { vector = vector.toDtype('number'); } var values = (vector.dtype !== 'number') ? vector.values.slice() : vector.values.map(function(x) { return Number.isNaN(x) ? null : x;
javascript
{ "resource": "" }
q4331
numClose
train
function numClose(x, y) { return (Number.isNaN(x) && Number.isNaN(y))
javascript
{ "resource": "" }
q4332
appendJoinRow
train
function appendJoinRow(arrayCols, keyDf, leftNonKeyDf, rightNonKeyDf, leftInd, rightInd, indicatorValue, rightIndForKey) { var keyInd = rightIndForKey ? rightInd : leftInd; var i, nCol; var colInd = 0; nCol = keyDf.nCol(); for (i = 0; i < nCol; i++) { arrayCols[colInd].push(keyDf._cols[i].values[keyInd]); colInd++; } nCol = leftNonKeyDf.nCol(); for (i
javascript
{ "resource": "" }
q4333
keyIndexing
train
function keyIndexing(selector, maxLen, index) { var opts = resolverOpts(RESOLVE_MODE.KEY, maxLen,
javascript
{ "resource": "" }
q4334
attemptBoolIndexing
train
function attemptBoolIndexing(selector, maxLen) { if (selector.type === exclusionProto.type) { var intIdxVector = attemptBoolIndexing(selector._selector, maxLen); return isUndefined(intIdxVector) ? undefined : excludeIntIndices(intIdxVector, maxLen);
javascript
{ "resource": "" }
q4335
excludeIntIndices
train
function excludeIntIndices(intIdxVector, maxLen) { return
javascript
{ "resource": "" }
q4336
resolveSelector
train
function resolveSelector(selector, opts) { var resultArr = []; resolveSelectorHelper(selector, opts,
javascript
{ "resource": "" }
q4337
resolveSelectorHelper
train
function resolveSelectorHelper(selector, opts, resultArr) { if (selector !== null && typeof selector === 'object') { if (typeof selector._resolveSelectorHelper === 'function') { selector._resolveSelectorHelper(opts, resultArr); return; } if (Array.isArray(selector)) { for (var i = 0; i < selector.length; i++) { resolveSelectorHelper(selector[i], opts, resultArr); } return; } } // Handle scalar case var intInds; switch (opts.resolveMode) { case RESOLVE_MODE.INT: resultArr.push(resolveIntIdx(selector, opts.maxLen)); break; case RESOLVE_MODE.COL: if (isNumber(selector)) { resultArr.push(resolveIntIdx(selector, opts.maxLen)); } else if (isString(selector) || selector === null) { intInds = opts.index.lookupKey([selector]); processLookupResults(intInds, selector, opts, resultArr); } else {
javascript
{ "resource": "" }
q4338
resolveRangeBound
train
function resolveRangeBound(bound, opts, isStop, includeStop) { var result; if (isUndefined(bound)) { return isStop ? opts.maxLen : 0; } var useIntIndexing = ( opts.resolveMode === RESOLVE_MODE.INT || (opts.resolveMode === RESOLVE_MODE.COL && typeof bound === 'number') ); if (includeStop === null) { includeStop = useIntIndexing ? false : true; } if (useIntIndexing) { result = resolveIntIdx(bound, opts.maxLen, false); return (isStop && includeStop) ? result + 1 : result; } else { if (opts.index.arity === 1) { result = opts.index.lookupKey([bound]); if (result === null) { throw new Error('could not find entry for range bound: ' + bound);
javascript
{ "resource": "" }
q4339
resolveIntIdx
train
function resolveIntIdx(inputInt, maxLen, checkBounds) { if (isUndefined(checkBounds)) { checkBounds = true; } if (!Number.isInteger(inputInt)) { throw new Error('expected integer selector for
javascript
{ "resource": "" }
q4340
processLookupResults
train
function processLookupResults(intInds, key, opts, resultArr) { if (intInds === null) { if (opts.resolveMode === RESOLVE_MODE.COL) { throw new Error('could not find column named "' + key + '"'); } else { throw new Error('could find entry for key: ' + key); } }
javascript
{ "resource": "" }
q4341
singleColNameLookup
train
function singleColNameLookup(selector, colNames) { if (isUndefined(selector)) { throw new Error('selector must not be undefined'); } selector = ensureScalar(selector); if (isNumber(selector)) { return resolveIntIdx(selector, colNames.values.length); } else if (isString(selector) || selector === null) { var intInds = colNames._getIndex().lookupKey([selector]); if (intInds === null) { throw new Error('invalid column name: ' + selector);
javascript
{ "resource": "" }
q4342
cleanKey
train
function cleanKey(key, dtype) { return ( key === null ? ESCAPED_KEYS.null
javascript
{ "resource": "" }
q4343
newVector
train
function newVector(array, dtype) { validateDtype(dtype); var proto
javascript
{ "resource": "" }
q4344
mapNonNa
train
function mapNonNa(array, naValue, func) { var len = array.length; var result = allocArray(len); for (var i = 0; i < len; i++) { var value
javascript
{ "resource": "" }
q4345
reduceNonNa
train
function reduceNonNa(array, initValue, func) { var result = initValue; for (var i = 0; i < array.length;
javascript
{ "resource": "" }
q4346
reduceUnless
train
function reduceUnless(array, initValue, condFunc, func) { var result = initValue; for (var i = 0; i < array.length; i++) { var value = array[i]; if (condFunc(value)) {
javascript
{ "resource": "" }
q4347
combineArrays
train
function combineArrays(array1, array2, naValue, func) { var skipMissing = true; if (isUndefined(func)) { func = naValue; skipMissing = false; } var arr1Len = array1.length; var arr2Len = array2.length; var outputLen = validateArrayLengths(arr1Len, arr2Len); var isSingleton1 = (arr1Len === 1); var isSingleton2 = (arr2Len === 1); var result = allocArray(outputLen); for (var i = 0; i < outputLen; i++) {
javascript
{ "resource": "" }
q4348
cumulativeReduce
train
function cumulativeReduce(array, naValue, func) { var skipMissing = false; if (isUndefined(func)) { func = naValue; skipMissing = true; } var outputLen = array.length; var result = allocArray(outputLen); var accumulatedVal = null; var foundNonMissing = false; for (var i = 0; i < outputLen; i++) { var currVal = array[i]; if (isMissing(currVal)) { result[i] = currVal; if (!skipMissing) { // Fill the rest of the array with naValue and break; for (var j = i + 1; j < outputLen; j++) {
javascript
{ "resource": "" }
q4349
subsetArray
train
function subsetArray(array, intIdx) { var result = allocArray(intIdx.length); for (var i = 0; i <
javascript
{ "resource": "" }
q4350
enforceVectorDtype
train
function enforceVectorDtype(array, dtype) { validateDtype(dtype); var coerceFunc = COERCE_FUNC[dtype]; // Coerce all elements to dtype for (var i = 0; i < array.length; i++) {
javascript
{ "resource": "" }
q4351
argSort
train
function argSort(vectors, ascending) { if (vectors.length !== ascending.length) { throw new Error('length of "ascending" must match the number of ' + 'sort columns'); } if (vectors.length === 0) { return null; } var nRow = vectors[0].size(); var result = allocArray(nRow); for (var i = 0; i < nRow; i++) { result[i] = i; } // Create composite compare function var
javascript
{ "resource": "" }
q4352
validateArrayLengths
train
function validateArrayLengths(len1, len2) { var outputLen = len1; if (len1 !== len2) { if (len1 === 1) { outputLen = len2; } else if (len2 !== 1)
javascript
{ "resource": "" }
q4353
ensureScalar
train
function ensureScalar(value) { if (isUndefined(value) || value === null) { return value; } var length = 1; var description = 'a scalar'; if (value.type === vectorProto.type) { length = value.size(); value = value.values[0]; description = 'a vector'; } else if (Array.isArray(value)) { length = value.length; value = value[0];
javascript
{ "resource": "" }
q4354
ensureVector
train
function ensureVector(values, defaultDtype) { if (isMissing(values) || values.type !== vectorProto.type) {
javascript
{ "resource": "" }
q4355
ensureStringVector
train
function ensureStringVector(values) { values = ensureVector(values, 'string'); return
javascript
{ "resource": "" }
q4356
extractMessages
train
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) { var visitor =
javascript
{ "resource": "" }
q4357
extractPlaceholderToIds
train
function extractPlaceholderToIds(messageBundle) { var messageMap = messageBundle.getMessageMap(); var placeholderToIds = {}; Object.keys(messageMap).forEach(function (msgId) {
javascript
{ "resource": "" }
q4358
extractStyleUrls
train
function extractStyleUrls(resolver, baseUrl, cssText) { var foundUrls = []; var modifiedCssText = cssText.replace(_cssImportRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i - 0] = arguments[_i]; } var url = m[1] || m[2]; if (!isStyleUrlResolvable(url)) { // Do not attempt to resolve non-package absolute URLs with URI scheme
javascript
{ "resource": "" }
q4359
createPlatform
train
function createPlatform(injector) { if (_platform && !_platform.destroyed) { throw new Error('There can be only one platform. Destroy the previous one to create a new one.'); } _platform = injector.get(PlatformRef); var
javascript
{ "resource": "" }
q4360
concat
train
function concat() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i];
javascript
{ "resource": "" }
q4361
merge
train
function merge() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i];
javascript
{ "resource": "" }
q4362
race
train
function race() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { observables[_i - 0] = arguments[_i]; } // if the only argument is an array, it was most likely called with // `pair([obs1, obs2, ...])`
javascript
{ "resource": "" }
q4363
mergeMapTo
train
function mergeMapTo(innerObservable, resultSelector, concurrent) { if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } if (typeof resultSelector === 'number') { concurrent
javascript
{ "resource": "" }
q4364
delay
train
function delay(delay, scheduler) { if (scheduler === void 0) { scheduler = async_1.async; } var absoluteDelay = isDate_1.isDate(delay); var delayFor
javascript
{ "resource": "" }
q4365
distinctKey
train
function distinctKey(key, compare, flushes) { return distinct_1.distinct.call(this, function (x, y) { if (compare) {
javascript
{ "resource": "" }
q4366
distinctUntilKeyChanged
train
function distinctUntilKeyChanged(key, compare) { return distinctUntilChanged_1.distinctUntilChanged.call(this, function (x, y) { if (compare) {
javascript
{ "resource": "" }
q4367
find
train
function find(predicate, thisArg) { if (typeof predicate !== 'function') { throw new TypeError('predicate is not a function'); } return
javascript
{ "resource": "" }
q4368
multicast
train
function multicast(subjectOrSubjectFactory, selector) { var subjectFactory; if (typeof subjectOrSubjectFactory === 'function') { subjectFactory = subjectOrSubjectFactory; } else { subjectFactory = function subjectFactory() { return subjectOrSubjectFactory;
javascript
{ "resource": "" }
q4369
publish
train
function publish(selector) { return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
javascript
{ "resource": "" }
q4370
done
train
function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0;
javascript
{ "resource": "" }
q4371
defaults
train
function defaults(object, defs) { var key; object = assign({}, object); defs = defs || {}; // Iterate over object non-prototype properties: for (key in defs) { if (defs.hasOwnProperty(key)) { // Replace
javascript
{ "resource": "" }
q4372
train
function (VMType, ViewType) { var vm = new VMType(); var vmFunctionProps = getFunctionalPropertiesMap(vm); var VConnect = /** @class */ (function (_super) { __extends(VConnect, _super); function VConnect() { return _super !== null && _super.apply(this, arguments) || this; } VConnect.prototype.render = function () { var props = this.props;
javascript
{ "resource": "" }
q4373
train
function() { var _this = this; this.canvas = document.createElement('canvas'); // Scale to same size as original canvas this.resize(true); document.body.appendChild(this.canvas); this.ctx = this.canvas.getContext( '2d'); window.addEventListener( 'resize', function() { setTimeout(function(){ GameController.resize.call(_this); }, 10); }); // Set the touch events for this new canvas this.setTouchEvents(); // Load
javascript
{ "resource": "" }
q4374
train
function( value, axis ){ if( !value ) return 0; if( typeof value === 'number' ) return value;
javascript
{ "resource": "" }
q4375
train
function( eventName, keyCode ) { // No keyboard, can't simulate... if( typeof window.onkeydown === 'undefined' ) return false; var oEvent = document.createEvent('KeyboardEvent'); // Chromium Hack if( navigator.userAgent.toLowerCase().indexOf( 'chrome' ) !== -1 ) { Object.defineProperty( oEvent, 'keyCode', { get: function() { return this.keyCodeVal; } }); Object.defineProperty( oEvent, 'which', { get: function() { return this.keyCodeVal;
javascript
{ "resource": "" }
q4376
train
function( options ) { var direction = new TouchableDirection( options); direction.id = this.touchableAreas.push( direction);
javascript
{ "resource": "" }
q4377
train
function() { for( var i = 0, j = this.touchableAreasCount; i < j; i++ ) { var area = this.touchableAreas[ i ]; if( typeof area === 'undefined' ) continue; area.draw(); // Go through all touches to see if any hit this area var touched = false; for( var k = 0, l = this.touches.length; k < l; k++ ) { var touch = this.touches[ k ]; if( typeof touch === 'undefined' ) continue; var x = this.normalizeTouchPositionX(touch.clientX), y = this.normalizeTouchPositionY(touch.clientY);
javascript
{ "resource": "" }
q4378
TouchableButton
train
function TouchableButton( options ) { for( var i in options ) { if( i === 'x' ) this[i] = GameController.getPixels( options[i], 'x'); else if( i === 'y' || i === 'radius' ){
javascript
{ "resource": "" }
q4379
ZCLClient
train
function ZCLClient(config) { ZNPClient.call(this, config); // handle zcl messages this.on('incoming-message', this._handleIncomingMessage.bind(this)); // handle attribute reports this.on('zcl-command:ReportAttributes',
javascript
{ "resource": "" }
q4380
ZNPClient
train
function ZNPClient(config) { this._devices = {}; this.config = config; if (!config || !config.panId) { throw new Error('You must set "panId" on ZNPClient config'); } this.comms = new ZNPSerial(); // Device state notifications this.comms.on('command:ZDO_STATE_CHANGE_IND', this._handleStateChange.bind(this)); // Device announcements this.comms.on('command:ZDO_END_DEVICE_ANNCE_IND', this._handleDeviceAnnounce.bind(this));
javascript
{ "resource": "" }
q4381
calculateFCS
train
function calculateFCS(buffer) { var fcs = 0; for (var i = 0; i < buffer.length; i++) {
javascript
{ "resource": "" }
q4382
ZCLCluster
train
function ZCLCluster(endpoint, clusterId) { this.endpoint = endpoint; this.device = this.endpoint.device; this.client = this.device.client; this.comms = this.client.comms; // XXX: Horrible hack, fix me. this.client.on('command.' + this.device.shortAddress + '.' + endpoint.endpointId + '.' + clusterId, function(command) { debug(this, 'command received', command); this.emit('command', command); }.bind(this)); this.clusterId = clusterId; this.description = profileStore.getCluster(clusterId) || { name: 'UNKNOWN DEVICE' }; this.name = this.description.name; this.attributes = {}; if (this.description.attribute) { this.description.attribute.forEach(function(attr) { var attrId = attr.id; this.attributes[attr.name] = this.attributes[attrId] = { name: attr.name, id: attr.id, read: function() { return this.readAttributes(attrId).then(function(responses) { var response = responses[attrId]; //debug('Responses', responses); if (response.status.key !== 'SUCCESS') { throw new Error('Failed to get attribute. Status', status); } return response.value; });
javascript
{ "resource": "" }
q4383
buildURL
train
function buildURL(connection) { var scheme; var url; switch (connection.adapter) { case 'sails-mysql': scheme = 'mysql'; break; case 'sails-postgresql': scheme = 'postgres'; break; case 'sails-mongo': scheme = 'mongodb' break; default: throw new Error('migrations not supported for ' + connection.adapter); } // return the connection url if one is configured if (connection.url) { return connection.url; } url = scheme + '://'; if (connection.user) { url += connection.user; if (connection.password) { url += ':' + encodeURIComponent(connection.password) } url += '@'; } url += connection.host ||
javascript
{ "resource": "" }
q4384
parseSailsConfig
train
function parseSailsConfig(sailsConfig) { var res = {}; var connection; if (!sailsConfig.migrations) { throw new Error('Migrations not configured. Please setup ./config/migrations.js'); } var connectionName = sailsConfig.migrations.connection; if (!connectionName) { throw new Error('connection missing from ./config/migrations.js'); } connection = sailsConfig.connections[connectionName]; if (!connection) { throw new Error('could not find connection ' + connectionName + ' in ./config/connections.js'); } // build the db url, which contains
javascript
{ "resource": "" }
q4385
buildDbMigrateArgs
train
function buildDbMigrateArgs(grunt, config, command) { var args = []; var name = grunt.option('name'); args.push(command); if (command === 'create') { if (!name) { throw new Error('--name required to create migration'); } args.push(name); } if (grunt.option('count') !== undefined) { args.push('--count'); args.push(grunt.option('count')); } if (grunt.option('dry-run')) { args.push('--dry-run'); } if (grunt.option('db-verbose')) {
javascript
{ "resource": "" }
q4386
usage
train
function usage(grunt) { grunt.log.writeln('usage: grunt db:migrate[:up|:down|:create] [options]'); grunt.log.writeln(' See ./migrations/README.md for more details'); grunt.log.writeln(); grunt.log.writeln('db:migrate:create Options:'); grunt.log.writeln(' --name=NAME Name of the migration to create'); grunt.log.writeln(); grunt.log.writeln('db:migrate[:up|:down] Options:'); grunt.log.writeln(' --count=N Max number
javascript
{ "resource": "" }
q4387
handleMessageFromMainThread
train
function handleMessageFromMainThread(message) { var kind = message.data.kind; var payload = message.data.payload; if (kind === messageKind.init) { graph = fromjson(payload.graph); var options = JSON.parse(payload.options); init(graph, options); } else if (kind === messageKind.step) { step(); } else if (kind === messageKind.pinNode) {
javascript
{ "resource": "" }
q4388
bindData
train
function bindData(target, key, selector) { return state_1.State.select(selector).subscribe(function (args) { if (typeof target.setState === 'function') {
javascript
{ "resource": "" }
q4389
action
train
function action(targetAction) { return function (target, propertyKey, descriptor) { if (targetAction == undefined) { var metadata = Reflect.getMetadata('design:paramtypes', target, propertyKey); if (metadata == undefined || metadata.length < 2) throw new Error('@action() must be applied to a function with two arguments. ' + 'eg: reducer(state: State, action: SubclassOfAction): State { }'); targetAction = metadata[1]; } var statexActions = {}; if (Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, target)) { statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, target);
javascript
{ "resource": "" }
q4390
subscribe
train
function subscribe(propsClass) { var _this = this; var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, propsClass || this); if (dataBindings != undefined) { var selectors_1 = dataBindings.selectors || {};
javascript
{ "resource": "" }
q4391
unsubscribe
train
function unsubscribe() { var _this = this; var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, this); if (dataBindings != undefined) { var subscriptions = dataBindings.subscriptions || []; subscriptions.forEach(function (item) { return item.target === _this && item.subscription != undefined && item.subscription.unsubscribe();
javascript
{ "resource": "" }
q4392
train
function() { if (!this.openAsModal_) { return; } this.openAsModal_ = false; this.dialog_.style.zIndex = ''; // This won't match the native <dialog> exactly because if the user set top on a centered // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's // possible to polyfill this perfectly. if (this.replacedStyleTop_) {
javascript
{ "resource": "" }
q4393
train
function() { // Find element with `autofocus` attribute, or fall back to the first form/tabindex control. var target = this.dialog_.querySelector('[autofocus]:not([disabled])'); if (!target && this.dialog_.tabIndex >= 0) { target = this.dialog_; } if (!target) { // Note that this is 'any focusable area'. This list is probably not exhaustive, but the // alternative involves stepping through and trying to focus everything. var opts = ['button', 'input', 'keygen', 'select', 'textarea']; var query = opts.map(function(el) { return el + ':not([disabled])'; });
javascript
{ "resource": "" }
q4394
train
function(opt_returnValue) { if (!this.dialog_.hasAttribute('open')) { throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.'); } this.setOpen(false); // Leave returnValue untouched in case it was set directly on the element if (opt_returnValue !== undefined) { this.dialog_.returnValue = opt_returnValue;
javascript
{ "resource": "" }
q4395
store
train
function store() { return function (storeClass) { // save a reference to the original constructor var original = storeClass; // a utility function to generate instances of a class function construct(constructor, args) { var dynamicClass = function () { return new (constructor.bind.apply(constructor, [void 0].concat(args)))(); }; dynamicClass.prototype = constructor.prototype; return new dynamicClass(); } // the new constructor behavior var overriddenConstructor = function Store() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this)) return; var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this);
javascript
{ "resource": "" }
q4396
Store
train
function Store() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this)) return; var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this);
javascript
{ "resource": "" }
q4397
select
train
function select(state, selector) { if (state == undefined) return; if (selector == undefined) return state; try {
javascript
{ "resource": "" }
q4398
loader
train
function loader(content, sourceMap) { /* jshint validthis:true */ // loader result is cacheable this.cacheable(); // path of the file being processed var filename = path.relative(this.options.context || process.cwd(), this.resourcePath).replace(/\\/g, '/'), options = loaderUtils.parseQuery(this.query), useMap = loader.sourceMap || options.sourceMap; // make sure the AST has the data from the original source map var pending = migrate.processSync(content,
javascript
{ "resource": "" }
q4399
highlightText
train
function highlightText(){ var text = $scope.areaData, html = htmlEncode(text); if(typeof($scope.areaConfig.autocomplete) === 'undefined' || $scope.areaConfig.autocomplete.length === 0){ return; } $scope.areaConfig.autocomplete.forEach(function(autoList){ for(var i=0; i<autoList.words.length; i++){ if(typeof(autoList.words[i]) === "string"){ html = html.replace(new RegExp("([^\\w]|\\b)("+autoList.words[i]+")([^\\w]|\\b)", 'g'), '$1<span class="'+autoList.cssClass+'">$2</span>$3');
javascript
{ "resource": "" }