_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q16200
|
transformArcs
|
train
|
function transformArcs(arcs, scale, translate) {
for (let i = 0, ii = arcs.length; i < ii; ++i) {
transformArc(arcs[i], scale, translate);
}
}
|
javascript
|
{
"resource": ""
}
|
q16201
|
transformArc
|
train
|
function transformArc(arc, scale, translate) {
let x = 0;
let y = 0;
for (let i = 0, ii = arc.length; i < ii; ++i) {
const vertex = arc[i];
x += vertex[0];
y += vertex[1];
vertex[0] = x;
vertex[1] = y;
transformVertex(vertex, scale, translate);
}
}
|
javascript
|
{
"resource": ""
}
|
q16202
|
transformVertex
|
train
|
function transformVertex(vertex, scale, translate) {
vertex[0] = vertex[0] * scale[0] + translate[0];
vertex[1] = vertex[1] * scale[1] + translate[1];
}
|
javascript
|
{
"resource": ""
}
|
q16203
|
touchstart
|
train
|
function touchstart(inEvent) {
this.vacuumTouches_(inEvent);
this.setPrimaryTouch_(inEvent.changedTouches[0]);
this.dedupSynthMouse_(inEvent);
this.clickCount_++;
this.processTouches_(inEvent, this.overDown_);
}
|
javascript
|
{
"resource": ""
}
|
q16204
|
tileUrlFunction
|
train
|
function tileUrlFunction(tileCoord) {
return ('https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' +
'{z}/{x}/{y}.vector.pbf?access_token=' + key)
.replace('{z}', String(tileCoord[0] * 2 - 1))
.replace('{x}', String(tileCoord[1]))
.replace('{y}', String(tileCoord[2]))
.replace('{a-d}', 'abcd'.substr(
((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1));
}
|
javascript
|
{
"resource": ""
}
|
q16205
|
train
|
function(e) {
if (e.doclet.kind == 'typedef' && e.doclet.properties) {
properties[e.doclet.longname] = e.doclet.properties;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q16206
|
getBinaryPath
|
train
|
function getBinaryPath(binaryName) {
if (isWindows) {
binaryName += '.cmd';
}
const jsdocResolved = require.resolve('jsdoc/jsdoc.js');
const expectedPaths = [
path.join(__dirname, '..', 'node_modules', '.bin', binaryName),
path.resolve(path.join(path.dirname(jsdocResolved), '..', '.bin', binaryName))
];
for (let i = 0; i < expectedPaths.length; i++) {
const expectedPath = expectedPaths[i];
if (fse.existsSync(expectedPath)) {
return expectedPath;
}
}
throw Error('JsDoc binary was not found in any of the expected paths: ' + expectedPaths);
}
|
javascript
|
{
"resource": ""
}
|
q16207
|
getPaths
|
train
|
function getPaths() {
return new Promise((resolve, reject) => {
let paths = [];
const walker = walk(sourceDir);
walker.on('file', (root, stats, next) => {
const sourcePath = path.join(root, stats.name);
if (/\.js$/.test(sourcePath)) {
paths.push(sourcePath);
}
next();
});
walker.on('errors', () => {
reject(new Error(`Trouble walking ${sourceDir}`));
});
walker.on('end', () => {
/**
* Windows has restrictions on length of command line, so passing all the
* changed paths to a task will fail if this limit is exceeded.
* To get round this, if this is Windows and there are newer files, just
* pass the sourceDir to the task so it can do the walking.
*/
if (isWindows) {
paths = [sourceDir];
}
resolve(paths);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16208
|
parseOutput
|
train
|
function parseOutput(output) {
if (!output) {
throw new Error('Expected JSON output');
}
let info;
try {
info = JSON.parse(String(output));
} catch (err) {
throw new Error('Failed to parse output as JSON: ' + output);
}
if (!Array.isArray(info.symbols)) {
throw new Error('Expected symbols array: ' + output);
}
if (!Array.isArray(info.defines)) {
throw new Error('Expected defines array: ' + output);
}
return info;
}
|
javascript
|
{
"resource": ""
}
|
q16209
|
spawnJSDoc
|
train
|
function spawnJSDoc(paths) {
return new Promise((resolve, reject) => {
let output = '';
let errors = '';
const cwd = path.join(__dirname, '..');
const child = spawn(jsdoc, ['-c', jsdocConfig].concat(paths), {cwd: cwd});
child.stdout.on('data', data => {
output += String(data);
});
child.stderr.on('data', data => {
errors += String(data);
});
child.on('exit', code => {
if (code) {
reject(new Error(errors || 'JSDoc failed with no output'));
return;
}
let info;
try {
info = parseOutput(output);
} catch (err) {
reject(err);
return;
}
resolve(info);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16210
|
mousedown
|
train
|
function mousedown(inEvent) {
if (!this.isEventSimulatedFromTouch_(inEvent)) {
// TODO(dfreedman) workaround for some elements not sending mouseup
// http://crbug/149091
if (POINTER_ID.toString() in this.pointerMap) {
this.cancel(inEvent);
}
const e = prepareEvent(inEvent, this.dispatcher);
this.pointerMap[POINTER_ID.toString()] = inEvent;
this.dispatcher.down(e, inEvent);
}
}
|
javascript
|
{
"resource": ""
}
|
q16211
|
mousemove
|
train
|
function mousemove(inEvent) {
if (!this.isEventSimulatedFromTouch_(inEvent)) {
const e = prepareEvent(inEvent, this.dispatcher);
this.dispatcher.move(e, inEvent);
}
}
|
javascript
|
{
"resource": ""
}
|
q16212
|
mouseup
|
train
|
function mouseup(inEvent) {
if (!this.isEventSimulatedFromTouch_(inEvent)) {
const p = this.pointerMap[POINTER_ID.toString()];
if (p && p.button === inEvent.button) {
const e = prepareEvent(inEvent, this.dispatcher);
this.dispatcher.up(e, inEvent);
this.cleanupMouse();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q16213
|
mouseover
|
train
|
function mouseover(inEvent) {
if (!this.isEventSimulatedFromTouch_(inEvent)) {
const e = prepareEvent(inEvent, this.dispatcher);
this.dispatcher.enterOver(e, inEvent);
}
}
|
javascript
|
{
"resource": ""
}
|
q16214
|
mouseout
|
train
|
function mouseout(inEvent) {
if (!this.isEventSimulatedFromTouch_(inEvent)) {
const e = prepareEvent(inEvent, this.dispatcher);
this.dispatcher.leaveOut(e, inEvent);
}
}
|
javascript
|
{
"resource": ""
}
|
q16215
|
train
|
function(point) {
let x_ = null;
let y_ = null;
if (point[0] == extent[0]) {
x_ = extent[2];
} else if (point[0] == extent[2]) {
x_ = extent[0];
}
if (point[1] == extent[1]) {
y_ = extent[3];
} else if (point[1] == extent[3]) {
y_ = extent[1];
}
if (x_ !== null && y_ !== null) {
return [x_, y_];
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q16216
|
fromNamed
|
train
|
function fromNamed(color) {
const el = document.createElement('div');
el.style.color = color;
if (el.style.color !== '') {
document.body.appendChild(el);
const rgb = getComputedStyle(el).color;
document.body.removeChild(el);
return rgb;
} else {
return '';
}
}
|
javascript
|
{
"resource": ""
}
|
q16217
|
getSymbols
|
train
|
async function getSymbols() {
const info = await generateInfo();
return info.symbols.filter(symbol => symbol.kind != 'member');
}
|
javascript
|
{
"resource": ""
}
|
q16218
|
getImport
|
train
|
function getImport(symbol, member) {
const defaultExport = symbol.name.split('~');
const namedExport = symbol.name.split('.');
if (defaultExport.length > 1) {
const from = defaultExport[0].replace(/^module\:/, './');
const importName = from.replace(/[.\/]+/g, '$');
return `import ${importName} from '${from}';`;
} else if (namedExport.length > 1 && member) {
const from = namedExport[0].replace(/^module\:/, './');
const importName = from.replace(/[.\/]+/g, '_');
return `import {${member} as ${importName}$${member}} from '${from}';`;
}
}
|
javascript
|
{
"resource": ""
}
|
q16219
|
formatSymbolExport
|
train
|
function formatSymbolExport(symbol, namespaces, imports) {
const name = symbol.name;
const parts = name.split('~');
const isNamed = parts[0].indexOf('.') !== -1;
const nsParts = parts[0].replace(/^module\:/, '').split(/[\/\.]/);
const last = nsParts.length - 1;
const importName = isNamed ?
'_' + nsParts.slice(0, last).join('_') + '$' + nsParts[last] :
'$' + nsParts.join('$');
let line = nsParts[0];
for (let i = 1, ii = nsParts.length; i < ii; ++i) {
line += `.${nsParts[i]}`;
namespaces[line] = (line in namespaces ? namespaces[line] : true) && i < ii - 1;
}
line += ` = ${importName};`;
imports[getImport(symbol, nsParts.pop())] = true;
return line;
}
|
javascript
|
{
"resource": ""
}
|
q16220
|
generateExports
|
train
|
function generateExports(symbols) {
const namespaces = {};
const imports = [];
let blocks = [];
symbols.forEach(function(symbol) {
const name = symbol.name;
if (name.indexOf('#') == -1) {
const imp = getImport(symbol);
if (imp) {
imports[getImport(symbol)] = true;
}
const block = formatSymbolExport(symbol, namespaces, imports);
if (block !== blocks[blocks.length - 1]) {
blocks.push(block);
}
}
});
const nsdefs = [];
const ns = Object.keys(namespaces).sort();
for (let i = 0, ii = ns.length; i < ii; ++i) {
if (namespaces[ns[i]]) {
nsdefs.push(`${ns[i]} = {};`);
}
}
blocks = Object.keys(imports).concat('\nvar ol = {};\n', nsdefs.sort()).concat(blocks.sort());
blocks.push('', 'export default ol;');
return blocks.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q16221
|
requestFullScreen
|
train
|
function requestFullScreen(element) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
}
}
|
javascript
|
{
"resource": ""
}
|
q16222
|
exitFullScreen
|
train
|
function exitFullScreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
|
javascript
|
{
"resource": ""
}
|
q16223
|
layersPBFReader
|
train
|
function layersPBFReader(tag, layers, pbf) {
if (tag === 3) {
const layer = {
keys: [],
values: [],
features: []
};
const end = pbf.readVarint() + pbf.pos;
pbf.readFields(layerPBFReader, layer, end);
layer.length = layer.features.length;
if (layer.length) {
layers[layer.name] = layer;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q16224
|
layerPBFReader
|
train
|
function layerPBFReader(tag, layer, pbf) {
if (tag === 15) {
layer.version = pbf.readVarint();
} else if (tag === 1) {
layer.name = pbf.readString();
} else if (tag === 5) {
layer.extent = pbf.readVarint();
} else if (tag === 2) {
layer.features.push(pbf.pos);
} else if (tag === 3) {
layer.keys.push(pbf.readString());
} else if (tag === 4) {
let value = null;
const end = pbf.readVarint() + pbf.pos;
while (pbf.pos < end) {
tag = pbf.readVarint() >> 3;
value = tag === 1 ? pbf.readString() :
tag === 2 ? pbf.readFloat() :
tag === 3 ? pbf.readDouble() :
tag === 4 ? pbf.readVarint64() :
tag === 5 ? pbf.readVarint() :
tag === 6 ? pbf.readSVarint() :
tag === 7 ? pbf.readBoolean() : null;
}
layer.values.push(value);
}
}
|
javascript
|
{
"resource": ""
}
|
q16225
|
featurePBFReader
|
train
|
function featurePBFReader(tag, feature, pbf) {
if (tag == 1) {
feature.id = pbf.readVarint();
} else if (tag == 2) {
const end = pbf.readVarint() + pbf.pos;
while (pbf.pos < end) {
const key = feature.layer.keys[pbf.readVarint()];
const value = feature.layer.values[pbf.readVarint()];
feature.properties[key] = value;
}
} else if (tag == 3) {
feature.type = pbf.readVarint();
} else if (tag == 4) {
feature.geometry = pbf.pos;
}
}
|
javascript
|
{
"resource": ""
}
|
q16226
|
readRawFeature
|
train
|
function readRawFeature(pbf, layer, i) {
pbf.pos = layer.features[i];
const end = pbf.readVarint() + pbf.pos;
const feature = {
layer: layer,
type: 0,
properties: {}
};
pbf.readFields(featurePBFReader, feature, end);
return feature;
}
|
javascript
|
{
"resource": ""
}
|
q16227
|
summarize
|
train
|
function summarize(value, counts) {
const min = counts.min;
const max = counts.max;
const num = counts.values.length;
if (value < min) {
// do nothing
} else if (value >= max) {
counts.values[num - 1] += 1;
} else {
const index = Math.floor((value - min) / counts.delta);
counts.values[index] += 1;
}
}
|
javascript
|
{
"resource": ""
}
|
q16228
|
train
|
function(pixels, data) {
const pixel = pixels[0];
const value = vgi(pixel);
summarize(value, data.counts);
if (value >= data.threshold) {
pixel[0] = 0;
pixel[1] = 255;
pixel[2] = 0;
pixel[3] = 128;
} else {
pixel[3] = 0;
}
return pixel;
}
|
javascript
|
{
"resource": ""
}
|
|
q16229
|
getMode
|
train
|
function getMode(type) {
let mode;
if (type === GeometryType.POINT ||
type === GeometryType.MULTI_POINT) {
mode = Mode.POINT;
} else if (type === GeometryType.LINE_STRING ||
type === GeometryType.MULTI_LINE_STRING) {
mode = Mode.LINE_STRING;
} else if (type === GeometryType.POLYGON ||
type === GeometryType.MULTI_POLYGON) {
mode = Mode.POLYGON;
} else if (type === GeometryType.CIRCLE) {
mode = Mode.CIRCLE;
}
return (
/** @type {!Mode} */ (mode)
);
}
|
javascript
|
{
"resource": ""
}
|
q16230
|
resolutionsFromExtent
|
train
|
function resolutionsFromExtent(extent, opt_maxZoom, opt_tileSize) {
const maxZoom = opt_maxZoom !== undefined ?
opt_maxZoom : DEFAULT_MAX_ZOOM;
const height = getHeight(extent);
const width = getWidth(extent);
const tileSize = toSize(opt_tileSize !== undefined ?
opt_tileSize : DEFAULT_TILE_SIZE);
const maxResolution = Math.max(
width / tileSize[0], height / tileSize[1]);
const length = maxZoom + 1;
const resolutions = new Array(length);
for (let z = 0; z < length; ++z) {
resolutions[z] = maxResolution / Math.pow(2, z);
}
return resolutions;
}
|
javascript
|
{
"resource": ""
}
|
q16231
|
encode
|
train
|
function encode(geom) {
let type = geom.getType();
const geometryEncoder = GeometryEncoder[type];
const enc = geometryEncoder(geom);
type = type.toUpperCase();
if (typeof /** @type {?} */ (geom).getFlatCoordinates === 'function') {
const dimInfo = encodeGeometryLayout(/** @type {import("../geom/SimpleGeometry.js").default} */ (geom));
if (dimInfo.length > 0) {
type += ' ' + dimInfo;
}
}
if (enc.length === 0) {
return type + ' ' + EMPTY;
}
return type + '(' + enc + ')';
}
|
javascript
|
{
"resource": ""
}
|
q16232
|
enlargeClipPoint
|
train
|
function enlargeClipPoint(centroidX, centroidY, x, y) {
const dX = x - centroidX;
const dY = y - centroidY;
const distance = Math.sqrt(dX * dX + dY * dY);
return [Math.round(x + dX / distance), Math.round(y + dY / distance)];
}
|
javascript
|
{
"resource": ""
}
|
q16233
|
pointDistanceToSegmentDataSquared
|
train
|
function pointDistanceToSegmentDataSquared(pointCoordinates, segmentData) {
const geometry = segmentData.geometry;
if (geometry.getType() === GeometryType.CIRCLE) {
const circleGeometry = /** @type {import("../geom/Circle.js").default} */ (geometry);
if (segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) {
const distanceToCenterSquared =
squaredCoordinateDistance(circleGeometry.getCenter(), pointCoordinates);
const distanceToCircumference =
Math.sqrt(distanceToCenterSquared) - circleGeometry.getRadius();
return distanceToCircumference * distanceToCircumference;
}
}
return squaredDistanceToSegment(pointCoordinates, segmentData.segment);
}
|
javascript
|
{
"resource": ""
}
|
q16234
|
closestOnSegmentData
|
train
|
function closestOnSegmentData(pointCoordinates, segmentData) {
const geometry = segmentData.geometry;
if (geometry.getType() === GeometryType.CIRCLE &&
segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) {
return geometry.getClosestPoint(pointCoordinates);
}
return closestOnSegment(pointCoordinates, segmentData.segment);
}
|
javascript
|
{
"resource": ""
}
|
q16235
|
createMap
|
train
|
function createMap(divId) {
const source = new OSM();
const layer = new TileLayer({
source: source
});
const map = new Map({
layers: [layer],
target: divId,
view: new View({
center: [0, 0],
zoom: 2
})
});
const zoomslider = new ZoomSlider();
map.addControl(zoomslider);
return map;
}
|
javascript
|
{
"resource": ""
}
|
q16236
|
sortByDistance
|
train
|
function sortByDistance(a, b) {
const deltaA = squaredDistanceToSegment(this.pixelCoordinate_, a.segment);
const deltaB = squaredDistanceToSegment(this.pixelCoordinate_, b.segment);
return deltaA - deltaB;
}
|
javascript
|
{
"resource": ""
}
|
q16237
|
SamplePlatform
|
train
|
function SamplePlatform(log, config, api) {
log("SamplePlatform Init");
var platform = this;
this.log = log;
this.config = config;
this.accessories = [];
this.requestServer = http.createServer(function(request, response) {
if (request.url === "/add") {
this.addAccessory(new Date().toISOString());
response.writeHead(204);
response.end();
}
if (request.url == "/reachability") {
this.updateAccessoriesReachability();
response.writeHead(204);
response.end();
}
if (request.url == "/remove") {
this.removeAccessory();
response.writeHead(204);
response.end();
}
}.bind(this));
this.requestServer.listen(18081, function() {
platform.log("Server Listening...");
});
if (api) {
// Save the API object as plugin needs to register new accessory via this object
this.api = api;
// Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories.
// Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.
// Or start discover new accessories.
this.api.on('didFinishLaunching', function() {
platform.log("DidFinishLaunching");
}.bind(this));
}
}
|
javascript
|
{
"resource": ""
}
|
q16238
|
done
|
train
|
function done() {
// We don't care if we were rejected.
if (rejected === true) {
return;
}
// Decrement the number of async tasks we are waiting on.
waiting--;
// If we are finished waiting then we want to resolve our promise.
if (waiting <= 0) {
if (waiting === 0) {
_resolve(filePaths);
} else {
reject(new Error(`Expected a positive number: ${waiting}`));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q16239
|
isLastNodeRemovedFromLine
|
train
|
function isLastNodeRemovedFromLine(context, node) {
var tokens = context.ast.tokens;
var priorTokenIdx = findTokenIndex(tokens, startOf(node)) - 1;
var token = tokens[priorTokenIdx];
var line = node.loc.end.line;
// Find previous token that was not removed on the same line.
while (
priorTokenIdx >= 0 &&
token.loc.end.line === line &&
isRemovedToken(context, token)
) {
token = tokens[--priorTokenIdx];
}
// If there's no prior token (start of file), or the prior token is on another
// line, this line must be fully removed.
return !token || token.loc.end.line !== line;
}
|
javascript
|
{
"resource": ""
}
|
q16240
|
visit
|
train
|
function visit(ast, context, visitor) {
var stack;
var parent;
var keys = [];
var index = -1;
do {
index++;
if (stack && index === keys.length) {
parent = stack.parent;
keys = stack.keys;
index = stack.index;
stack = stack.prev;
} else {
var node = parent ? parent[keys[index]] : getProgram(ast);
if (node && typeof node === 'object' && (node.type || node.length)) {
if (node.type) {
var visitFn = visitor[node.type];
if (visitFn && visitFn(context, node, ast) === false) {
continue;
}
}
stack = {parent: parent, keys: keys, index: index, prev: stack};
parent = node;
keys = Object.keys(node);
index = -1;
}
}
} while (stack);
}
|
javascript
|
{
"resource": ""
}
|
q16241
|
space
|
train
|
function space(size) {
var sp = ' ';
var result = '';
for (;;) {
if ((size & 1) === 1) {
result += sp;
}
size >>>= 1;
if (size === 0) {
break;
}
sp += sp;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q16242
|
getOutputFile
|
train
|
function getOutputFile(options) {
var outFile = options.outFile;
if (!outFile || typeof outFile !== 'string' || (!options.data && !options.file)) {
return null;
}
return path.resolve(outFile);
}
|
javascript
|
{
"resource": ""
}
|
q16243
|
getSourceMap
|
train
|
function getSourceMap(options) {
var sourceMap = options.sourceMap;
if (sourceMap && typeof sourceMap !== 'string' && options.outFile) {
sourceMap = options.outFile + '.map';
}
return sourceMap && typeof sourceMap === 'string' ? path.resolve(sourceMap) : null;
}
|
javascript
|
{
"resource": ""
}
|
q16244
|
buildIncludePaths
|
train
|
function buildIncludePaths(options) {
options.includePaths = options.includePaths || [];
if (process.env.hasOwnProperty('SASS_PATH')) {
options.includePaths = options.includePaths.concat(
process.env.SASS_PATH.split(path.delimiter)
);
}
// Preserve the behaviour people have come to expect.
// This behaviour was removed from Sass in 3.4 and
// LibSass in 3.5.
options.includePaths.unshift(process.cwd());
return options.includePaths.join(path.delimiter);
}
|
javascript
|
{
"resource": ""
}
|
q16245
|
tryCallback
|
train
|
function tryCallback(callback, args) {
try {
return callback.apply(this, args);
} catch (e) {
if (typeof e === 'string') {
return new binding.types.Error(e);
} else if (e instanceof Error) {
return new binding.types.Error(e.message);
} else {
return new binding.types.Error('An unexpected error occurred');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q16246
|
getHumanEnvironment
|
train
|
function getHumanEnvironment(env) {
var binding = env.replace(/_binding\.node$/, ''),
parts = binding.split('-'),
platform = getHumanPlatform(parts[0]),
arch = getHumanArchitecture(parts[1]),
runtime = getHumanNodeVersion(parts[2]);
if (parts.length !== 3) {
return 'Unknown environment (' + binding + ')';
}
if (!platform) {
platform = 'Unsupported platform (' + parts[0] + ')';
}
if (!arch) {
arch = 'Unsupported architecture (' + parts[1] + ')';
}
if (!runtime) {
runtime = 'Unsupported runtime (' + parts[2] + ')';
}
return [
platform, arch, 'with', runtime,
].join(' ');
}
|
javascript
|
{
"resource": ""
}
|
q16247
|
isSupportedEnvironment
|
train
|
function isSupportedEnvironment(platform, arch, abi) {
return (
false !== getHumanPlatform(platform) &&
false !== getHumanArchitecture(arch) &&
false !== getHumanNodeVersion(abi)
);
}
|
javascript
|
{
"resource": ""
}
|
q16248
|
getArgument
|
train
|
function getArgument(name, args) {
var flags = args || process.argv.slice(2),
index = flags.lastIndexOf(name);
if (index === -1 || index + 1 >= flags.length) {
return null;
}
return flags[index + 1];
}
|
javascript
|
{
"resource": ""
}
|
q16249
|
getBinaryUrl
|
train
|
function getBinaryUrl() {
var site = getArgument('--sass-binary-site') ||
process.env.SASS_BINARY_SITE ||
process.env.npm_config_sass_binary_site ||
(pkg.nodeSassConfig && pkg.nodeSassConfig.binarySite) ||
'https://github.com/sass/node-sass/releases/download';
return [site, 'v' + pkg.version, getBinaryName()].join('/');
}
|
javascript
|
{
"resource": ""
}
|
q16250
|
getBinaryCachePath
|
train
|
function getBinaryCachePath() {
var i,
cachePath,
cachePathCandidates = getCachePathCandidates();
for (i = 0; i < cachePathCandidates.length; i++) {
cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version);
try {
mkdir.sync(cachePath);
return cachePath;
} catch (e) {
// Directory is not writable, try another
}
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q16251
|
getCachedBinary
|
train
|
function getCachedBinary() {
var i,
cachePath,
cacheBinary,
cachePathCandidates = getCachePathCandidates(),
binaryName = getBinaryName();
for (i = 0; i < cachePathCandidates.length; i++) {
cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version);
cacheBinary = path.join(cachePath, binaryName);
if (fs.existsSync(cacheBinary)) {
return cacheBinary;
}
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
q16252
|
getVersionInfo
|
train
|
function getVersionInfo(binding) {
return [
['node-sass', pkg.version, '(Wrapper)', '[JavaScript]'].join('\t'),
['libsass ', binding.libsassVersion(), '(Sass Compiler)', '[C/C++]'].join('\t'),
].join(eol);
}
|
javascript
|
{
"resource": ""
}
|
q16253
|
isPreviewContext
|
train
|
function isPreviewContext(context, previewContext) {
if (previewContext) {
return context === previewContext;
}
return PREVIEW_CONTEXT_KEYWORDS.some(keyword => context.includes(keyword));
}
|
javascript
|
{
"resource": ""
}
|
q16254
|
getPreviewStatus
|
train
|
function getPreviewStatus(statuses, config) {
const previewContext = config.getIn(['backend', 'preview_context']);
return statuses.find(({ context }) => {
return isPreviewContext(context, previewContext);
});
}
|
javascript
|
{
"resource": ""
}
|
q16255
|
createBlock
|
train
|
function createBlock(type, nodes, props = {}) {
if (!isArray(nodes)) {
props = nodes;
nodes = undefined;
}
const node = { object: 'block', type, ...props };
return addNodes(node, nodes);
}
|
javascript
|
{
"resource": ""
}
|
q16256
|
createInline
|
train
|
function createInline(type, props = {}, nodes) {
const node = { object: 'inline', type, ...props };
return addNodes(node, nodes);
}
|
javascript
|
{
"resource": ""
}
|
q16257
|
createText
|
train
|
function createText(value, data) {
const node = { object: 'text', data };
const leaves = isArray(value) ? value : [{ text: value }];
return { ...node, leaves };
}
|
javascript
|
{
"resource": ""
}
|
q16258
|
convertNode
|
train
|
function convertNode(node, nodes) {
switch (node.type) {
/**
* General
*
* Convert simple cases that only require a type and children, with no
* additional properties.
*/
case 'root':
case 'paragraph':
case 'listItem':
case 'blockquote':
case 'tableRow':
case 'tableCell': {
return createBlock(typeMap[node.type], nodes);
}
/**
* Shortcodes
*
* Shortcode nodes are represented as "void" blocks in the Slate AST. They
* maintain the same data as MDAST shortcode nodes. Slate void blocks must
* contain a blank text node.
*/
case 'shortcode': {
const { data } = node;
const nodes = [createText('')];
return createBlock(typeMap[node.type], nodes, { data, isVoid: true });
}
/**
* Text
*
* Text and HTML nodes are both used to render text, and should be treated
* the same. HTML is treated as text because we never want to escape or
* encode it.
*/
case 'text':
case 'html': {
return createText(node.value, node.data);
}
/**
* Inline Code
*
* Inline code nodes from an MDAST are represented in our Slate schema as
* text nodes with a "code" mark. We manually create the "leaf" containing
* the inline code value and a "code" mark, and place it in an array for use
* as a Slate text node's children array.
*/
case 'inlineCode': {
const leaf = {
text: node.value,
marks: [{ type: 'code' }],
};
return createText([leaf]);
}
/**
* Marks
*
* Marks are typically decorative sub-types that apply to text nodes. In an
* MDAST, marks are nodes that can contain other nodes. This nested
* hierarchy has to be flattened and split into distinct text nodes with
* their own set of marks.
*/
case 'strong':
case 'emphasis':
case 'delete': {
return convertMarkNode(node);
}
/**
* Headings
*
* MDAST headings use a single type with a separate "depth" property to
* indicate the heading level, while the Slate schema uses a separate node
* type for each heading level. Here we get the proper Slate node name based
* on the MDAST node depth.
*/
case 'heading': {
const depthMap = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six' };
const slateType = `heading-${depthMap[node.depth]}`;
return createBlock(slateType, nodes);
}
/**
* Code Blocks
*
* MDAST code blocks are a distinct node type with a simple text value. We
* convert that value into a nested child text node for Slate. We also carry
* over the "lang" data property if it's defined.
*/
case 'code': {
const data = { lang: node.lang };
const text = createText(node.value);
const nodes = [text];
return createBlock(typeMap[node.type], nodes, { data });
}
/**
* Lists
*
* MDAST has a single list type and an "ordered" property. We derive that
* information into the Slate schema's distinct list node types. We also
* include the "start" property, which indicates the number an ordered list
* starts at, if defined.
*/
case 'list': {
const slateType = node.ordered ? 'numbered-list' : 'bulleted-list';
const data = { start: node.start };
return createBlock(slateType, nodes, { data });
}
/**
* Breaks
*
* MDAST soft break nodes represent a trailing double space or trailing
* slash from a Markdown document. In Slate, these are simply transformed to
* line breaks within a text node.
*/
case 'break': {
const textNode = createText('\n');
return createInline('break', {}, [textNode]);
}
/**
* Thematic Breaks
*
* Thematic breaks are void nodes in the Slate schema.
*/
case 'thematicBreak': {
return createBlock(typeMap[node.type], { isVoid: true });
}
/**
* Links
*
* MDAST stores the link attributes directly on the node, while our Slate
* schema references them in the data object.
*/
case 'link': {
const { title, url, data } = node;
const newData = { ...data, title, url };
return createInline(typeMap[node.type], { data: newData }, nodes);
}
/**
* Images
*
* Identical to link nodes except for the lack of child nodes and addition
* of alt attribute data MDAST stores the link attributes directly on the
* node, while our Slate schema references them in the data object.
*/
case 'image': {
const { title, url, alt, data } = node;
const newData = { ...data, title, alt, url };
return createInline(typeMap[node.type], { isVoid: true, data: newData });
}
/**
* Tables
*
* Tables are parsed separately because they may include an "align"
* property, which should be passed to the Slate node.
*/
case 'table': {
const data = { align: node.align };
return createBlock(typeMap[node.type], nodes, { data });
}
}
}
|
javascript
|
{
"resource": ""
}
|
q16259
|
markdownToRemarkRemoveTokenizers
|
train
|
function markdownToRemarkRemoveTokenizers({ inlineTokenizers }) {
inlineTokenizers &&
inlineTokenizers.forEach(tokenizer => {
delete this.Parser.prototype.inlineTokenizers[tokenizer];
});
}
|
javascript
|
{
"resource": ""
}
|
q16260
|
remarkAllowAllText
|
train
|
function remarkAllowAllText() {
const Compiler = this.Compiler;
const visitors = Compiler.prototype.visitors;
visitors.text = node => node.value;
}
|
javascript
|
{
"resource": ""
}
|
q16261
|
getRoot
|
train
|
function getRoot() {
/**
* Return existing root if found.
*/
const existingRoot = document.getElementById(ROOT_ID);
if (existingRoot) {
return existingRoot;
}
/**
* If no existing root, create and return a new root.
*/
const newRoot = document.createElement('div');
newRoot.id = ROOT_ID;
document.body.appendChild(newRoot);
return newRoot;
}
|
javascript
|
{
"resource": ""
}
|
q16262
|
transform
|
train
|
function transform(node) {
/**
* Combine adjacent text and inline nodes before processing so they can
* share marks.
*/
const combinedChildren = node.nodes && combineTextAndInline(node.nodes);
/**
* Call `transform` recursively on child nodes, and flatten the resulting
* array.
*/
const children = !isEmpty(combinedChildren) && flatMap(combinedChildren, transform);
/**
* Run individual nodes through conversion factories.
*/
return ['text'].includes(node.object) ? convertTextNode(node) : convertNode(node, children);
}
|
javascript
|
{
"resource": ""
}
|
q16263
|
combineTextAndInline
|
train
|
function combineTextAndInline(nodes) {
return nodes.reduce((acc, node) => {
const prevNode = last(acc);
const prevNodeLeaves = get(prevNode, 'leaves');
const data = node.data || {};
/**
* If the previous node has leaves and the current node has marks in data
* (only happens when we place them on inline nodes here in the parser), or
* the current node also has leaves (because the previous node was
* originally an inline node that we've already squashed into a leaf)
* combine the current node into the previous.
*/
if (!isEmpty(prevNodeLeaves) && !isEmpty(data.marks)) {
prevNodeLeaves.push({ node, marks: data.marks });
return acc;
}
if (!isEmpty(prevNodeLeaves) && !isEmpty(node.leaves)) {
prevNode.leaves = prevNodeLeaves.concat(node.leaves);
return acc;
}
/**
* Break nodes contain a single child text node with a newline character
* for visual purposes in the editor, but Remark break nodes have no
* children, so we remove the child node here.
*/
if (node.type === 'break') {
acc.push({ object: 'inline', type: 'break' });
return acc;
}
/**
* Convert remaining inline nodes to standalone text nodes with leaves.
*/
if (node.object === 'inline') {
acc.push({ object: 'text', leaves: [{ node, marks: data.marks }] });
return acc;
}
/**
* Only remaining case is an actual text node, can be pushed as is.
*/
acc.push(node);
return acc;
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q16264
|
processCodeMark
|
train
|
function processCodeMark(markTypes) {
const isInlineCode = markTypes.includes('inlineCode');
const filteredMarkTypes = isInlineCode ? without(markTypes, 'inlineCode') : markTypes;
const textNodeType = isInlineCode ? 'inlineCode' : 'html';
return { filteredMarkTypes, textNodeType };
}
|
javascript
|
{
"resource": ""
}
|
q16265
|
convertTextNode
|
train
|
function convertTextNode(node) {
/**
* If the Slate text node has a "leaves" property, translate the Slate AST to
* a nested MDAST structure. Otherwise, just return an equivalent MDAST text
* node.
*/
if (node.leaves) {
const processedLeaves = node.leaves.map(processLeaves);
// Compensate for Slate including leading and trailing whitespace in styled text nodes, which
// cannot be represented in markdown (https://github.com/netlify/netlify-cms/issues/1448)
for (let i = 0; i < processedLeaves.length; i += 1) {
const leaf = processedLeaves[i];
if (leaf.marks.length > 0 && leaf.text && leaf.text.trim() !== leaf.text) {
const [, leadingWhitespace, trailingWhitespace] = leaf.text.match(/^(\s*).*?(\s*)$/);
// Move the leading whitespace to a separate unstyled leaf, unless the current leaf
// is preceded by another one with (at least) the same marks applied:
if (
leadingWhitespace.length > 0 &&
(i === 0 ||
!leaf.marks.every(
mark => processedLeaves[i - 1].marks && processedLeaves[i - 1].marks.includes(mark),
))
) {
processedLeaves.splice(i, 0, {
text: leadingWhitespace,
marks: [],
textNodeType: leaf.textNodeType,
});
i += 1;
leaf.text = leaf.text.replace(/^\s+/, '');
}
// Move the trailing whitespace to a separate unstyled leaf, unless the current leaf
// is followed by another one with (at least) the same marks applied:
if (
trailingWhitespace.length > 0 &&
(i === processedLeaves.length - 1 ||
!leaf.marks.every(
mark => processedLeaves[i + 1].marks && processedLeaves[i + 1].marks.includes(mark),
))
) {
processedLeaves.splice(i + 1, 0, {
text: trailingWhitespace,
marks: [],
textNodeType: leaf.textNodeType,
});
i += 1;
leaf.text = leaf.text.replace(/\s+$/, '');
}
}
}
const condensedNodes = processedLeaves.reduce(condenseNodesReducer, { nodes: [] });
return condensedNodes.nodes;
}
if (node.object === 'inline') {
return transform(node);
}
return u('html', node.text);
}
|
javascript
|
{
"resource": ""
}
|
q16266
|
processLeaves
|
train
|
function processLeaves(leaf) {
/**
* Get an array of the mark types, converted to their MDAST equivalent
* types.
*/
const { marks = [], text } = leaf;
const markTypes = marks.map(mark => markMap[mark.type]);
if (typeof leaf.text === 'string') {
/**
* Code marks must be removed from the marks array, and the presence of a
* code mark changes the text node type that should be used.
*/
const { filteredMarkTypes, textNodeType } = processCodeMark(markTypes);
return { text, marks: filteredMarkTypes, textNodeType };
}
return { node: leaf.node, marks: markTypes };
}
|
javascript
|
{
"resource": ""
}
|
q16267
|
getMarkLength
|
train
|
function getMarkLength(markType, nodes) {
let length = 0;
while (nodes[length] && nodes[length].marks.includes(markType)) {
++length;
}
return { markType, length };
}
|
javascript
|
{
"resource": ""
}
|
q16268
|
convertNode
|
train
|
function convertNode(node, children) {
switch (node.type) {
/**
* General
*
* Convert simple cases that only require a type and children, with no
* additional properties.
*/
case 'root':
case 'paragraph':
case 'quote':
case 'list-item':
case 'table':
case 'table-row':
case 'table-cell': {
return u(typeMap[node.type], children);
}
/**
* Shortcodes
*
* Shortcode nodes only exist in Slate's Raw AST if they were inserted
* via the plugin toolbar in memory, so they should always have
* shortcode data attached. The "shortcode" data property contains the
* name of the registered shortcode plugin, and the "shortcodeData" data
* property contains the data received from the shortcode plugin's
* `fromBlock` method when the shortcode node was created.
*
* Here we create a `shortcode` MDAST node that contains only the shortcode
* data.
*/
case 'shortcode': {
const { data } = node;
return u(typeMap[node.type], { data });
}
/**
* Headings
*
* Slate schemas don't usually infer basic type info from data, so each
* level of heading is a separately named type. The MDAST schema just
* has a single "heading" type with the depth stored in a "depth"
* property on the node. Here we derive the depth from the Slate node
* type - e.g., for "heading-two", we need a depth value of "2".
*/
case 'heading-one':
case 'heading-two':
case 'heading-three':
case 'heading-four':
case 'heading-five':
case 'heading-six': {
const depthMap = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6 };
const depthText = node.type.split('-')[1];
const depth = depthMap[depthText];
return u(typeMap[node.type], { depth }, children);
}
/**
* Code Blocks
*
* Code block nodes have a single text child, and may have a code language
* stored in the "lang" data property. Here we transfer both the node
* value and the "lang" data property to the new MDAST node.
*/
case 'code': {
const value = flatMap(node.nodes, child => {
return flatMap(child.leaves, 'text');
}).join('');
const { lang, ...data } = get(node, 'data', {});
return u(typeMap[node.type], { lang, data }, value);
}
/**
* Lists
*
* Our Slate schema has separate node types for ordered and unordered
* lists, but the MDAST spec uses a single type with a boolean "ordered"
* property to indicate whether the list is numbered. The MDAST spec also
* allows for a "start" property to indicate the first number used for an
* ordered list. Here we translate both values to our Slate schema.
*/
case 'numbered-list':
case 'bulleted-list': {
const ordered = node.type === 'numbered-list';
const props = { ordered, start: get(node.data, 'start') || 1 };
return u(typeMap[node.type], props, children);
}
/**
* Breaks
*
* Breaks don't have children. We parse them separately for clarity.
*/
case 'break':
case 'thematic-break': {
return u(typeMap[node.type]);
}
/**
* Links
*
* The url and title attributes of link nodes are stored in properties on
* the node for both Slate and Remark schemas.
*/
case 'link': {
const { url, title, ...data } = get(node, 'data', {});
return u(typeMap[node.type], { url, title, data }, children);
}
/**
* Images
*
* This transformation is almost identical to that of links, except for the
* lack of child nodes and addition of `alt` attribute data.
*/
case 'image': {
const { url, title, alt, ...data } = get(node, 'data', {});
return u(typeMap[node.type], { url, title, alt, data });
}
/**
* No default case is supplied because an unhandled case should never
* occur. In the event that it does, let the error throw (for now).
*/
}
}
|
javascript
|
{
"resource": ""
}
|
q16269
|
getExplicitFieldReplacement
|
train
|
function getExplicitFieldReplacement(key, data) {
if (!key.startsWith(FIELD_PREFIX)) {
return;
}
const fieldName = key.substring(FIELD_PREFIX.length);
return data.get(fieldName, '');
}
|
javascript
|
{
"resource": ""
}
|
q16270
|
isFileGroup
|
train
|
function isFileGroup(files) {
const basePatternString = `~${files.length}/nth/`;
const mapExpression = (val, idx) => new RegExp(`${basePatternString}${idx}/$`);
const expressions = Array.from({ length: files.length }, mapExpression);
return expressions.every(exp => files.some(url => exp.test(url)));
}
|
javascript
|
{
"resource": ""
}
|
q16271
|
getFileGroup
|
train
|
function getFileGroup(files) {
/**
* Capture the group id from the first file in the files array.
*/
const groupId = new RegExp(`^.+/([^/]+~${files.length})/nth/`).exec(files[0])[1];
/**
* The `openDialog` method handles the jQuery promise object returned by
* `fileFrom`, but requires the promise returned by `loadFileGroup` to provide
* the result of it's `done` method.
*/
return new Promise(resolve => uploadcare.loadFileGroup(groupId).done(group => resolve(group)));
}
|
javascript
|
{
"resource": ""
}
|
q16272
|
openDialog
|
train
|
function openDialog(files, config, handleInsert) {
uploadcare.openDialog(files, config).done(({ promise }) =>
promise().then(({ cdnUrl, count }) => {
if (config.multiple) {
const urls = Array.from({ length: count }, (val, idx) => `${cdnUrl}nth/${idx}/`);
handleInsert(urls);
} else {
handleInsert(cdnUrl);
}
}),
);
}
|
javascript
|
{
"resource": ""
}
|
q16273
|
init
|
train
|
async function init({ options = { config: {} }, handleInsert } = {}) {
const { publicKey, ...globalConfig } = options.config;
const baseConfig = { ...defaultConfig, ...globalConfig };
window.UPLOADCARE_PUBLIC_KEY = publicKey;
/**
* Register the effects tab by default because the effects tab is awesome. Can
* be disabled via config.
*/
uploadcare.registerTab('preview', uploadcareTabEffects);
return {
/**
* On show, create a new widget, cache it in the widgets object, and open.
* No hide method is provided because the widget doesn't provide it.
*/
show: ({ value, config: instanceConfig = {}, allowMultiple, imagesOnly = false } = {}) => {
const config = { ...baseConfig, imagesOnly, ...instanceConfig };
const multiple = allowMultiple === false ? false : !!config.multiple;
const resolvedConfig = { ...config, multiple };
const files = getFiles(value);
/**
* Resolve the promise only if it's ours. Only the jQuery promise objects
* from the Uploadcare library will have a `state` method.
*/
if (files && !files.state) {
return files.then(result => openDialog(result, resolvedConfig, handleInsert));
} else {
return openDialog(files, resolvedConfig, handleInsert);
}
},
/**
* Uploadcare doesn't provide a "media library" widget for viewing and
* selecting existing files, so we return `false` here so Netlify CMS only
* opens the Uploadcare widget when called from an editor control. This
* results in the "Media" button in the global nav being hidden.
*/
enableStandalone: () => false,
};
}
|
javascript
|
{
"resource": ""
}
|
q16274
|
allOnes
|
train
|
function allOnes(product) {
for (var i = 0; i < product.weights.length; i++) {
product.weights[i] = 1;
product.deltas[i] = 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q16275
|
mse
|
train
|
function mse(errors) {
var sum = 0;
for (var i = 0; i < this.constants.size; i++) {
sum += Math.pow(errors[i], 2);
}
return sum / this.constants.size;
}
|
javascript
|
{
"resource": ""
}
|
q16276
|
gaussRandom
|
train
|
function gaussRandom() {
if (gaussRandom.returnV) {
gaussRandom.returnV = false;
return gaussRandom.vVal;
}
var u = 2 * Math.random() - 1;
var v = 2 * Math.random() - 1;
var r = u * u + v * v;
if (r == 0 || r > 1) {
return gaussRandom();
}
var c = Math.sqrt(-2 * Math.log(r) / r);
gaussRandom.vVal = v * c; // cache this
gaussRandom.returnV = true;
return u * c;
}
|
javascript
|
{
"resource": ""
}
|
q16277
|
train
|
function(obj) {
console.log(`trained in ${ obj.iterations } iterations with error: ${ obj.error }`);
const result01 = net.run([0, 1]);
const result00 = net.run([0, 0]);
const result11 = net.run([1, 1]);
const result10 = net.run([1, 0]);
assert(result01[0] > 0.9);
assert(result00[0] < 0.1);
assert(result11[0] < 0.1);
assert(result10[0] > 0.9);
console.log('0 XOR 1: ', result01); // 0.987
console.log('0 XOR 0: ', result00); // 0.058
console.log('1 XOR 1: ', result11); // 0.087
console.log('1 XOR 0: ', result10); // 0.934
}
|
javascript
|
{
"resource": ""
}
|
|
q16278
|
transformAjvErrors
|
train
|
function transformAjvErrors(errors = []) {
if (errors === null) {
return [];
}
return errors.map(e => {
const { dataPath, keyword, message, params, schemaPath } = e;
let property = `${dataPath}`;
// put data in expected format
return {
name: keyword,
property,
message,
params, // specific to ajv
stack: `${property} ${message}`.trim(),
schemaPath,
};
});
}
|
javascript
|
{
"resource": ""
}
|
q16279
|
schemaRequiresTrueValue
|
train
|
function schemaRequiresTrueValue(schema) {
// Check if const is a truthy value
if (schema.const) {
return true;
}
// Check if an enum has a single value of true
if (schema.enum && schema.enum.length === 1 && schema.enum[0] === true) {
return true;
}
// If anyOf has a single value, evaluate the subschema
if (schema.anyOf && schema.anyOf.length === 1) {
return schemaRequiresTrueValue(schema.anyOf[0]);
}
// If oneOf has a single value, evaluate the subschema
if (schema.oneOf && schema.oneOf.length === 1) {
return schemaRequiresTrueValue(schema.oneOf[0]);
}
// Evaluate each subschema in allOf, to see if one of them requires a true
// value
if (schema.allOf) {
return schema.allOf.some(schemaRequiresTrueValue);
}
}
|
javascript
|
{
"resource": ""
}
|
q16280
|
DefaultArrayItem
|
train
|
function DefaultArrayItem(props) {
const btnStyle = {
flex: 1,
paddingLeft: 6,
paddingRight: 6,
fontWeight: "bold",
};
return (
<div key={props.index} className={props.className}>
<div className={props.hasToolbar ? "col-xs-9" : "col-xs-12"}>
{props.children}
</div>
{props.hasToolbar && (
<div className="col-xs-3 array-item-toolbox">
<div
className="btn-group"
style={{
display: "flex",
justifyContent: "space-around",
}}>
{(props.hasMoveUp || props.hasMoveDown) && (
<IconButton
icon="arrow-up"
className="array-item-move-up"
tabIndex="-1"
style={btnStyle}
disabled={props.disabled || props.readonly || !props.hasMoveUp}
onClick={props.onReorderClick(props.index, props.index - 1)}
/>
)}
{(props.hasMoveUp || props.hasMoveDown) && (
<IconButton
icon="arrow-down"
className="array-item-move-down"
tabIndex="-1"
style={btnStyle}
disabled={
props.disabled || props.readonly || !props.hasMoveDown
}
onClick={props.onReorderClick(props.index, props.index + 1)}
/>
)}
{props.hasRemove && (
<IconButton
type="danger"
icon="remove"
className="array-item-remove"
tabIndex="-1"
style={btnStyle}
disabled={props.disabled || props.readonly}
onClick={props.onDropIndexClick(props.index)}
/>
)}
</div>
</div>
)}
</div>
);
}
|
javascript
|
{
"resource": ""
}
|
q16281
|
processValue
|
train
|
function processValue(schema, value) {
// "enum" is a reserved word, so only "type" and "items" can be destructured
const { type, items } = schema;
if (value === "") {
return undefined;
} else if (type === "array" && items && nums.has(items.type)) {
return value.map(asNumber);
} else if (type === "boolean") {
return value === "true";
} else if (type === "number") {
return asNumber(value);
}
// If type is undefined, but an enum is present, try and infer the type from
// the enum values
if (schema.enum) {
if (schema.enum.every(x => guessType(x) === "number")) {
return asNumber(value);
} else if (schema.enum.every(x => guessType(x) === "boolean")) {
return value === "true";
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q16282
|
train
|
function (element, opts) {
var owner = this;
var hasMultipleElements = false;
if (typeof element === 'string') {
owner.element = document.querySelector(element);
hasMultipleElements = document.querySelectorAll(element).length > 1;
} else {
if (typeof element.length !== 'undefined' && element.length > 0) {
owner.element = element[0];
hasMultipleElements = element.length > 1;
} else {
owner.element = element;
}
}
if (!owner.element) {
throw new Error('[cleave.js] Please check the element');
}
if (hasMultipleElements) {
try {
// eslint-disable-next-line
console.warn('[cleave.js] Multiple input fields matched, cleave.js will only take the first one.');
} catch (e) {
// Old IE
}
}
opts.initValue = owner.element.value;
owner.properties = Cleave.DefaultProperties.assign({}, opts);
owner.init();
}
|
javascript
|
{
"resource": ""
}
|
|
q16283
|
_findFocusTd
|
train
|
function _findFocusTd($newTable, rowIndex, colIndex) {
const tableData = dataHandler.createTableData($newTable);
const newRowIndex = dataHandler.findRowMergedLastIndex(tableData, rowIndex, colIndex) + 1;
const cellElementIndex = dataHandler.findElementIndex(tableData, newRowIndex, colIndex);
return $newTable.find('tr').eq(cellElementIndex.rowIndex).find('td')[cellElementIndex.colIndex];
}
|
javascript
|
{
"resource": ""
}
|
q16284
|
_parseCell
|
train
|
function _parseCell(cell, rowIndex, colIndex) {
const $cell = $(cell);
const colspan = $cell.attr('colspan');
const rowspan = $cell.attr('rowspan');
const {nodeName} = cell;
if (nodeName !== 'TH' && nodeName !== 'TD') {
return null;
}
const cellData = {
nodeName: cell.nodeName,
colspan: colspan ? parseInt(colspan, 10) : 1,
rowspan: rowspan ? parseInt(rowspan, 10) : 1,
content: $cell.html(),
elementIndex: {
rowIndex,
colIndex
}
};
if (cell.nodeName === 'TH' && cell.align) {
cellData.align = cell.align;
}
return cellData;
}
|
javascript
|
{
"resource": ""
}
|
q16285
|
_addMergedCell
|
train
|
function _addMergedCell(base, cellData, startRowIndex, startCellIndex) {
const {
colspan,
rowspan,
nodeName
} = cellData;
const colMerged = colspan > 1;
const rowMerged = rowspan > 1;
if (!colMerged && !rowMerged) {
return;
}
const limitRowIndex = startRowIndex + rowspan;
const limitCellIndex = startCellIndex + colspan;
util.range(startRowIndex, limitRowIndex).forEach(rowIndex => {
base[rowIndex] = base[rowIndex] || [];
util.range(startCellIndex, limitCellIndex).forEach(cellIndex => {
const mergedData = {
nodeName
};
if (rowIndex === startRowIndex && cellIndex === startCellIndex) {
return;
}
if (colMerged) {
mergedData.colMergeWith = startCellIndex;
}
if (rowMerged) {
mergedData.rowMergeWith = startRowIndex;
}
base[rowIndex][cellIndex] = mergedData;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16286
|
_getHeaderAligns
|
train
|
function _getHeaderAligns(tableData) {
const [headRowData] = tableData;
return headRowData.map(cellData => {
let align;
if (util.isExisty(cellData.colMergeWith)) {
({align} = headRowData[cellData.colMergeWith]);
} else {
({align} = cellData);
}
return align;
});
}
|
javascript
|
{
"resource": ""
}
|
q16287
|
createRenderData
|
train
|
function createRenderData(tableData, cellIndexData) {
const headerAligns = _getHeaderAligns(tableData);
const renderData = cellIndexData.map(row => row.map(({rowIndex, colIndex}) => (util.extend({
align: headerAligns[colIndex]
}, tableData[rowIndex][colIndex]))));
if (tableData.className) {
renderData.className = tableData.className;
}
return renderData;
}
|
javascript
|
{
"resource": ""
}
|
q16288
|
createBasicCell
|
train
|
function createBasicCell(rowIndex, colIndex, nodeName) {
return {
nodeName: nodeName || 'TD',
colspan: 1,
rowspan: 1,
content: BASIC_CELL_CONTENT,
elementIndex: {
rowIndex,
colIndex
}
};
}
|
javascript
|
{
"resource": ""
}
|
q16289
|
findElementIndex
|
train
|
function findElementIndex(tableData, rowIndex, colIndex) {
const cellData = tableData[rowIndex][colIndex];
rowIndex = util.isExisty(cellData.rowMergeWith) ? cellData.rowMergeWith : rowIndex;
colIndex = util.isExisty(cellData.colMergeWith) ? cellData.colMergeWith : colIndex;
return tableData[rowIndex][colIndex].elementIndex;
}
|
javascript
|
{
"resource": ""
}
|
q16290
|
stuffCellsIntoIncompleteRow
|
train
|
function stuffCellsIntoIncompleteRow(tableData, limitIndex) {
tableData.forEach((rowData, rowIndex) => {
const startIndex = rowData.length;
if (startIndex) {
const [{nodeName}] = rowData;
util.range(startIndex, limitIndex).forEach(colIndex => {
rowData.push(createBasicCell(rowIndex, colIndex, nodeName));
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16291
|
addTbodyOrTheadIfNeed
|
train
|
function addTbodyOrTheadIfNeed(tableData) {
const [header] = tableData;
const cellCount = header.length;
let added = true;
if (!cellCount && tableData[1]) {
util.range(0, tableData[1].length).forEach(colIndex => {
header.push(createBasicCell(0, colIndex, 'TH'));
});
} else if (tableData[0][0].nodeName !== 'TH') {
const newHeader = util.range(0, cellCount).map(colIndex => createBasicCell(0, colIndex, 'TH'));
[].concat(...tableData).forEach(cellData => {
if (cellData.elementIndex) {
cellData.elementIndex.rowIndex += 1;
}
});
tableData.unshift(newHeader);
} else if (tableData.length === 1) {
const newRow = util.range(0, cellCount).map(colIndex => (
createBasicCell(1, colIndex, 'TD')
));
tableData.push(newRow);
} else {
added = false;
}
return added;
}
|
javascript
|
{
"resource": ""
}
|
q16292
|
styleItalic
|
train
|
function styleItalic(sq) {
if (sq.hasFormat('i') || sq.hasFormat('em')) {
sq.changeFormat(null, {tag: 'i'});
} else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) {
if (sq.hasFormat('code')) {
sq.changeFormat(null, {tag: 'code'});
}
sq.italic();
}
}
|
javascript
|
{
"resource": ""
}
|
q16293
|
_pickContent
|
train
|
function _pickContent(targetRows, startColIndex, endColIndex) {
const limitColIndex = endColIndex + 1;
const cells = [].concat(...targetRows.map(rowData => rowData.slice(startColIndex, limitColIndex)));
const foundCellData = cells.filter(({content}) => content && content !== BASIC_CELL_CONTENT);
return foundCellData.length ? foundCellData[0].content : BASIC_CELL_CONTENT;
}
|
javascript
|
{
"resource": ""
}
|
q16294
|
_initCellData
|
train
|
function _initCellData(targetRows, startColIndex, endColIndex) {
const limitColIndex = endColIndex + 1;
const targetCells = targetRows.map(rowData => rowData.slice(startColIndex, limitColIndex));
[].concat(...targetCells).slice(1).forEach(cellData => {
const {nodeName} = cellData;
util.forEach(cellData, (value, name) => (delete cellData[name]));
cellData.nodeName = nodeName;
});
}
|
javascript
|
{
"resource": ""
}
|
q16295
|
_updateRowMergeWith
|
train
|
function _updateRowMergeWith(targetRows, startColIndex, endColIndex, rowMergeWith) {
const limitColIndex = endColIndex + 1;
targetRows.forEach(rowData => {
rowData.slice(startColIndex, limitColIndex).forEach(cellData => {
cellData.rowMergeWith = rowMergeWith;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16296
|
_updateColMergeWith
|
train
|
function _updateColMergeWith(targetRows, startColIndex, endColIndex, colMergeWith) {
const limitColIndex = endColIndex + 1;
targetRows.forEach(rowData => {
rowData.slice(startColIndex, limitColIndex).forEach(cellData => {
cellData.colMergeWith = colMergeWith;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16297
|
focusToFirstTd
|
train
|
function focusToFirstTd(sq, range, $tr, tableMgr) {
const nextFocusCell = $tr.find('td').get(0);
range.setStart(nextFocusCell, 0);
range.collapse(true);
tableMgr.setLastCellNode(nextFocusCell);
sq.setSelection(range);
}
|
javascript
|
{
"resource": ""
}
|
q16298
|
getSelectedRows
|
train
|
function getSelectedRows(firstSelectedCell, rangeInformation, $table) {
const tbodyRowLength = $table.find('tbody tr').length;
const isStartContainerInThead = $(firstSelectedCell).parents('thead').length;
let startRowIndex = rangeInformation.from.row;
let endRowIndex = rangeInformation.to.row;
if (isStartContainerInThead) {
startRowIndex += 1;
}
const isWholeTbodySelected = (startRowIndex === 1 || isStartContainerInThead) && endRowIndex === tbodyRowLength;
if (isWholeTbodySelected) {
endRowIndex -= 1;
}
return $table.find('tr').slice(startRowIndex, endRowIndex + 1);
}
|
javascript
|
{
"resource": ""
}
|
q16299
|
_changeWysiwygManagers
|
train
|
function _changeWysiwygManagers(wwComponentManager) {
wwComponentManager.removeManager('table');
wwComponentManager.removeManager('tableSelection');
wwComponentManager.addManager(WwMergedTableManager);
wwComponentManager.addManager(WwMergedTableSelectionManager);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.