_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q18400
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.SENSING_CURRENT,
"args0": [
{
"type": "field_dropdown",
"name": "CURRENTMENU",
"options": [
[Blockly.Msg.SENSING_CURRENT_YEAR, 'YEAR'],
[Blockly.Msg.SENSING_CURRENT_MONTH, 'MONTH'],
[Blockly.Msg.SENSING_CURRENT_DATE, 'DATE'],
[Blockly.Msg.SENSING_CURRENT_DAYOFWEEK, 'DAYOFWEEK'],
[Blockly.Msg.SENSING_CURRENT_HOUR, 'HOUR'],
[Blockly.Msg.SENSING_CURRENT_MINUTE, 'MINUTE'],
[Blockly.Msg.SENSING_CURRENT_SECOND, 'SECOND']
]
}
],
"category": Blockly.Categories.sensing,
"checkboxInFlyout": true,
"extensions": ["colours_sensing", "output_number"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18401
|
train
|
function() {
this.jsonInit({
"message0": "%1",
"args0": [
{
"type": "field_dropdown",
"name": "SOUND_MENU",
"options": [
['1', '0'],
['2', '1'],
['3', '2'],
['4', '3'],
['5', '4'],
['6', '5'],
['7', '6'],
['8', '7'],
['9', '8'],
['10', '9'],
['call a function', function() {
window.alert('function called!');}
]
]
}
],
"colour": Blockly.Colours.sounds.secondary,
"colourSecondary": Blockly.Colours.sounds.secondary,
"colourTertiary": Blockly.Colours.sounds.tertiary,
"extensions": ["output_string"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18402
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.SOUND_SETEFFECTO,
"args0": [
{
"type": "field_dropdown",
"name": "EFFECT",
"options": [
[Blockly.Msg.SOUND_EFFECTS_PITCH, 'PITCH'],
[Blockly.Msg.SOUND_EFFECTS_PAN, 'PAN']
]
},
{
"type": "input_value",
"name": "VALUE"
}
],
"category": Blockly.Categories.sound,
"extensions": ["colours_sounds", "shape_statement"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18403
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.SOUND_CHANGEEFFECTBY,
"args0": [
{
"type": "field_dropdown",
"name": "EFFECT",
"options": [
[Blockly.Msg.SOUND_EFFECTS_PITCH, 'PITCH'],
[Blockly.Msg.SOUND_EFFECTS_PAN, 'PAN']
]
},
{
"type": "input_value",
"name": "VALUE"
}
],
"category": Blockly.Categories.sound,
"extensions": ["colours_sounds", "shape_statement"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18404
|
train
|
function (str) {
str = str.split('Blockly.Msg.')[1].split(' ');
return {
key: str[0],
value: str
.splice(2, str.length)
.join(' ')
.slice(1, -2) // strip off initial ', and ending ';
.replace(/\\'/g, "'")
};
}
|
javascript
|
{
"resource": ""
}
|
|
q18405
|
train
|
function() {
this.jsonInit({
"type": "control_if_else",
"message0": Blockly.Msg.CONTROL_IF,
"message1": "%1",
"message2": Blockly.Msg.CONTROL_ELSE,
"message3": "%1",
"args0": [
{
"type": "input_value",
"name": "CONDITION",
"check": "Boolean"
}
],
"args1": [
{
"type": "input_statement",
"name": "SUBSTACK"
}
],
"args3": [
{
"type": "input_statement",
"name": "SUBSTACK2"
}
],
"category": Blockly.Categories.control,
"extensions": ["colours_control", "shape_statement"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18406
|
train
|
function() {
var ALL_SCRIPTS = 'all';
var THIS_SCRIPT = 'this script';
var OTHER_SCRIPTS = 'other scripts in sprite';
var stopDropdown = new Blockly.FieldDropdown(function() {
if (this.sourceBlock_ &&
this.sourceBlock_.nextConnection &&
this.sourceBlock_.nextConnection.isConnected()) {
return [
[Blockly.Msg.CONTROL_STOP_OTHER, OTHER_SCRIPTS]
];
}
return [[Blockly.Msg.CONTROL_STOP_ALL, ALL_SCRIPTS],
[Blockly.Msg.CONTROL_STOP_THIS, THIS_SCRIPT],
[Blockly.Msg.CONTROL_STOP_OTHER, OTHER_SCRIPTS]
];
}, function(option) {
// Create an event group to keep field value and mutator in sync
// Return null at the end because setValue is called here already.
Blockly.Events.setGroup(true);
var oldMutation = Blockly.Xml.domToText(this.sourceBlock_.mutationToDom());
this.sourceBlock_.setNextStatement(option == OTHER_SCRIPTS);
var newMutation = Blockly.Xml.domToText(this.sourceBlock_.mutationToDom());
Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,
'mutation', null, oldMutation, newMutation));
this.setValue(option);
Blockly.Events.setGroup(false);
return null;
});
this.appendDummyInput()
.appendField(Blockly.Msg.CONTROL_STOP)
.appendField(stopDropdown, 'STOP_OPTION');
this.setCategory(Blockly.Categories.control);
this.setColour(Blockly.Colours.control.primary,
Blockly.Colours.control.secondary,
Blockly.Colours.control.tertiary
);
this.setPreviousStatement(true);
}
|
javascript
|
{
"resource": ""
}
|
|
q18407
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.CONTROL_REPEATUNTIL,
"message1": "%1",
"message2": "%1",
"lastDummyAlign2": "RIGHT",
"args0": [
{
"type": "input_value",
"name": "CONDITION",
"check": "Boolean"
}
],
"args1": [
{
"type": "input_statement",
"name": "SUBSTACK"
}
],
"args2": [
{
"type": "field_image",
"src": Blockly.mainWorkspace.options.pathToMedia + "repeat.svg",
"width": 24,
"height": 24,
"alt": "*",
"flip_rtl": true
}
],
"category": Blockly.Categories.control,
"extensions": ["colours_control", "shape_statement"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18408
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.DATA_SHOWVARIABLE,
"args0": [
{
"type": "field_variable",
"name": "VARIABLE"
}
],
"previousStatement": null,
"nextStatement": null,
"category": Blockly.Categories.data,
"colour": Blockly.Colours.data.primary,
"colourSecondary": Blockly.Colours.data.secondary,
"colourTertiary": Blockly.Colours.data.tertiary
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18409
|
train
|
function() {
this.jsonInit({
"message0": "%1",
"args0": [
{
"type": "field_numberdropdown",
"name": "INDEX",
"value": "1",
"min": 1,
"precision": 1,
"options": [
["1", "1"],
[Blockly.Msg.DATA_INDEX_LAST, "last"],
[Blockly.Msg.DATA_INDEX_ALL, "all"]
]
}
],
"category": Blockly.Categories.data,
"extensions": ["colours_textfield", "output_string"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18410
|
train
|
function() {
this.jsonInit({
"message0": "%1",
"args0": [
{
"type": "field_numberdropdown",
"name": "INDEX",
"value": "1",
"min": 1,
"precision": 1,
"options": [
["1", "1"],
[Blockly.Msg.DATA_INDEX_LAST, "last"],
[Blockly.Msg.DATA_INDEX_RANDOM, "random"]
]
}
],
"category": Blockly.Categories.data,
"extensions": ["colours_textfield", "output_string"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18411
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.DATA_ITEMOFLIST,
"args0": [
{
"type": "input_value",
"name": "INDEX"
},
{
"type": "field_variable",
"name": "LIST",
"variableTypes": [Blockly.LIST_VARIABLE_TYPE]
}
],
"output": null,
"category": Blockly.Categories.dataLists,
"extensions": ["colours_data_lists"],
"outputShape": Blockly.OUTPUT_SHAPE_ROUND
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18412
|
train
|
function(options) {
var fieldName = 'VARIABLE';
if (this.isCollapsed()) {
return;
}
var currentVarName = this.getField(fieldName).text_;
if (!this.isInFlyout) {
var variablesList = this.workspace.getVariablesOfType('');
variablesList.sort(function(a, b) {
return Blockly.scratchBlocksUtils.compareStrings(a.name, b.name);
});
for (var i = 0; i < variablesList.length; i++) {
var varName = variablesList[i].name;
if (varName == currentVarName) continue;
var option = {enabled: true};
option.text = varName;
option.callback =
Blockly.Constants.Data.VARIABLE_OPTION_CALLBACK_FACTORY(this,
variablesList[i].getId(), fieldName);
options.push(option);
}
} else {
var renameOption = {
text: Blockly.Msg.RENAME_VARIABLE,
enabled: true,
callback: Blockly.Constants.Data.RENAME_OPTION_CALLBACK_FACTORY(this,
fieldName)
};
var deleteOption = {
text: Blockly.Msg.DELETE_VARIABLE.replace('%1', currentVarName),
enabled: true,
callback: Blockly.Constants.Data.DELETE_OPTION_CALLBACK_FACTORY(this,
fieldName)
};
options.push(renameOption);
options.push(deleteOption);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q18413
|
train
|
function(options) {
var fieldName = 'LIST';
if (this.isCollapsed()) {
return;
}
var currentVarName = this.getField(fieldName).text_;
if (!this.isInFlyout) {
var variablesList = this.workspace.getVariablesOfType('list');
for (var i = 0; i < variablesList.length; i++) {
var varName = variablesList[i].name;
if (varName == currentVarName) continue;
var option = {enabled: true};
option.text = varName;
option.callback =
Blockly.Constants.Data.VARIABLE_OPTION_CALLBACK_FACTORY(this,
variablesList[i].getId(), fieldName);
options.push(option);
}
} else {
var renameOption = {
text: Blockly.Msg.RENAME_LIST,
enabled: true,
callback: Blockly.Constants.Data.RENAME_OPTION_CALLBACK_FACTORY(this,
fieldName)
};
var deleteOption = {
text: Blockly.Msg.DELETE_LIST.replace('%1', currentVarName),
enabled: true,
callback: Blockly.Constants.Data.DELETE_OPTION_CALLBACK_FACTORY(this,
fieldName)
};
options.push(renameOption);
options.push(deleteOption);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q18414
|
checkConnection_
|
train
|
function checkConnection_(yIndex) {
var dx = currentX - db[yIndex].x_;
var dy = currentY - db[yIndex].y_;
var r = Math.sqrt(dx * dx + dy * dy);
if (r <= maxRadius) {
neighbours.push(db[yIndex]);
}
return dy < maxRadius;
}
|
javascript
|
{
"resource": ""
}
|
q18415
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.MOTION_TURNRIGHT,
"args0": [
{
"type": "field_image",
"src": Blockly.mainWorkspace.options.pathToMedia + "rotate-right.svg",
"width": 24,
"height": 24
},
{
"type": "input_value",
"name": "DEGREES"
}
],
"category": Blockly.Categories.motion,
"extensions": ["colours_motion", "shape_statement"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18416
|
train
|
function() {
this.jsonInit({
"message0": "%1",
"args0": [
{
"type": "field_dropdown",
"name": "TOWARDS",
"options": [
[Blockly.Msg.MOTION_POINTTOWARDS_POINTER, '_mouse_'],
[Blockly.Msg.MOTION_POINTTOWARDS_RANDOM, '_random_']
]
}
],
"colour": Blockly.Colours.motion.secondary,
"colourSecondary": Blockly.Colours.motion.secondary,
"colourTertiary": Blockly.Colours.motion.tertiary,
"extensions": ["output_string"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18417
|
train
|
function() {
this.jsonInit({
"message0": "%1",
"args0": [
{
"type": "field_dropdown",
"name": "TO",
"options": [
[Blockly.Msg.MOTION_GOTO_POINTER, '_mouse_'],
[Blockly.Msg.MOTION_GOTO_RANDOM, '_random_']
]
}
],
"colour": Blockly.Colours.motion.secondary,
"colourSecondary": Blockly.Colours.motion.secondary,
"colourTertiary": Blockly.Colours.motion.tertiary,
"extensions": ["output_string"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18418
|
train
|
function() {
this.jsonInit({
"message0": "%1",
"args0": [
{
"type": "field_dropdown",
"name": "TO",
"options": [
[Blockly.Msg.MOTION_GLIDETO_POINTER, '_mouse_'],
[Blockly.Msg.MOTION_GLIDETO_RANDOM, '_random_']
]
}
],
"colour": Blockly.Colours.motion.secondary,
"colourSecondary": Blockly.Colours.motion.secondary,
"colourTertiary": Blockly.Colours.motion.tertiary,
"extensions": ["output_string"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18419
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.MOTION_SETROTATIONSTYLE,
"args0": [
{
"type": "field_dropdown",
"name": "STYLE",
"options": [
[Blockly.Msg.MOTION_SETROTATIONSTYLE_LEFTRIGHT, 'left-right'],
[Blockly.Msg.MOTION_SETROTATIONSTYLE_DONTROTATE, 'don\'t rotate'],
[Blockly.Msg.MOTION_SETROTATIONSTYLE_ALLAROUND, 'all around']
]
}
],
"category": Blockly.Categories.motion,
"extensions": ["colours_motion", "shape_statement"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18420
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.MOTION_ALIGNSCENE,
"args0": [
{
"type": "field_dropdown",
"name": "ALIGNMENT",
"options": [
[Blockly.Msg.MOTION_ALIGNSCENE_BOTTOMLEFT, 'bottom-left'],
[Blockly.Msg.MOTION_ALIGNSCENE_BOTTOMRIGHT, 'bottom-right'],
[Blockly.Msg.MOTION_ALIGNSCENE_MIDDLE, 'middle'],
[Blockly.Msg.MOTION_ALIGNSCENE_TOPLEFT, 'top-left'],
[Blockly.Msg.MOTION_ALIGNSCENE_TOPRIGHT, 'top-right']
]
}
],
"category": Blockly.Categories.motion,
"extensions": ["colours_motion", "shape_statement"]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q18421
|
validateStartEnd
|
train
|
function validateStartEnd(start, end) {
if (!start || !start.isValid) {
return new Invalid("missing or invalid start");
} else if (!end || !end.isValid) {
return new Invalid("missing or invalid end");
} else if (end < start) {
return new Invalid(
"end before start",
`The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`
);
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q18422
|
clone
|
train
|
function clone(dur, alts, clear = false) {
// deep merge for vals
const conf = {
values: clear ? alts.values : Object.assign({}, dur.values, alts.values || {}),
loc: dur.loc.clone(alts.loc),
conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy
};
return new Duration(conf);
}
|
javascript
|
{
"resource": ""
}
|
q18423
|
possiblyCachedWeekData
|
train
|
function possiblyCachedWeekData(dt) {
if (dt.weekData === null) {
dt.weekData = gregorianToWeek(dt.c);
}
return dt.weekData;
}
|
javascript
|
{
"resource": ""
}
|
q18424
|
clone
|
train
|
function clone(inst, alts) {
const current = {
ts: inst.ts,
zone: inst.zone,
c: inst.c,
o: inst.o,
loc: inst.loc,
invalid: inst.invalid
};
return new DateTime(Object.assign({}, current, alts, { old: current }));
}
|
javascript
|
{
"resource": ""
}
|
q18425
|
tsToObj
|
train
|
function tsToObj(ts, offset) {
ts += offset * 60 * 1000;
const d = new Date(ts);
return {
year: d.getUTCFullYear(),
month: d.getUTCMonth() + 1,
day: d.getUTCDate(),
hour: d.getUTCHours(),
minute: d.getUTCMinutes(),
second: d.getUTCSeconds(),
millisecond: d.getUTCMilliseconds()
};
}
|
javascript
|
{
"resource": ""
}
|
q18426
|
adjustTime
|
train
|
function adjustTime(inst, dur) {
const oPre = inst.o,
year = inst.c.year + dur.years,
month = inst.c.month + dur.months + dur.quarters * 3,
c = Object.assign({}, inst.c, {
year,
month,
day: Math.min(inst.c.day, daysInMonth(year, month)) + dur.days + dur.weeks * 7
}),
millisToAdd = Duration.fromObject({
hours: dur.hours,
minutes: dur.minutes,
seconds: dur.seconds,
milliseconds: dur.milliseconds
}).as("milliseconds"),
localTS = objToLocalTS(c);
let [ts, o] = fixOffset(localTS, oPre, inst.zone);
if (millisToAdd !== 0) {
ts += millisToAdd;
// that could have changed the offset by going over a DST, but we want to keep the ts the same
o = inst.zone.offset(ts);
}
return { ts, o };
}
|
javascript
|
{
"resource": ""
}
|
q18427
|
parseDataToDateTime
|
train
|
function parseDataToDateTime(parsed, parsedZone, opts, format, text) {
const { setZone, zone } = opts;
if (parsed && Object.keys(parsed).length !== 0) {
const interpretationZone = parsedZone || zone,
inst = DateTime.fromObject(
Object.assign(parsed, opts, {
zone: interpretationZone,
// setZone is a valid option in the calling methods, but not in fromObject
setZone: undefined
})
);
return setZone ? inst : inst.setZone(zone);
} else {
return DateTime.invalid(
new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)
);
}
}
|
javascript
|
{
"resource": ""
}
|
q18428
|
normalizeUnit
|
train
|
function normalizeUnit(unit) {
const normalized = {
year: "year",
years: "year",
month: "month",
months: "month",
day: "day",
days: "day",
hour: "hour",
hours: "hour",
minute: "minute",
minutes: "minute",
second: "second",
seconds: "second",
millisecond: "millisecond",
milliseconds: "millisecond",
weekday: "weekday",
weekdays: "weekday",
weeknumber: "weekNumber",
weeksnumber: "weekNumber",
weeknumbers: "weekNumber",
weekyear: "weekYear",
weekyears: "weekYear",
ordinal: "ordinal"
}[unit.toLowerCase()];
if (!normalized) throw new InvalidUnitError(unit);
return normalized;
}
|
javascript
|
{
"resource": ""
}
|
q18429
|
execFile
|
train
|
function execFile(cmd, args, opts) {
const deferred = Q.defer();
childProcess.execFile(cmd, args, opts, function(err, stdout, stderr) {
if (err) {
console.error("Error executing " + cmd + " " + args.join(" "));
console.error(stdout + stderr);
err.stdout = stdout;
err.stderr = stderr;
deferred.reject(err);
} else {
deferred.resolve(stdout);
}
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q18430
|
readPNG
|
train
|
function readPNG(file) {
const deferred = Q.defer();
const onerror = deferred.reject.bind(deferred);
const stream = fs.createReadStream(file);
stream.on("error", onerror);
pngparse.parseStream(stream, function(err, image) {
if (err) {
console.log("Failed to load " + file);
onerror(err);
return;
}
deferred.resolve(image);
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q18431
|
fftImage
|
train
|
function fftImage(image) {
const real = createMatrix();
const imag = createMatrix();
let idx = 0;
const nchan = image.channels;
const alphachan = 1 - (nchan % 2);
const colorchan = nchan - alphachan;
for (let y = 0; y < image.height; ++y) {
for (let x = 0; x < image.width; ++x) {
let v = 0;
for (let c = 0; c < colorchan; ++c) {
v += 255 - image.data[idx++];
}
for (let c = 0; c < alphachan; ++c) {
v += image.data[idx++];
}
real.set(y, x, v);
}
}
fft(1, real, imag);
return {
real: real,
imag: imag,
width: image.width,
height: image.height,
};
}
|
javascript
|
{
"resource": ""
}
|
q18432
|
createConfig
|
train
|
function createConfig(target /*: Target */, dev /*: boolean */,
minimize /*: boolean */) /*: Object */ {
const cssLoaders /*: Array<Object> */ = [{loader: 'css-loader'}];
if (minimize) {
cssLoaders[0].options = {importLoaders: 1};
cssLoaders.push({
loader: 'postcss-loader',
options: {plugins: [require('cssnano')()]},
});
}
const lessOptions = {modifyVars: {
version: `"${version}"`,
}};
// use only necessary fonts, overridable by environment variables
let isCovered = false;
for (const font of fonts) {
const override = process.env[`USE_${font.toUpperCase()}`];
const useFont = override === "true" || override !== "false" && !isCovered;
lessOptions.modifyVars[`use-${font}`] = useFont;
const support = caniuse.feature(caniuse.features[font]).stats;
isCovered = isCovered || useFont && browserslist.every(browser => {
const [name, version] = browser.split(' ');
return !support[name] || support[name][version] === 'y';
});
}
return {
mode: dev ? 'development' : 'production',
context: __dirname,
entry: {
[target.name]: target.entry,
},
output: {
filename: minimize ? '[name].min.js' : '[name].js',
library: target.library,
libraryTarget: 'umd',
libraryExport: 'default',
// Enable output modules to be used in browser or Node.
// See: https://github.com/webpack/webpack/issues/6522
globalObject: "(typeof self !== 'undefined' ? self : this)",
path: path.resolve(__dirname, 'dist'),
publicPath: dev ? '/' : '',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.css$/,
use: [
dev ? 'style-loader' : MiniCssExtractPlugin.loader,
...cssLoaders,
],
},
{
test: /\.less$/,
use: [
dev ? 'style-loader' : MiniCssExtractPlugin.loader,
...cssLoaders,
{
loader: 'less-loader',
options: lessOptions,
},
],
},
{
test: /\.(ttf|woff|woff2)$/,
use: [{
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]',
},
}],
},
],
},
externals: 'katex',
plugins: [
!dev && new MiniCssExtractPlugin({
filename: minimize ? '[name].min.css' : '[name].css',
}),
].filter(Boolean),
devtool: dev && 'inline-source-map',
optimization: {
minimize,
minimizer: [
new TerserPlugin({
terserOptions: {
output: {
ascii_only: true,
},
},
}),
],
},
performance: {
hints: false,
},
};
}
|
javascript
|
{
"resource": ""
}
|
q18433
|
train
|
function (tokens, stateMachine) {
// Recreate the argument string from KaTeX's array of tokens.
var str = "";
var expectedLoc = tokens[tokens.length - 1].loc.start
for (var i = tokens.length - 1; i >= 0; i--) {
if(tokens[i].loc.start > expectedLoc) {
// context.consumeArgs has eaten a space.
str += " ";
expectedLoc = tokens[i].loc.start;
}
str += tokens[i].text;
expectedLoc += tokens[i].text.length;
}
var tex = texify.go(mhchemParser.go(str, stateMachine));
return tex;
}
|
javascript
|
{
"resource": ""
}
|
|
q18434
|
execFile
|
train
|
function execFile(cmd, args, opts) {
return new Promise(function(resolve, reject) {
childProcess.execFile(cmd, args, opts, function(err, stdout, stderr) {
if (err) {
console.error("Error executing " + cmd + " " + args.join(" "));
console.error(stdout + stderr);
err.stdout = stdout;
err.stderr = stderr;
reject(err);
} else {
resolve(stdout);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q18435
|
getNormalizedPrimitive2D
|
train
|
function getNormalizedPrimitive2D ({ positions, cells, normals, uvs }, opt = {}) {
// Default to assuming the positions are a unit circle/box/etc
normals = normals ? expandVectorList(normals) : positions.map(p => vec3.normalize([], expandVector(p)));
// Planar UV across bounding box of mesh
uvs = uvs || get2DUV(positions);
// Assume 2D primitives are centered in -1..1 space, recenter to 0..1
positions = opt.center ? recenter(positions) : positions;
// Expand to 3D
positions = expandVectorList(positions);
return {
positions,
uvs,
normals,
cells
};
}
|
javascript
|
{
"resource": ""
}
|
q18436
|
getNormalizedPrimitive3D
|
train
|
function getNormalizedPrimitive3D ({ positions, cells, normals, uvs }, opt = {}) {
return {
positions,
uvs,
normals,
cells
};
}
|
javascript
|
{
"resource": ""
}
|
q18437
|
train
|
function(attributeName, skip) {
var skipDequantization = true;
if (typeof skip !== 'undefined')
skipDequantization = skip;
this.getAttributeOptions(attributeName).skipDequantization =
skipDequantization;
}
|
javascript
|
{
"resource": ""
}
|
|
q18438
|
initSymbols
|
train
|
function initSymbols() {
var i;
var symlen = AMsymbols.length;
for (i=0; i<symlen; i++) {
if (AMsymbols[i].tex) {
AMsymbols.push({input:AMsymbols[i].tex,
tag:AMsymbols[i].tag, output:AMsymbols[i].output, ttype:AMsymbols[i].ttype,
acc:(AMsymbols[i].acc||false)});
}
}
refreshSymbols();
}
|
javascript
|
{
"resource": ""
}
|
q18439
|
cpTypes
|
train
|
function cpTypes(typeAsset) {
const {dir, base} = path.parse(typeAsset);
let destDir = dir.split('build/types/')[1];
destDir = destDir.split('/');
destDir.splice(2, 0, 'dist');
destDir = `${destDir.join('/')}/${base}`;
addTsIgnore(typeAsset);
return cpFile(typeAsset, destDir)
.then(() => console.log(`cp ${typeAsset} -> ${destDir}`));
}
|
javascript
|
{
"resource": ""
}
|
q18440
|
templateParametersGenerator
|
train
|
function templateParametersGenerator (compilation, assets, assetTags, options) {
const xhtml = options.xhtml;
assetTags.headTags.toString = function () {
return this.map((assetTagObject) => htmlTagObjectToString(assetTagObject, xhtml)).join('');
};
assetTags.bodyTags.toString = function () {
return this.map((assetTagObject) => htmlTagObjectToString(assetTagObject, xhtml)).join('');
};
return {
compilation: compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
tags: assetTags,
files: assets,
options: options
}
};
}
|
javascript
|
{
"resource": ""
}
|
q18441
|
createHtmlTagObject
|
train
|
function createHtmlTagObject (tagName, attributes, innerHTML) {
return {
tagName: tagName,
voidTag: voidTags.indexOf(tagName) !== -1,
attributes: attributes || {},
innerHTML: innerHTML
};
}
|
javascript
|
{
"resource": ""
}
|
q18442
|
extractHelperFilesFromCompilation
|
train
|
function extractHelperFilesFromCompilation (mainCompilation, childCompilation, filename, childEntryChunks) {
const helperAssetNames = childEntryChunks.map((entryChunk, index) => {
return mainCompilation.mainTemplate.hooks.assetPath.call(filename, {
hash: childCompilation.hash,
chunk: entryChunk,
name: `HtmlWebpackPlugin_${index}`
});
});
helperAssetNames.forEach((helperFileName) => {
delete mainCompilation.assets[helperFileName];
});
const helperContents = helperAssetNames.map((helperFileName) => {
return childCompilation.assets[helperFileName].source();
});
return helperContents;
}
|
javascript
|
{
"resource": ""
}
|
q18443
|
getChildCompiler
|
train
|
function getChildCompiler (mainCompiler) {
const cachedChildCompiler = childCompilerCache.get(mainCompiler);
if (cachedChildCompiler) {
return cachedChildCompiler;
}
const newCompiler = new HtmlWebpackChildCompiler();
childCompilerCache.set(mainCompiler, newCompiler);
return newCompiler;
}
|
javascript
|
{
"resource": ""
}
|
q18444
|
clearCache
|
train
|
function clearCache (mainCompiler) {
const childCompiler = getChildCompiler(mainCompiler);
// If this childCompiler was already used
// remove the entire childCompiler from the cache
if (childCompiler.isCompiling() || childCompiler.didCompile()) {
childCompilerCache.delete(mainCompiler);
}
}
|
javascript
|
{
"resource": ""
}
|
q18445
|
addTemplateToCompiler
|
train
|
function addTemplateToCompiler (mainCompiler, templatePath) {
const childCompiler = getChildCompiler(mainCompiler);
const isNew = childCompiler.addTemplate(templatePath);
if (isNew) {
clearCache(mainCompiler);
}
}
|
javascript
|
{
"resource": ""
}
|
q18446
|
compileTemplate
|
train
|
function compileTemplate (templatePath, outputFilename, mainCompilation) {
const childCompiler = getChildCompiler(mainCompilation.compiler);
return childCompiler.compileTemplates(mainCompilation).then((compiledTemplates) => {
if (!compiledTemplates[templatePath]) console.log(Object.keys(compiledTemplates), templatePath);
const compiledTemplate = compiledTemplates[templatePath];
// Replace [hash] placeholders in filename
const outputName = mainCompilation.mainTemplate.hooks.assetPath.call(outputFilename, {
hash: compiledTemplate.hash,
chunk: compiledTemplate.entry
});
return {
// Hash of the template entry point
hash: compiledTemplate.hash,
// Output name
outputName: outputName,
// Compiled code
content: compiledTemplate.content
};
});
}
|
javascript
|
{
"resource": ""
}
|
q18447
|
hasOutDatedTemplateCache
|
train
|
function hasOutDatedTemplateCache (mainCompilation) {
const childCompiler = getChildCompiler(mainCompilation.compiler);
/**
* @type {WeakMap<HtmlWebpackChildCompiler, boolean>|undefined}
*/
let hasOutdatedChildCompilerDependenciesMap = hasOutdatedCompilationDependenciesMap.get(mainCompilation);
// Create map for childCompiler if none exist
if (!hasOutdatedChildCompilerDependenciesMap) {
hasOutdatedChildCompilerDependenciesMap = new WeakMap();
hasOutdatedCompilationDependenciesMap.set(mainCompilation, hasOutdatedChildCompilerDependenciesMap);
}
// Try to get the `checkChildCompilerCache` result from cache
let isOutdated = hasOutdatedChildCompilerDependenciesMap.get(childCompiler);
if (isOutdated !== undefined) {
return isOutdated;
}
// If `checkChildCompilerCache` has never been called for the given
// `mainCompilation` and `childCompiler` combination call it:
isOutdated = isChildCompilerCacheOutdated(mainCompilation, childCompiler);
hasOutdatedChildCompilerDependenciesMap.set(childCompiler, isOutdated);
return isOutdated;
}
|
javascript
|
{
"resource": ""
}
|
q18448
|
isChildCompilerCacheOutdated
|
train
|
function isChildCompilerCacheOutdated (mainCompilation, childCompiler) {
// If the compilation was never run there is no invalid cache
if (!childCompiler.compilationStartedTimestamp) {
return false;
}
// Check if any dependent file was changed after the last compilation
const fileTimestamps = mainCompilation.fileTimestamps;
const isCacheOutOfDate = childCompiler.fileDependencies.some((fileDependency) => {
const timestamp = fileTimestamps.get(fileDependency);
// If the timestamp is not known the file is new
// If the timestamp is larger then the file has changed
// Otherwise the file is still the same
return !timestamp || timestamp > childCompiler.compilationStartedTimestamp;
});
return isCacheOutOfDate;
}
|
javascript
|
{
"resource": ""
}
|
q18449
|
getHtmlWebpackPluginHooks
|
train
|
function getHtmlWebpackPluginHooks (compilation) {
let hooks = htmlWebpackPluginHooksMap.get(compilation);
// Setup the hooks only once
if (hooks === undefined) {
hooks = createHtmlWebpackPluginHooks();
htmlWebpackPluginHooksMap.set(compilation, hooks);
}
return hooks;
}
|
javascript
|
{
"resource": ""
}
|
q18450
|
createHtmlWebpackPluginHooks
|
train
|
function createHtmlWebpackPluginHooks () {
return {
beforeAssetTagGeneration: new AsyncSeriesWaterfallHook(['pluginArgs']),
alterAssetTags: new AsyncSeriesWaterfallHook(['pluginArgs']),
alterAssetTagGroups: new AsyncSeriesWaterfallHook(['pluginArgs']),
afterTemplateExecution: new AsyncSeriesWaterfallHook(['pluginArgs']),
beforeEmit: new AsyncSeriesWaterfallHook(['pluginArgs']),
afterEmit: new AsyncSeriesWaterfallHook(['pluginArgs'])
};
}
|
javascript
|
{
"resource": ""
}
|
q18451
|
scrollInterpolator1
|
train
|
function scrollInterpolator1 (index, carouselProps) {
const range = [3, 2, 1, 0, -1];
const inputRange = getInputRangeFromIndexes(range, index, carouselProps);
const outputRange = range;
return { inputRange, outputRange };
}
|
javascript
|
{
"resource": ""
}
|
q18452
|
flattenValues
|
train
|
function flattenValues (report) {
if (Object.prototype.toString.call(report.values) === '[object Array]') {
report.values.forEach(function (value) {
Object.assign(report, value)
})
}
return report
}
|
javascript
|
{
"resource": ""
}
|
q18453
|
train
|
function(key, optionalDefaultValue) {
var data = this.storage.read(this._namespacePrefix + key)
return this._deserialize(data, optionalDefaultValue)
}
|
javascript
|
{
"resource": ""
}
|
|
q18454
|
train
|
function(callback) {
var self = this
this.storage.each(function(val, namespacedKey) {
callback.call(self, self._deserialize(val), (namespacedKey || '').replace(self._namespaceRegexp, ''))
})
}
|
javascript
|
{
"resource": ""
}
|
|
q18455
|
super_fn
|
train
|
function super_fn() {
if (!oldFn) { return }
each(arguments, function(arg, i) {
args[i] = arg
})
return oldFn.apply(self, args)
}
|
javascript
|
{
"resource": ""
}
|
q18456
|
set
|
train
|
function set(super_fn, key, val) {
var oldVal = this.get(key)
super_fn()
pubsub.fire(key, val, oldVal)
}
|
javascript
|
{
"resource": ""
}
|
q18457
|
fixShortcut
|
train
|
function fixShortcut(name) {
if(isMac) {
name = name.replace("Ctrl", "Cmd");
} else {
name = name.replace("Cmd", "Ctrl");
}
return name;
}
|
javascript
|
{
"resource": ""
}
|
q18458
|
getState
|
train
|
function getState(cm, pos) {
pos = pos || cm.getCursor("start");
var stat = cm.getTokenAt(pos);
if(!stat.type) return {};
var types = stat.type.split(" ");
var ret = {},
data, text;
for(var i = 0; i < types.length; i++) {
data = types[i];
if(data === "strong") {
ret.bold = true;
} else if(data === "variable-2") {
text = cm.getLine(pos.line);
if(/^\s*\d+\.\s/.test(text)) {
ret["ordered-list"] = true;
} else {
ret["unordered-list"] = true;
}
} else if(data === "atom") {
ret.quote = true;
} else if(data === "em") {
ret.italic = true;
} else if(data === "quote") {
ret.quote = true;
} else if(data === "strikethrough") {
ret.strikethrough = true;
} else if(data === "comment") {
ret.code = true;
} else if(data === "link") {
ret.link = true;
} else if(data === "tag") {
ret.image = true;
} else if(data.match(/^header(\-[1-6])?$/)) {
ret[data.replace("header", "heading")] = true;
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q18459
|
toggleCodeBlock
|
train
|
function toggleCodeBlock(editor) {
var fenceCharsToInsert = editor.options.blockStyles.code;
function fencing_line(line) {
/* return true, if this is a ``` or ~~~ line */
if(typeof line !== "object") {
throw "fencing_line() takes a 'line' object (not a line number, or line text). Got: " + typeof line + ": " + line;
}
return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
}
function token_state(token) {
// base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
return token.state.base.base || token.state.base;
}
function code_type(cm, line_num, line, firstTok, lastTok) {
/*
* Return "single", "indented", "fenced" or false
*
* cm and line_num are required. Others are optional for efficiency
* To check in the middle of a line, pass in firstTok yourself.
*/
line = line || cm.getLineHandle(line_num);
firstTok = firstTok || cm.getTokenAt({
line: line_num,
ch: 1
});
lastTok = lastTok || (!!line.text && cm.getTokenAt({
line: line_num,
ch: line.text.length - 1
}));
var types = firstTok.type ? firstTok.type.split(" ") : [];
if(lastTok && token_state(lastTok).indentedCode) {
// have to check last char, since first chars of first line aren"t marked as indented
return "indented";
} else if(types.indexOf("comment") === -1) {
// has to be after "indented" check, since first chars of first indented line aren"t marked as such
return false;
} else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
return "fenced";
} else {
return "single";
}
}
function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
var start_line_sel = cur_start.line + 1,
end_line_sel = cur_end.line + 1,
sel_multi = cur_start.line !== cur_end.line,
repl_start = fenceCharsToInsert + "\n",
repl_end = "\n" + fenceCharsToInsert;
if(sel_multi) {
end_line_sel++;
}
// handle last char including \n or not
if(sel_multi && cur_end.ch === 0) {
repl_end = fenceCharsToInsert + "\n";
end_line_sel--;
}
_replaceSelection(cm, false, [repl_start, repl_end]);
cm.setSelection({
line: start_line_sel,
ch: 0
}, {
line: end_line_sel,
ch: 0
});
}
var cm = editor.codemirror,
cur_start = cm.getCursor("start"),
cur_end = cm.getCursor("end"),
tok = cm.getTokenAt({
line: cur_start.line,
ch: cur_start.ch || 1
}), // avoid ch 0 which is a cursor pos but not token
line = cm.getLineHandle(cur_start.line),
is_code = code_type(cm, cur_start.line, line, tok);
var block_start, block_end, lineCount;
if(is_code === "single") {
// similar to some SimpleMDE _toggleBlock logic
var start = line.text.slice(0, cur_start.ch).replace("`", ""),
end = line.text.slice(cur_start.ch).replace("`", "");
cm.replaceRange(start + end, {
line: cur_start.line,
ch: 0
}, {
line: cur_start.line,
ch: 99999999999999
});
cur_start.ch--;
if(cur_start !== cur_end) {
cur_end.ch--;
}
cm.setSelection(cur_start, cur_end);
cm.focus();
} else if(is_code === "fenced") {
if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
// use selection
// find the fenced line so we know what type it is (tilde, backticks, number of them)
for(block_start = cur_start.line; block_start >= 0; block_start--) {
line = cm.getLineHandle(block_start);
if(fencing_line(line)) {
break;
}
}
var fencedTok = cm.getTokenAt({
line: block_start,
ch: 1
});
var fence_chars = token_state(fencedTok).fencedChars;
var start_text, start_line;
var end_text, end_line;
// check for selection going up against fenced lines, in which case we don't want to add more fencing
if(fencing_line(cm.getLineHandle(cur_start.line))) {
start_text = "";
start_line = cur_start.line;
} else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
start_text = "";
start_line = cur_start.line - 1;
} else {
start_text = fence_chars + "\n";
start_line = cur_start.line;
}
if(fencing_line(cm.getLineHandle(cur_end.line))) {
end_text = "";
end_line = cur_end.line;
if(cur_end.ch === 0) {
end_line += 1;
}
} else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
end_text = "";
end_line = cur_end.line + 1;
} else {
end_text = fence_chars + "\n";
end_line = cur_end.line + 1;
}
if(cur_end.ch === 0) {
// full last line selected, putting cursor at beginning of next
end_line -= 1;
}
cm.operation(function() {
// end line first, so that line numbers don't change
cm.replaceRange(end_text, {
line: end_line,
ch: 0
}, {
line: end_line + (end_text ? 0 : 1),
ch: 0
});
cm.replaceRange(start_text, {
line: start_line,
ch: 0
}, {
line: start_line + (start_text ? 0 : 1),
ch: 0
});
});
cm.setSelection({
line: start_line + (start_text ? 1 : 0),
ch: 0
}, {
line: end_line + (start_text ? 1 : -1),
ch: 0
});
cm.focus();
} else {
// no selection, search for ends of this fenced block
var search_from = cur_start.line;
if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
if(code_type(cm, cur_start.line + 1) === "fenced") {
block_start = cur_start.line;
search_from = cur_start.line + 1; // for searching for "end"
} else {
block_end = cur_start.line;
search_from = cur_start.line - 1; // for searching for "start"
}
}
if(block_start === undefined) {
for(block_start = search_from; block_start >= 0; block_start--) {
line = cm.getLineHandle(block_start);
if(fencing_line(line)) {
break;
}
}
}
if(block_end === undefined) {
lineCount = cm.lineCount();
for(block_end = search_from; block_end < lineCount; block_end++) {
line = cm.getLineHandle(block_end);
if(fencing_line(line)) {
break;
}
}
}
cm.operation(function() {
cm.replaceRange("", {
line: block_start,
ch: 0
}, {
line: block_start + 1,
ch: 0
});
cm.replaceRange("", {
line: block_end - 1,
ch: 0
}, {
line: block_end,
ch: 0
});
});
cm.focus();
}
} else if(is_code === "indented") {
if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
// use selection
block_start = cur_start.line;
block_end = cur_end.line;
if(cur_end.ch === 0) {
block_end--;
}
} else {
// no selection, search for ends of this indented block
for(block_start = cur_start.line; block_start >= 0; block_start--) {
line = cm.getLineHandle(block_start);
if(line.text.match(/^\s*$/)) {
// empty or all whitespace - keep going
continue;
} else {
if(code_type(cm, block_start, line) !== "indented") {
block_start += 1;
break;
}
}
}
lineCount = cm.lineCount();
for(block_end = cur_start.line; block_end < lineCount; block_end++) {
line = cm.getLineHandle(block_end);
if(line.text.match(/^\s*$/)) {
// empty or all whitespace - keep going
continue;
} else {
if(code_type(cm, block_end, line) !== "indented") {
block_end -= 1;
break;
}
}
}
}
// if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
// insert a blank line so that the next line(s) continue to be indented code
var next_line = cm.getLineHandle(block_end + 1),
next_line_last_tok = next_line && cm.getTokenAt({
line: block_end + 1,
ch: next_line.text.length - 1
}),
next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
if(next_line_indented) {
cm.replaceRange("\n", {
line: block_end + 1,
ch: 0
});
}
for(var i = block_start; i <= block_end; i++) {
cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
}
cm.focus();
} else {
// insert code formatting
var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
var sel_multi = cur_start.line !== cur_end.line;
if(no_sel_and_starting_of_line || sel_multi) {
insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
} else {
_replaceSelection(cm, false, ["`", "`"]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q18460
|
drawLink
|
train
|
function drawLink(editor) {
var cm = editor.codemirror;
var stat = getState(cm);
var options = editor.options;
var url = "http://";
if(options.promptURLs) {
url = prompt(options.promptTexts.link);
if(!url) {
return false;
}
}
_replaceSelection(cm, stat.link, options.insertTexts.link, url);
}
|
javascript
|
{
"resource": ""
}
|
q18461
|
drawImage
|
train
|
function drawImage(editor) {
var cm = editor.codemirror;
var stat = getState(cm);
var options = editor.options;
var url = "http://";
if(options.promptURLs) {
url = prompt(options.promptTexts.image);
if(!url) {
return false;
}
}
_replaceSelection(cm, stat.image, options.insertTexts.image, url);
}
|
javascript
|
{
"resource": ""
}
|
q18462
|
drawTable
|
train
|
function drawTable(editor) {
var cm = editor.codemirror;
var stat = getState(cm);
var options = editor.options;
_replaceSelection(cm, stat.table, options.insertTexts.table);
}
|
javascript
|
{
"resource": ""
}
|
q18463
|
drawHorizontalRule
|
train
|
function drawHorizontalRule(editor) {
var cm = editor.codemirror;
var stat = getState(cm);
var options = editor.options;
_replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);
}
|
javascript
|
{
"resource": ""
}
|
q18464
|
togglePreview
|
train
|
function togglePreview(editor) {
var cm = editor.codemirror;
var wrapper = cm.getWrapperElement();
var toolbar_div = wrapper.previousSibling;
var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
var preview = wrapper.lastChild;
if(!preview || !/editor-preview/.test(preview.className)) {
preview = document.createElement("div");
preview.className = "editor-preview";
wrapper.appendChild(preview);
}
if(/editor-preview-active/.test(preview.className)) {
preview.className = preview.className.replace(
/\s*editor-preview-active\s*/g, ""
);
if(toolbar) {
toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
}
} else {
// When the preview button is clicked for the first time,
// give some time for the transition from editor.css to fire and the view to slide from right to left,
// instead of just appearing.
setTimeout(function() {
preview.className += " editor-preview-active";
}, 1);
if(toolbar) {
toolbar.className += " active";
toolbar_div.className += " disabled-for-preview";
}
}
preview.innerHTML = editor.options.previewRender(editor.value(), preview);
// Turn off side by side if needed
var sidebyside = cm.getWrapperElement().nextSibling;
if(/editor-preview-active-side/.test(sidebyside.className))
toggleSideBySide(editor);
}
|
javascript
|
{
"resource": ""
}
|
q18465
|
_mergeProperties
|
train
|
function _mergeProperties(target, source) {
for(var property in source) {
if(source.hasOwnProperty(property)) {
if(source[property] instanceof Array) {
target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);
} else if(
source[property] !== null &&
typeof source[property] === "object" &&
source[property].constructor === Object
) {
target[property] = _mergeProperties(target[property] || {}, source[property]);
} else {
target[property] = source[property];
}
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
q18466
|
extend
|
train
|
function extend(target) {
for(var i = 1; i < arguments.length; i++) {
target = _mergeProperties(target, arguments[i]);
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
q18467
|
isLocalStorageAvailable
|
train
|
function isLocalStorageAvailable() {
if(typeof localStorage === "object") {
try {
localStorage.setItem("smde_localStorage", 1);
localStorage.removeItem("smde_localStorage");
} catch(e) {
return false;
}
} else {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q18468
|
buildSpriteString
|
train
|
function buildSpriteString(icons) {
const symbols = Object.keys(icons)
.map(icon => toSvgSymbol(icon, icons[icon]))
.join('');
return `<svg xmlns="${DEFAULT_ATTRS.xmlns}"><defs>${symbols}</defs></svg>`;
}
|
javascript
|
{
"resource": ""
}
|
q18469
|
toSvg
|
train
|
function toSvg(name, attrs = {}) {
console.warn(
'feather.toSvg() is deprecated. Please use feather.icons[name].toSvg() instead.',
);
if (!name) {
throw new Error('The required `key` (icon name) parameter is missing.');
}
if (!icons[name]) {
throw new Error(
`No icon matching '${
name
}'. See the complete list of icons at https://feathericons.com`,
);
}
return icons[name].toSvg(attrs);
}
|
javascript
|
{
"resource": ""
}
|
q18470
|
attrsToString
|
train
|
function attrsToString(attrs) {
return Object.keys(attrs)
.map(key => `${key}="${attrs[key]}"`)
.join(' ');
}
|
javascript
|
{
"resource": ""
}
|
q18471
|
replace
|
train
|
function replace(attrs = {}) {
if (typeof document === 'undefined') {
throw new Error('`feather.replace()` only works in a browser environment.');
}
const elementsToReplace = document.querySelectorAll('[data-feather]');
Array.from(elementsToReplace).forEach(element =>
replaceElement(element, attrs),
);
}
|
javascript
|
{
"resource": ""
}
|
q18472
|
replaceElement
|
train
|
function replaceElement(element, attrs = {}) {
const elementAttrs = getAttrs(element);
const name = elementAttrs['data-feather'];
delete elementAttrs['data-feather'];
const svgString = icons[name].toSvg({
...attrs,
...elementAttrs,
...{ class: classnames(attrs.class, elementAttrs.class) },
});
const svgDocument = new DOMParser().parseFromString(
svgString,
'image/svg+xml',
);
const svgElement = svgDocument.querySelector('svg');
element.parentNode.replaceChild(svgElement, element);
}
|
javascript
|
{
"resource": ""
}
|
q18473
|
getAttrs
|
train
|
function getAttrs(element) {
return Array.from(element.attributes).reduce((attrs, attr) => {
attrs[attr.name] = attr.value;
return attrs;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q18474
|
processSvg
|
train
|
function processSvg(svg) {
return (
optimize(svg)
.then(setAttrs)
.then(format)
// remove semicolon inserted by prettier
// because prettier thinks it's formatting JSX not HTML
.then(svg => svg.replace(/;/g, ''))
);
}
|
javascript
|
{
"resource": ""
}
|
q18475
|
optimize
|
train
|
function optimize(svg) {
const svgo = new Svgo({
plugins: [
{ convertShapeToPath: false },
{ mergePaths: false },
{ removeAttrs: { attrs: '(fill|stroke.*)' } },
{ removeTitle: true },
],
});
return new Promise(resolve => {
svgo.optimize(svg, ({ data }) => resolve(data));
});
}
|
javascript
|
{
"resource": ""
}
|
q18476
|
setAttrs
|
train
|
function setAttrs(svg) {
const $ = cheerio.load(svg);
Object.keys(DEFAULT_ATTRS).forEach(key =>
$('svg').attr(key, DEFAULT_ATTRS[key]),
);
return $('body').html();
}
|
javascript
|
{
"resource": ""
}
|
q18477
|
nextPow2
|
train
|
function nextPow2(size) {
return Math.pow(2, Math.ceil(Math.log(size) / Math.LN2));
}
|
javascript
|
{
"resource": ""
}
|
q18478
|
loadFromBuffer
|
train
|
function loadFromBuffer(input) {
var buf = new BunserBuf();
var result = buf.append(input, true);
if (buf.buf.readAvail()) {
throw Error(
'excess data found after input buffer, use BunserBuf instead');
}
if (typeof result === 'undefined') {
throw Error(
'no bser found in string and no error raised!?');
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q18479
|
byteswap64
|
train
|
function byteswap64(buf) {
var swap = new Buffer(buf.length);
for (var i = 0; i < buf.length; i++) {
swap[i] = buf[buf.length -1 - i];
}
return swap;
}
|
javascript
|
{
"resource": ""
}
|
q18480
|
dumpToBuffer
|
train
|
function dumpToBuffer(val) {
var buf = new Accumulator();
// Build out the header
buf.writeByte(0);
buf.writeByte(1);
// Reserve room for an int32 to hold our PDU length
buf.writeByte(BSER_INT32);
buf.writeInt(0, 4); // We'll come back and fill this in at the end
dump_any(buf, val);
// Compute PDU length
var off = buf.writeOffset;
var len = off - 7 /* the header length */;
buf.writeOffset = 3; // The length value to fill in
buf.writeInt(len, 4); // write the length in the space we reserved
buf.writeOffset = off;
return buf.buf.slice(0, off);
}
|
javascript
|
{
"resource": ""
}
|
q18481
|
forEach
|
train
|
function forEach(callback /* , thisArg */) {
var entries = getInternalParamsState(this).entries;
var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3);
var i = 0;
var entry;
while (i < entries.length) {
entry = entries[i++];
boundFunction(entry.value, entry.key, this);
}
}
|
javascript
|
{
"resource": ""
}
|
q18482
|
sortBy
|
train
|
function sortBy (coll, iteratee, callback) {
var _iteratee = wrapAsync(iteratee);
return map(coll, (x, iterCb) => {
_iteratee(x, (err, criteria) => {
if (err) return iterCb(err);
iterCb(err, {value: x, criteria});
});
}, (err, results) => {
if (err) return callback(err);
callback(null, results.sort(comparator).map(v => v.value));
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q18483
|
whilst
|
train
|
function whilst(test, iteratee, callback) {
callback = onlyOnce(callback);
var _fn = wrapAsync(iteratee);
var _test = wrapAsync(test);
var results = [];
function next(err, ...rest) {
if (err) return callback(err);
results = rest;
if (err === false) return;
_test(check);
}
function check(err, truth) {
if (err) return callback(err);
if (err === false) return;
if (!truth) return callback(null, ...results);
_fn(next);
}
return _test(check);
}
|
javascript
|
{
"resource": ""
}
|
q18484
|
every
|
train
|
function every(coll, iteratee, callback) {
return createTester(bool => !bool, res => !res)(eachOf, coll, iteratee, callback)
}
|
javascript
|
{
"resource": ""
}
|
q18485
|
eachOfArrayLike
|
train
|
function eachOfArrayLike(coll, iteratee, callback) {
callback = once(callback);
var index = 0,
completed = 0,
{length} = coll,
canceled = false;
if (length === 0) {
callback(null);
}
function iteratorCallback(err, value) {
if (err === false) {
canceled = true
}
if (canceled === true) return
if (err) {
callback(err);
} else if ((++completed === length) || value === breakLoop) {
callback(null);
}
}
for (; index < length; index++) {
iteratee(coll[index], index, onlyOnce(iteratorCallback));
}
}
|
javascript
|
{
"resource": ""
}
|
q18486
|
reduce
|
train
|
function reduce(coll, memo, iteratee, callback) {
callback = once(callback);
var _iteratee = wrapAsync(iteratee);
return eachOfSeries(coll, (x, i, iterCb) => {
_iteratee(memo, x, (err, v) => {
memo = v;
iterCb(err);
});
}, err => callback(err, memo));
}
|
javascript
|
{
"resource": ""
}
|
q18487
|
waterfall
|
train
|
function waterfall (tasks, callback) {
callback = once(callback);
if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
if (!tasks.length) return callback();
var taskIndex = 0;
function nextTask(args) {
var task = wrapAsync(tasks[taskIndex++]);
task(...args, onlyOnce(next));
}
function next(err, ...args) {
if (err === false) return
if (err || taskIndex === tasks.length) {
return callback(err, ...args);
}
nextTask(args);
}
nextTask([]);
}
|
javascript
|
{
"resource": ""
}
|
q18488
|
some
|
train
|
function some(coll, iteratee, callback) {
return createTester(Boolean, res => res)(eachOf, coll, iteratee, callback)
}
|
javascript
|
{
"resource": ""
}
|
q18489
|
sortStrs
|
train
|
function sortStrs(strArr) {
return strArr.sort(function(s1, s2) {
var lowerCaseS1 = s1.toLowerCase();
var lowerCaseS2 = s2.toLowerCase();
if (lowerCaseS1 < lowerCaseS2) {
return -1;
} else if (lowerCaseS1 > lowerCaseS2) {
return 1;
} else {
return 0;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q18490
|
forever
|
train
|
function forever(fn, errback) {
var done = onlyOnce(errback);
var task = wrapAsync(ensureAsync(fn));
function next(err) {
if (err) return done(err);
if (err === false) return;
task(next);
}
return next();
}
|
javascript
|
{
"resource": ""
}
|
q18491
|
train
|
function (b) {
var a = this;
var sx = b.width / a.width;
var sy = b.height / a.height;
var m = matrix.create();
// 矩阵右乘
matrix.translate(m, m, [-a.x, -a.y]);
matrix.scale(m, m, [sx, sy]);
matrix.translate(m, m, [b.x, b.y]);
return m;
}
|
javascript
|
{
"resource": ""
}
|
|
q18492
|
train
|
function (state, subPropKey, key, transitionCfg, done) {
var el = this._el;
var stateObj = subPropKey ? state[subPropKey] : state;
var elObj = subPropKey ? el[subPropKey] : el;
var availableProp = stateObj && (key in stateObj)
&& elObj && (key in elObj);
var transitionAnimators = this._transitionAnimators;
if (availableProp) {
var obj = {};
if (stateObj[key] === elObj[key]) {
return 0;
}
obj[key] = stateObj[key];
var animator = el.animate(subPropKey)
.when(transitionCfg.duration, obj)
.delay(transitionCfg.dealy)
.done(function () {
var idx = zrUtil.indexOf(transitionAnimators, 1);
if (idx > 0) {
transitionAnimators.splice(idx, 1);
}
done();
})
.start(transitionCfg.easing);
transitionAnimators.push(animator);
return 1;
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q18493
|
train
|
function (cb, context) {
var zlevelList = this._zlevelList;
var z;
var i;
for (i = 0; i < zlevelList.length; i++) {
z = zlevelList[i];
cb.call(context, this._layers[z], z);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q18494
|
train
|
function (opts) {
opts = opts || {};
if (this._singleCanvas && !this._compositeManually) {
return this._layers[CANVAS_ZLEVEL].dom;
}
var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
imageLayer.initContext();
imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
if (opts.pixelRatio <= this.dpr) {
this.refresh();
var width = imageLayer.dom.width;
var height = imageLayer.dom.height;
var ctx = imageLayer.ctx;
this.eachLayer(function (layer) {
if (layer.__builtin__) {
ctx.drawImage(layer.dom, 0, 0, width, height);
}
else if (layer.renderToCanvas) {
imageLayer.ctx.save();
layer.renderToCanvas(imageLayer.ctx);
imageLayer.ctx.restore();
}
});
}
else {
// PENDING, echarts-gl and incremental rendering.
var scope = {};
var displayList = this.storage.getDisplayList(true);
for (var i = 0; i < displayList.length; i++) {
var el = displayList[i];
this._doPaintEl(el, imageLayer, true, scope);
}
}
return imageLayer.dom;
}
|
javascript
|
{
"resource": ""
}
|
|
q18495
|
train
|
function (cb, context) {
context !== void 0 && (cb = bind(cb, context));
for (var key in this.data) {
this.data.hasOwnProperty(key) && cb(this.data[key], key);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q18496
|
train
|
function (t) {
var p = someVectorAt(this.shape, t, true);
return vec2.normalize(p, p);
}
|
javascript
|
{
"resource": ""
}
|
|
q18497
|
fillArr
|
train
|
function fillArr(arr0, arr1, arrDim) {
var arr0Len = arr0.length;
var arr1Len = arr1.length;
if (arr0Len !== arr1Len) {
// FIXME Not work for TypedArray
var isPreviousLarger = arr0Len > arr1Len;
if (isPreviousLarger) {
// Cut the previous
arr0.length = arr1Len;
}
else {
// Fill the previous
for (var i = arr0Len; i < arr1Len; i++) {
arr0.push(
arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
);
}
}
}
// Handling NaN value
var len2 = arr0[0] && arr0[0].length;
for (var i = 0; i < arr0.length; i++) {
if (arrDim === 1) {
if (isNaN(arr0[i])) {
arr0[i] = arr1[i];
}
}
else {
for (var j = 0; j < len2; j++) {
if (isNaN(arr0[i][j])) {
arr0[i][j] = arr1[i][j];
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q18498
|
catmullRomInterpolateArray
|
train
|
function catmullRomInterpolateArray(
p0, p1, p2, p3, t, t2, t3, out, arrDim
) {
var len = p0.length;
if (arrDim === 1) {
for (var i = 0; i < len; i++) {
out[i] = catmullRomInterpolate(
p0[i], p1[i], p2[i], p3[i], t, t2, t3
);
}
}
else {
var len2 = p0[0].length;
for (var i = 0; i < len; i++) {
for (var j = 0; j < len2; j++) {
out[i][j] = catmullRomInterpolate(
p0[i][j], p1[i][j], p2[i][j], p3[i][j],
t, t2, t3
);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q18499
|
train
|
function (event, query, handler, context) {
return on(this, event, query, handler, context, true);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.