_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| 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 = new Decimal(Math.floor(middle.div(step).toNumber())).mul(step);
} else if (absVal > 1) {
// Return the maximum integer which is smaller than 'value' when 'value' is greater than 1
middle = new Decimal(Math.floor(value));
}
} else if (value === 0) {
middle = new Decimal(Math.floor((tickCount - 1) / 2));
} else if (!allowDecimals) {
middle = new Decimal(Math.floor(value));
}
const middleIndex = Math.floor((tickCount - 1) / 2);
const fn = compose(
map(n => middle.add(new Decimal(n - middleIndex).mul(step)).toNumber()),
range,
);
return fn(0, tickCount);
}
|
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) {
// When more ticks need to cover the interval, step should be bigger.
return calculateStep(min, max, tickCount, allowDecimals, correctionFactor + 1);
} if (scaleCount < tickCount) {
// When less ticks can cover the interval, we should add some additional ticks
upCount = max > 0 ? upCount + (tickCount - scaleCount) : upCount;
belowCount = max > 0 ? belowCount : belowCount + (tickCount - scaleCount);
}
return {
step,
tickMin: middle.sub(new Decimal(belowCount).mul(step)),
tickMax: middle.add(new Decimal(upCount).mul(step)),
};
}
|
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;
}
if (cormin === cormax) {
return getTickOfSingleValue(cormin, tickCount, allowDecimals);
}
// Get the step between two ticks
const { step, tickMin, tickMax } = calculateStep(cormin, cormax, count, allowDecimals);
const values = Arithmetic.rangeStep(tickMin, tickMax.add(new Decimal(0.1).mul(step)), step);
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 = compose(
map(n => new Decimal(cormin).add(new Decimal(n).mul(step)).toNumber()),
range,
);
const values = fn(0, count).filter(entry => (entry >= cormin && entry <= cormax));
return min > max ? reverse(values) : values;
}
|
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 === cormax) { return [cormin]; }
const count = Math.max(tickCount, 2);
const step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0);
const values = [
...Arithmetic.rangeStep(
new Decimal(cormin),
new Decimal(cormax).sub(new Decimal(0.99).mul(step)),
step,
),
cormax,
];
return min > max ? reverse(values) : values;
}
|
javascript
|
{
"resource": ""
}
|
q4305
|
List
|
train
|
function List(props) {
var tag = props.type.toLowerCase() === 'bullet' ? 'ul' : 'ol';
var attrs = getCoreProps(props);
if (props.start !== null && props.start !== 1) {
attrs.start = props.start.toString();
}
return createElement(tag, attrs, props.children);
}
|
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 = node.title || undef;
if (opts.linkTarget) {
props.target = opts.linkTarget;
}
break;
case 'image':
props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination;
props.title = node.title || undef;
// Commonmark treats image description as children. We just want the text
props.alt = node.react.children.join('');
node.react.children = undef;
break;
case 'list':
props.start = node.listStart;
props.type = node.listType;
props.tight = node.listTight;
break;
default:
}
if (typeof renderer !== 'string') {
props.literal = node.literal;
}
var children = props.children || (node.react && node.react.children);
if (Array.isArray(children)) {
props.children = children.reduce(reduceChildren, []) || null;
}
return props;
}
|
javascript
|
{
"resource": ""
}
|
q4307
|
BRDA
|
train
|
function BRDA (lineNumber, blockNumber, branchNumber, hits) {
this.lineNumber = lineNumber
this.blockNumber = blockNumber
this.branchNumber = branchNumber
this.hits = hits
}
|
javascript
|
{
"resource": ""
}
|
q4308
|
findDA
|
train
|
function findDA (source, lineNumber) {
for (var i = 0; i < source.length; i++) {
var da = source[i]
if (da.lineNumber === lineNumber) {
return da
}
}
return null
}
|
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 === branchNumber &&
brda.lineNumber === lineNumber) {
return brda
}
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q4310
|
findCoverageFile
|
train
|
function findCoverageFile (source, filename) {
for (var i = 0; i < source.length; i++) {
var file = source[i]
if (file.filename === filename) {
return file
}
}
return null
}
|
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(':')
var currentCoverageFile = findCoverageFile(lcov, currentFileName)
if (currentCoverageFile) {
return currentCoverageFile
}
currentCoverageFile = new CoverageFile(currentFileName)
lcov.push(currentCoverageFile)
return currentCoverageFile
}
|
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 = findDA(currentCoverageFile.DARecords, lineNumber)
if (existingDA) {
existingDA.hits += hits
return
}
currentCoverageFile.DARecords.push(new DA(lineNumber, hits))
}
|
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
// to the code being executed, but the branch not being taken). Keep
// it as a string and let mergedBRDAHits work it out.
var hits = numberSplit[3]
if (existingBRDA) {
existingBRDA.hits = mergedBRDAHits(existingBRDA.hits, hits)
return
}
currentCoverageFile.BRDARecords.push(new BRDA(lineNumber, blockNumber, branchNumber, hits))
}
|
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(':')
var prefix = prefixSplit[0]
switch (prefix) {
case 'SF':
currentCoverageFile = parseSF(lcov, prefixSplit)
break
case 'DA':
parseDA(currentCoverageFile, prefixSplit)
break
case 'BRDA':
parseBRDA(currentCoverageFile, prefixSplit)
break
default:
// do nothing with not implemented prefixes
}
}
return lcov
}
|
javascript
|
{
"resource": ""
}
|
q4315
|
JUnitXmlReporter
|
train
|
function JUnitXmlReporter(savePath, consolidate, useDotNotation) {
this.savePath = savePath || '';
this.consolidate = typeof consolidate === 'undefined' ? true : consolidate;
this.useDotNotation = typeof useDotNotation === 'undefined' ? true : useDotNotation;
}
|
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 ' +
required + ' must be installed, but version ' + current +
' was detected.'
);
grunt.warn('The correct version of PhantomJS needs to be installed.', 127);
}
}
|
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:');
Debug.log(data);
cmd.responseHandler.call(cmd, data);
});
}
Debug.log('request:');
Debug.log(cmd.command());
process.nextTick(function() {
_self.conn.write(cmd.command());
});
}
}
|
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 = new Eth(new SignerProvider("http://ropsten.infura.io", { privateKey: (account, cb) => cb(null, 'some private key') }));').`); }
const self = this;
self.options = Object.assign({
provider: HTTPProvider,
}, options);
self.timeout = options.timeout || 0;
self.provider = new self.options.provider(path, self.timeout); // eslint-disable-line
self.rpc = new EthRPC(self.provider);
}
|
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;
} else if (args[i] === 'element') {
args[i] = test;
} else {
args[i] = dots.get(test, args[i]);
}
}
return args;
}
|
javascript
|
{
"resource": ""
}
|
q4320
|
wrap
|
train
|
function wrap(body, extKeys) {
const wrapper = [
'(function (exports, require, module, __filename, __dirname',
') { ',
'\n});'
];
extKeys = extKeys ? `, ${extKeys}` : '';
return wrapper[0] + extKeys + wrapper[1] + body + wrapper[2];
}
|
javascript
|
{
"resource": ""
}
|
q4321
|
_getCalleeFilename
|
train
|
function _getCalleeFilename(calls) {
calls = (calls|0) + 3; // 3 is a number of inner calls
const e = {};
Error.captureStackTrace(e);
return parseStackLine(e.stack.split(/\n/)[calls]).filename;
}
|
javascript
|
{
"resource": ""
}
|
q4322
|
train
|
function(subset, key) {
return [
key.nRow(),
key.nCol(),
key.at(0, 'D'),
key.at(0, 'C'),
];
}
|
javascript
|
{
"resource": ""
}
|
|
q4323
|
train
|
function(joinDf, indicatorValues) {
var boolInd = joinDf.c('_join').isIn(indicatorValues);
return joinDf.s(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) {
throw new Error('all row arrays must be of the same size');
}
for (j = 0; j < nCol; j++) {
columns[j][i] = rowArray[j];
}
}
return newDataFrame(columns, colNames);
}
|
javascript
|
{
"resource": ""
}
|
q4325
|
rightAlign
|
train
|
function rightAlign(strVec) {
var maxWidth = strVec.nChar().max();
var padding = jd.rep(' ', maxWidth).strJoin('');
return strVec.map(function(str) {
return (padding + str).slice(-padding.length);
});
}
|
javascript
|
{
"resource": ""
}
|
q4326
|
makeRowIds
|
train
|
function makeRowIds(numRows, maxLines) {
var printVec = jd.seq(numRows)._toTruncatedPrintVector(maxLines);
return printVec.map(function(str) {
return str === _SKIP_MARKER ? str : str + _ROW_ID_SUFFIX;
});
}
|
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) {
str = lines[0] + '...';
}
if (str.length > _MAX_STR_WIDTH) {
str = str.slice(0, _MAX_STR_WIDTH - 3) + '...';
}
return str;
}
}
|
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');
} else if (candidate < lowerBound) {
throw new Error('"' + label + '" too small');
}
}
|
javascript
|
{
"resource": ""
}
|
q4329
|
fractionDigits
|
train
|
function fractionDigits(number) {
var splitArr = number.toString().split('.');
return (splitArr.length > 1) ?
splitArr[1].length :
0;
}
|
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;
});
var result = {dtype: dtype, values: values};
if (includeMetadata) {
result.version = jd.version;
result.type = vectorProto.type;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q4331
|
numClose
|
train
|
function numClose(x, y) {
return (Number.isNaN(x) && Number.isNaN(y)) ||
Math.abs(x - y) <= 1e-7;
}
|
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 = 0; i < nCol; i++) {
var leftVal = (leftInd === null) ? null :
leftNonKeyDf._cols[i].values[leftInd];
arrayCols[colInd].push(leftVal);
colInd++;
}
nCol = rightNonKeyDf.nCol();
for (i = 0; i < nCol; i++) {
var rightVal = (rightInd === null) ? null :
rightNonKeyDf._cols[i].values[rightInd];
arrayCols[colInd].push(rightVal);
colInd++;
}
if (colInd < arrayCols.length) {
// Add the join indicator value if there's a final column for it
arrayCols[colInd].push(indicatorValue);
}
}
|
javascript
|
{
"resource": ""
}
|
q4333
|
keyIndexing
|
train
|
function keyIndexing(selector, maxLen, index) {
var opts = resolverOpts(RESOLVE_MODE.KEY, maxLen, index);
return resolveSelector(selector, opts);
}
|
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);
}
if (Array.isArray(selector)) {
selector = inferVectorDtype(selector.slice(), 'object');
}
if (selector.type === vectorProto.type && selector.dtype === 'boolean') {
if (selector.size() !== maxLen) {
throw new Error('inappropriate boolean indexer length (' +
selector.size() + '); expected length to be ' + maxLen);
}
return selector.which();
}
}
|
javascript
|
{
"resource": ""
}
|
q4335
|
excludeIntIndices
|
train
|
function excludeIntIndices(intIdxVector, maxLen) {
return jd.seq(maxLen).isIn(intIdxVector).not().which();
}
|
javascript
|
{
"resource": ""
}
|
q4336
|
resolveSelector
|
train
|
function resolveSelector(selector, opts) {
var resultArr = [];
resolveSelectorHelper(selector, opts, resultArr);
return newVector(resultArr, 'number');
}
|
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 {
throw new Error('expected integer or string selector but got: ' +
selector);
}
break;
case RESOLVE_MODE.KEY:
if (opts.index.arity === 1) {
var expectedDtype = opts.index.initVectors[0].dtype;
validateScalarIsDtype(selector, expectedDtype);
intInds = opts.index.lookupKey([selector]);
processLookupResults(intInds, selector, opts, resultArr);
} else {
// TODO
throw new Error('unimplemented case (TODO)');
}
break;
default:
throw new Error('Unrecognized RESOLVE_MODE: ' + opts.resolveMode);
}
}
|
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);
} else if (typeof result === 'number') {
return (isStop && includeStop) ? result + 1 : result;
} else {
return (isStop && includeStop) ?
result[result.length - 1] + 1 :
result[0];
}
} else {
// TODO
throw new Error('unimplemented case (TODO)');
}
}
}
|
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 integer indexing ' +
'but got non-integer: ' + inputInt);
}
var result = inputInt < 0 ? maxLen + inputInt : inputInt;
if (checkBounds && (result < 0 || result >= maxLen)) {
throw new Error('integer index out of bounds');
}
return result;
}
|
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);
}
} else if (typeof intInds === 'number') {
resultArr.push(intInds);
} else {
for (var j = 0; j < intInds.length; j++) {
resultArr.push(intInds[j]);
}
}
}
|
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);
} else if (typeof intInds !== 'number') {
// must be an array, so use the first element
intInds = intInds[0];
}
return intInds;
} else {
throw new Error('column selector must be an integer or string');
}
}
|
javascript
|
{
"resource": ""
}
|
q4342
|
cleanKey
|
train
|
function cleanKey(key, dtype) {
return (
key === null ? ESCAPED_KEYS.null :
isUndefined(key) ? ESCAPED_KEYS.undefined :
dtype === 'date' ? key.valueOf() :
key
);
}
|
javascript
|
{
"resource": ""
}
|
q4343
|
newVector
|
train
|
function newVector(array, dtype) {
validateDtype(dtype);
var proto = PROTO_MAP[dtype];
var vector = Object.create(proto);
vector._init(array);
return vector;
}
|
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 = array[i];
result[i] = isMissing(value) ? naValue : func(value);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q4345
|
reduceNonNa
|
train
|
function reduceNonNa(array, initValue, func) {
var result = initValue;
for (var i = 0; i < array.length; i++) {
var value = array[i];
if (!isMissing(value)) {
result = func(result, value);
}
}
return result;
}
|
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)) {
return value;
}
result = func(result, value);
}
return result;
}
|
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++) {
var val1 = isSingleton1 ? array1[0] : array1[i];
var val2 = isSingleton2 ? array2[0] : array2[i];
if (skipMissing && (isMissing(val1) || isMissing(val2))) {
result[i] = naValue;
} else {
result[i] = func(val1, val2);
}
}
return result;
}
|
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++) {
result[j] = naValue;
}
break;
}
} else {
accumulatedVal = foundNonMissing ?
func(accumulatedVal, currVal) :
currVal;
foundNonMissing = true;
result[i] = accumulatedVal;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q4349
|
subsetArray
|
train
|
function subsetArray(array, intIdx) {
var result = allocArray(intIdx.length);
for (var i = 0; i < intIdx.length; i++) {
result[i] = array[intIdx[i]];
}
return result;
}
|
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++) {
array[i] = coerceFunc(array[i]);
}
// Construct vector
return newVector(array, dtype);
}
|
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 compareFuncs = ascending.map(function(asc) {
return asc ? compare : compareReverse;
});
var compositeCompare = function(a, b) {
var result = 0;
for (var i = 0; i < compareFuncs.length; i++) {
var aValue = vectors[i].values[a];
var bValue = vectors[i].values[b];
result = compareFuncs[i](aValue, bValue);
if (result !== 0) {
return result;
}
}
// Order based on row index as last resort to ensure stable sorting
return compare(a, b);
};
result.sort(compositeCompare);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q4352
|
validateArrayLengths
|
train
|
function validateArrayLengths(len1, len2) {
var outputLen = len1;
if (len1 !== len2) {
if (len1 === 1) {
outputLen = len2;
} else if (len2 !== 1) {
throw new Error('incompatible array lengths: ' + len1 + ' and ' +
len2);
}
}
return outputLen;
}
|
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];
description = 'an array';
}
if (length !== 1) {
throw new Error('expected a single scalar value but got ' +
description + ' of length ' + length);
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q4354
|
ensureVector
|
train
|
function ensureVector(values, defaultDtype) {
if (isMissing(values) || values.type !== vectorProto.type) {
values = Array.isArray(values) ?
inferVectorDtype(values.slice(), defaultDtype) :
inferVectorDtype([values], defaultDtype);
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
q4355
|
ensureStringVector
|
train
|
function ensureStringVector(values) {
values = ensureVector(values, 'string');
return (values.dtype !== 'string') ?
values.toDtype('string') :
values;
}
|
javascript
|
{
"resource": ""
}
|
q4356
|
extractMessages
|
train
|
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
var visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.extract(nodes, interpolationConfig);
}
|
javascript
|
{
"resource": ""
}
|
q4357
|
extractPlaceholderToIds
|
train
|
function extractPlaceholderToIds(messageBundle) {
var messageMap = messageBundle.getMessageMap();
var placeholderToIds = {};
Object.keys(messageMap).forEach(function (msgId) {
placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds;
});
return placeholderToIds;
}
|
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
return m[0];
}
foundUrls.push(resolver.resolve(baseUrl, url));
return '';
});
return new StyleWithImports(modifiedCssText, foundUrls);
}
|
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 inits = injector.get(PLATFORM_INITIALIZER, null);
if (inits)
inits.forEach(function (init) { return init(); });
return _platform;
}
|
javascript
|
{
"resource": ""
}
|
q4360
|
concat
|
train
|
function concat() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i - 0] = arguments[_i];
}
return concatStatic.apply(void 0, [this].concat(observables));
}
|
javascript
|
{
"resource": ""
}
|
q4361
|
merge
|
train
|
function merge() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i - 0] = arguments[_i];
}
observables.unshift(this);
return mergeStatic.apply(this, observables);
}
|
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, ...])`
if (observables.length === 1 && isArray_1.isArray(observables[0])) {
observables = observables[0];
}
observables.unshift(this);
return raceStatic.apply(this, observables);
}
|
javascript
|
{
"resource": ""
}
|
q4363
|
mergeMapTo
|
train
|
function mergeMapTo(innerObservable, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
if (typeof resultSelector === 'number') {
concurrent = resultSelector;
resultSelector = null;
}
return this.lift(new MergeMapToOperator(innerObservable, resultSelector, 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 = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
return this.lift(new DelayOperator(delayFor, scheduler));
}
|
javascript
|
{
"resource": ""
}
|
q4365
|
distinctKey
|
train
|
function distinctKey(key, compare, flushes) {
return distinct_1.distinct.call(this, function (x, y) {
if (compare) {
return compare(x[key], y[key]);
}
return x[key] === y[key];
}, flushes);
}
|
javascript
|
{
"resource": ""
}
|
q4366
|
distinctUntilKeyChanged
|
train
|
function distinctUntilKeyChanged(key, compare) {
return distinctUntilChanged_1.distinctUntilChanged.call(this, function (x, y) {
if (compare) {
return compare(x[key], y[key]);
}
return x[key] === y[key];
});
}
|
javascript
|
{
"resource": ""
}
|
q4367
|
find
|
train
|
function find(predicate, thisArg) {
if (typeof predicate !== 'function') {
throw new TypeError('predicate is not a function');
}
return this.lift(new FindValueOperator(predicate, this, false, thisArg));
}
|
javascript
|
{
"resource": ""
}
|
q4368
|
multicast
|
train
|
function multicast(subjectOrSubjectFactory, selector) {
var subjectFactory;
if (typeof subjectOrSubjectFactory === 'function') {
subjectFactory = subjectOrSubjectFactory;
}
else {
subjectFactory = function subjectFactory() {
return subjectOrSubjectFactory;
};
}
return !selector ?
new ConnectableObservable_1.ConnectableObservable(this, subjectFactory) :
new MulticastObservable_1.MulticastObservable(this, subjectFactory, selector);
}
|
javascript
|
{
"resource": ""
}
|
q4369
|
publish
|
train
|
function publish(selector) {
return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
multicast_1.multicast.call(this, new Subject_1.Subject());
}
|
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;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
|
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 values with defaults only if undefined (allow empty/zero values):
if (object[key] == null) {
object[key] = defs[key];
}
}
}
return object;
}
|
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;
return (react_1.default.createElement(ViewType, __assign({ vm: vm }, vmFunctionProps, props)));
};
return VConnect;
}(react_1.default.PureComponent));
return VConnect;
}
|
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 in the initial UI elements
this.loadSide('left');
this.loadSide('right');
// Starts up the rendering / drawing
this.render();
// pause until a touch event
if( !this.touches || !this.touches.length ) this.paused = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q4374
|
train
|
function( value, axis ){
if( !value ) return 0;
if( typeof value === 'number' ) return value;
// a percentage
return parseInt(value, 10) / 100 *
(axis === 'x' ? this.canvas.width : this.canvas.height);
}
|
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; }
});
}
var initKeyEvent = oEvent.initKeyboardEvent || oEvent.initKeyEvent;
initKeyEvent.call(oEvent,
'key' + eventName,
true,
true,
document.defaultView,
false,
false,
false,
false,
keyCode,
keyCode
);
oEvent.keyCodeVal = keyCode;
}
|
javascript
|
{
"resource": ""
}
|
|
q4376
|
train
|
function( options ) {
var direction = new TouchableDirection( options);
direction.id = this.touchableAreas.push( direction);
this.touchableAreasCount++;
this.boundingSet(options);
}
|
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);
// Check that it's in the bounding box/circle
if( area.check(x, y) && !touched) touched = this.touches[k];
}
if( touched ) {
if( !area.active ) area.touchStartWrapper(touched);
area.touchMoveWrapper(touched);
} else if( area.active ) area.touchEndWrapper(touched);
}
}
|
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' ){
this[i] = GameController.getPixels(options[i], 'y');
} else this[i] = options[i];
}
this.draw();
}
|
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', this._handleReportAttributes.bind(this));
// XXX: This really should be pulled out and handled by the user, or at least put into a IASZone mixin
this.on('zcl-command:IAS Zone.Zone Enroll Request', this._handleZoneEnrollRequest.bind(this));
}
|
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));
// Device endpoint responses
this.comms.on('command:ZDO_MATCH_DESC_RSP', this._handleDeviceMatchDescriptionResponse.bind(this));
this.comms.on('command:ZDO_ACTIVE_EP_RSP', this._handleDeviceMatchDescriptionResponse.bind(this));
// Endpoint description responses
this.comms.on('command:ZDO_SIMPLE_DESC_RSP', this._handleEndpointSimpleDescriptorResponse.bind(this));
// Application framework (ZCL) messages
this.comms.on('command:AF_INCOMING_MSG', this._handleAFIncomingMessage.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q4381
|
calculateFCS
|
train
|
function calculateFCS(buffer) {
var fcs = 0;
for (var i = 0; i < buffer.length; i++) {
fcs ^= buffer[i];
}
return fcs;
}
|
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;
});
}.bind(this)
/*,
write: function(value) {
return this.writeAttributes(attrId).then(function(responses) {
var response = responses[0];
if (response.status.key !== 'SUCCESS') {
throw new Error('Failed to get attribute. Status', status);
}
return response.value;
});
}.bind(this)*/
};
}.bind(this));
}
this.commands = {};
if (this.description.command) {
this.description.command.forEach(function(command) {
var commandId = command.id;
this.commands[command.name] = this.commands[commandId] = function(payload) {
debug(this, 'Sending command', command, command.id, commandId);
return this.sendClusterSpecificCommand(commandId, payload);
}.bind(this);
}.bind(this));
}
}
|
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 || 'localhost';
if (connection.port) {
url += ':' + connection.port;
}
if (connection.database) {
url += '/' + encodeURIComponent(connection.database);
}
var params = [];
if (connection.multipleStatements) {
params.push('multipleStatements=true');
}
if (params.length > 0) {
url += '?' + params.join('&');
}
return url;
}
|
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 the password
res.url = buildURL(connection);
// check for ssl option in connection config
if (connection.ssl) {
res.adapter = connection.adapter;
res.ssl = true;
}
// now build a clean one for logging, without the password
if (connection.password != null) {
connection.password = '****';
}
res.cleanURL = buildURL(connection);
return res;
}
|
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')) {
args.push('--verbose');
}
if (grunt.option('sql-file')) {
args.push('--sql-file');
}
if (grunt.option('coffee-file')) {
args.push('--coffee-file');
} else if (config.coffeeFile) {
args.push('--coffee-file');
}
if (grunt.option('migrations-dir')) {
args.push('--migrations-dir');
args.push(grunt.option('migrations-dir'));
} else if (config.migrationsDir) {
args.push('--migrations-dir');
args.push(config.migrationsDir);
}
if (grunt.option('table')) {
args.push('--table');
args.push(grunt.option('table'));
} else if (config.table) {
args.push('--table');
args.push(config.table);
}
return args;
}
|
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 of migrations to run.');
grunt.log.writeln(' --dry-run Prints the SQL but doesn\'t run it.');
grunt.log.writeln(' --db-verbose Verbose mode.');
grunt.log.writeln(' --sql-file Create sql files for up and down.');
grunt.log.writeln(' --coffee-file Create a coffeescript migration file.');
grunt.log.writeln(' --migrations-dir The directory to use for migration files.');
grunt.log.writeln(' Defaults to "migrations".');
grunt.log.writeln(' --table Specify the table to track migrations in.');
grunt.log.writeln(' Defaults to "migrations".');
}
|
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) {
pinNode(payload.nodeId, payload.isPinned);
} else if (kind === messageKind.setNodePosition) {
setNodePosition(payload.nodeId, payload.x, payload.y, payload.z);
}
// TODO: listen for graph changes from main thread and update layout here.
}
|
javascript
|
{
"resource": ""
}
|
q4388
|
bindData
|
train
|
function bindData(target, key, selector) {
return state_1.State.select(selector).subscribe(function (args) {
if (typeof target.setState === 'function') {
var state = {};
state[key] = args;
target.setState(state);
}
if (typeof target[key] === 'function')
return target[key].call(target, args);
target[key] = args;
});
}
|
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);
}
statexActions[propertyKey] = targetAction;
Reflect.defineMetadata(constance_1.STATEX_ACTION_KEY, statexActions, target);
return {
value: function (state, payload) {
return descriptor.value.call(this, state, payload);
}
};
};
}
|
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 || {};
dataBindings.subscriptions = (dataBindings.subscriptions || []).concat(Object.keys(selectors_1).map(function (key) { return ({
target: _this,
subscription: bindData(_this, key, selectors_1[key])
}); }));
Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this);
}
}
|
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(); });
dataBindings.subscriptions = subscriptions.filter(function (item) { return item.target !== _this; });
Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this);
}
}
|
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_) {
this.dialog_.style.top = '';
this.replacedStyleTop_ = false;
}
// Clear the backdrop and remove from the manager.
this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_);
dialogPolyfill.dm.removeDialog(this);
}
|
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])';
});
// TODO(samthor): tabindex values that are not numeric are not focusable.
query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled
target = this.dialog_.querySelector(query.join(', '));
}
safeBlur(document.activeElement);
target && target.focus();
}
|
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;
}
// Triggering "close" event for any attached listeners on the <dialog>.
var closeEvent = new supportCustomEvent('close', {
bubbles: false,
cancelable: false
});
this.dialog_.dispatchEvent(closeEvent);
}
|
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);
Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); });
return construct(original, args);
};
// copy prototype so instanceof operator still works
overriddenConstructor.prototype = original.prototype;
// create singleton instance
var instance = new overriddenConstructor();
// return new constructor (will override original)
return instance && overriddenConstructor;
};
}
|
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);
Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); });
return construct(original, args);
}
|
javascript
|
{
"resource": ""
}
|
q4397
|
select
|
train
|
function select(state, selector) {
if (state == undefined)
return;
if (selector == undefined)
return state;
try {
return selector(state);
}
catch (error) {
return undefined;
}
}
|
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, {
filename : filename,
sourceMap: useMap && (sourceMap || true),
quoteChar: options.singleQuote ? '\'' : '"'
});
// emit deprecation warning
if ((pending.isChanged) && (options.deprecate)) {
var text = ' ' + PACKAGE_NAME + ': @ngInject doctag is deprecated, use "ngInject" string directive instead';
this.emitWarning(text);
}
// emit errors
if (pending.errors.length) {
var text = pending.errors.map(indent).join('\n');
this.emitError(text);
}
// complete
if (useMap) {
this.callback(null, pending.content, pending.sourceMap);
} else {
return pending.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');
}else{
html = html.replace(autoList.words[i], function(match){
return '<span class="'+autoList.cssClass+'">'+match+'</span>';
});
}
}
});
// Add to the fakeArea
$scope.fakeArea = $sce.trustAsHtml(html);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.