_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q48400
|
train
|
function() {
this.appendDummyInput('TOPROW')
.appendField('', 'NAME');
this.setOutput(true);
this.setColour(Blockly.Blocks.procedures.HUE);
// Tooltip is set in domToMutation.
this.setHelpUrl(Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL);
this.arguments_ = [];
this.quarkConnections_ = {};
this.quarkIds_ = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q48401
|
train
|
function() {
this.appendValueInput('CONDITION')
.setCheck('Boolean')
.appendField(Blockly.Msg.CONTROLS_IF_MSG_IF);
this.appendValueInput('VALUE')
.appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN);
this.setInputsInline(true);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setColour(Blockly.Blocks.procedures.HUE);
this.setTooltip(Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP);
this.setHelpUrl(Blockly.Msg.PROCEDURES_IFRETURN_HELPURL);
this.hasReturnValue_ = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q48402
|
train
|
function(xmlElement) {
var value = xmlElement.getAttribute('value');
this.hasReturnValue_ = (value == 1);
if (!this.hasReturnValue_) {
this.removeInput('VALUE');
this.appendDummyInput('VALUE')
.appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48403
|
train
|
function() {
this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);
this.setColour(Blockly.Blocks.texts.HUE);
this.appendDummyInput()
.appendField(this.newQuote_(true))
.appendField(new Blockly.FieldTextInput(''), 'TEXT')
.appendField(this.newQuote_(false));
this.setOutput(true, 'String');
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
// Text block is trivial. Use tooltip of parent block if it exists.
this.setTooltip(function() {
var parent = thisBlock.getParent();
return (parent && parent.tooltip) || Blockly.Msg.TEXT_TEXT_TOOLTIP;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48404
|
train
|
function() {
this.setColour(Blockly.Blocks.texts.HUE);
this.appendDummyInput()
.appendField(Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN);
this.appendStatementInput('STACK');
this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP);
this.contextMenu = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q48405
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.TEXT_LENGTH_TITLE,
"args0": [
{
"type": "input_value",
"name": "VALUE",
"check": ['String', 'Array']
}
],
"output": 'Number',
"colour": Blockly.Blocks.texts.HUE,
"tooltip": Blockly.Msg.TEXT_LENGTH_TOOLTIP,
"helpUrl": Blockly.Msg.TEXT_LENGTH_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48406
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.TEXT_ISEMPTY_TITLE,
"args0": [
{
"type": "input_value",
"name": "VALUE",
"check": ['String', 'Array']
}
],
"output": 'Boolean',
"colour": Blockly.Blocks.texts.HUE,
"tooltip": Blockly.Msg.TEXT_ISEMPTY_TOOLTIP,
"helpUrl": Blockly.Msg.TEXT_ISEMPTY_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48407
|
train
|
function() {
this.WHERE_OPTIONS =
[[Blockly.Msg.TEXT_CHARAT_FROM_START, 'FROM_START'],
[Blockly.Msg.TEXT_CHARAT_FROM_END, 'FROM_END'],
[Blockly.Msg.TEXT_CHARAT_FIRST, 'FIRST'],
[Blockly.Msg.TEXT_CHARAT_LAST, 'LAST'],
[Blockly.Msg.TEXT_CHARAT_RANDOM, 'RANDOM']];
this.setHelpUrl(Blockly.Msg.TEXT_CHARAT_HELPURL);
this.setColour(Blockly.Blocks.texts.HUE);
this.setOutput(true, 'String');
this.appendValueInput('VALUE')
.setCheck('String')
.appendField(Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT);
this.appendDummyInput('AT');
this.setInputsInline(true);
this.updateAt_(true);
this.setTooltip(Blockly.Msg.TEXT_CHARAT_TOOLTIP);
}
|
javascript
|
{
"resource": ""
}
|
|
q48408
|
train
|
function(isAt) {
// Destroy old 'AT' and 'ORDINAL' inputs.
this.removeInput('AT');
this.removeInput('ORDINAL', true);
// Create either a value 'AT' input or a dummy input.
if (isAt) {
this.appendValueInput('AT').setCheck('Number');
if (Blockly.Msg.ORDINAL_NUMBER_SUFFIX) {
this.appendDummyInput('ORDINAL')
.appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX);
}
} else {
this.appendDummyInput('AT');
}
if (Blockly.Msg.TEXT_CHARAT_TAIL) {
this.removeInput('TAIL', true);
this.appendDummyInput('TAIL')
.appendField(Blockly.Msg.TEXT_CHARAT_TAIL);
}
var menu = new Blockly.FieldDropdown(this.WHERE_OPTIONS, function(value) {
var newAt = (value == 'FROM_START') || (value == 'FROM_END');
// The 'isAt' variable is available due to this function being a closure.
if (newAt != isAt) {
var block = this.sourceBlock_;
block.updateAt_(newAt);
// This menu has been destroyed and replaced. Update the replacement.
block.setFieldValue(value, 'WHERE');
return null;
}
return undefined;
});
this.getInput('AT').appendField(menu, 'WHERE');
}
|
javascript
|
{
"resource": ""
}
|
|
q48409
|
train
|
function() {
var container = document.createElement('mutation');
var isAt1 = this.getInput('AT1').type == Blockly.INPUT_VALUE;
container.setAttribute('at1', isAt1);
var isAt2 = this.getInput('AT2').type == Blockly.INPUT_VALUE;
container.setAttribute('at2', isAt2);
return container;
}
|
javascript
|
{
"resource": ""
}
|
|
q48410
|
train
|
function(xmlElement) {
var isAt1 = (xmlElement.getAttribute('at1') == 'true');
var isAt2 = (xmlElement.getAttribute('at2') == 'true');
this.updateAt_(1, isAt1);
this.updateAt_(2, isAt2);
}
|
javascript
|
{
"resource": ""
}
|
|
q48411
|
train
|
function() {
var OPERATORS =
[[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE, 'UPPERCASE'],
[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE, 'LOWERCASE'],
[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE, 'TITLECASE']];
this.setHelpUrl(Blockly.Msg.TEXT_CHANGECASE_HELPURL);
this.setColour(Blockly.Blocks.texts.HUE);
this.appendValueInput('TEXT')
.setCheck('String')
.appendField(new Blockly.FieldDropdown(OPERATORS), 'CASE');
this.setOutput(true, 'String');
this.setTooltip(Blockly.Msg.TEXT_CHANGECASE_TOOLTIP);
}
|
javascript
|
{
"resource": ""
}
|
|
q48412
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.TEXT_PRINT_TITLE,
"args0": [
{
"type": "input_value",
"name": "TEXT"
}
],
"previousStatement": null,
"nextStatement": null,
"colour": Blockly.Blocks.texts.HUE,
"tooltip": Blockly.Msg.TEXT_PRINT_TOOLTIP,
"helpUrl": Blockly.Msg.TEXT_PRINT_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48413
|
train
|
function(xmlElement) {
this.elseifCount_ = parseInt(xmlElement.getAttribute('elseif'), 10) || 0;
this.elseCount_ = parseInt(xmlElement.getAttribute('else'), 10) || 0;
this.updateShape_();
}
|
javascript
|
{
"resource": ""
}
|
|
q48414
|
train
|
function(containerBlock) {
var clauseBlock = containerBlock.nextConnection.targetBlock();
var i = 1;
while (clauseBlock) {
switch (clauseBlock.type) {
case 'controls_if_elseif':
var inputIf = this.getInput('IF' + i);
var inputDo = this.getInput('DO' + i);
clauseBlock.valueConnection_ =
inputIf && inputIf.connection.targetConnection;
clauseBlock.statementConnection_ =
inputDo && inputDo.connection.targetConnection;
i++;
break;
case 'controls_if_else':
var inputDo = this.getInput('ELSE');
clauseBlock.statementConnection_ =
inputDo && inputDo.connection.targetConnection;
break;
default:
throw 'Unknown block type.';
}
clauseBlock = clauseBlock.nextConnection &&
clauseBlock.nextConnection.targetBlock();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48415
|
train
|
function() {
this.setColour(Blockly.Blocks.logic.HUE);
this.appendDummyInput()
.appendField(Blockly.Msg.CONTROLS_IF_IF_TITLE_IF);
this.setNextStatement(true);
this.setTooltip(Blockly.Msg.CONTROLS_IF_IF_TOOLTIP);
this.contextMenu = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q48416
|
train
|
function() {
this.setColour(Blockly.Blocks.logic.HUE);
this.appendDummyInput()
.appendField(Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip(Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP);
this.contextMenu = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q48417
|
train
|
function() {
this.setColour(Blockly.Blocks.logic.HUE);
this.appendDummyInput()
.appendField(Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE);
this.setPreviousStatement(true);
this.setTooltip(Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP);
this.contextMenu = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q48418
|
train
|
function() {
var OPERATORS = this.RTL ? [
['=', 'EQ'],
['\u2260', 'NEQ'],
['>', 'LT'],
['\u2265', 'LTE'],
['<', 'GT'],
['\u2264', 'GTE']
] : [
['=', 'EQ'],
['\u2260', 'NEQ'],
['<', 'LT'],
['\u2264', 'LTE'],
['>', 'GT'],
['\u2265', 'GTE']
];
this.setHelpUrl(Blockly.Msg.LOGIC_COMPARE_HELPURL);
this.setColour(Blockly.Blocks.logic.HUE);
this.setOutput(true, 'Boolean');
this.appendValueInput('A');
this.appendValueInput('B')
.appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
this.setInputsInline(true);
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
this.setTooltip(function() {
var op = thisBlock.getFieldValue('OP');
var TOOLTIPS = {
'EQ': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ,
'NEQ': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ,
'LT': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT,
'LTE': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE,
'GT': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT,
'GTE': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE
};
return TOOLTIPS[op];
});
this.prevBlocks_ = [null, null];
}
|
javascript
|
{
"resource": ""
}
|
|
q48419
|
train
|
function(e) {
var blockA = this.getInputTargetBlock('A');
var blockB = this.getInputTargetBlock('B');
// Disconnect blocks that existed prior to this change if they don't match.
if (blockA && blockB &&
!blockA.outputConnection.checkType_(blockB.outputConnection)) {
// Mismatch between two inputs. Disconnect previous and bump it away.
// Ensure that any disconnections are grouped with the causing event.
Blockly.Events.setGroup(e.group);
for (var i = 0; i < this.prevBlocks_.length; i++) {
var block = this.prevBlocks_[i];
if (block === blockA || block === blockB) {
block.unplug();
block.bumpNeighbours_();
}
}
Blockly.Events.setGroup(false);
}
this.prevBlocks_[0] = blockA;
this.prevBlocks_[1] = blockB;
}
|
javascript
|
{
"resource": ""
}
|
|
q48420
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.LOGIC_NEGATE_TITLE,
"args0": [
{
"type": "input_value",
"name": "BOOL",
"check": "Boolean"
}
],
"output": "Boolean",
"colour": Blockly.Blocks.logic.HUE,
"tooltip": Blockly.Msg.LOGIC_NEGATE_TOOLTIP,
"helpUrl": Blockly.Msg.LOGIC_NEGATE_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48421
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.LOGIC_NULL,
"output": null,
"colour": Blockly.Blocks.logic.HUE,
"tooltip": Blockly.Msg.LOGIC_NULL_TOOLTIP,
"helpUrl": Blockly.Msg.LOGIC_NULL_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48422
|
train
|
function() {
this.setHelpUrl(Blockly.Msg.LOGIC_TERNARY_HELPURL);
this.setColour(Blockly.Blocks.logic.HUE);
this.appendValueInput('IF')
.setCheck('Boolean')
.appendField(Blockly.Msg.LOGIC_TERNARY_CONDITION);
this.appendValueInput('THEN')
.appendField(Blockly.Msg.LOGIC_TERNARY_IF_TRUE);
this.appendValueInput('ELSE')
.appendField(Blockly.Msg.LOGIC_TERNARY_IF_FALSE);
this.setOutput(true);
this.setTooltip(Blockly.Msg.LOGIC_TERNARY_TOOLTIP);
this.prevParentConnection_ = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q48423
|
train
|
function(e) {
var blockA = this.getInputTargetBlock('THEN');
var blockB = this.getInputTargetBlock('ELSE');
var parentConnection = this.outputConnection.targetConnection;
// Disconnect blocks that existed prior to this change if they don't match.
if ((blockA || blockB) && parentConnection) {
for (var i = 0; i < 2; i++) {
var block = (i == 1) ? blockA : blockB;
if (block && !block.outputConnection.checkType_(parentConnection)) {
// Ensure that any disconnections are grouped with the causing event.
Blockly.Events.setGroup(e.group);
if (parentConnection === this.prevParentConnection_) {
this.unplug();
parentConnection.getSourceBlock().bumpNeighbours_();
} else {
block.unplug();
block.bumpNeighbours_();
}
Blockly.Events.setGroup(false);
}
}
}
this.prevParentConnection_ = parentConnection;
}
|
javascript
|
{
"resource": ""
}
|
|
q48424
|
train
|
function(e) {
var blocks = this.workspace_.getTopBlocks(false);
for (var i = 0, block; block = blocks[i]; i++) {
block.removeSelect();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48425
|
train
|
function() {
this.setHelpUrl(Blockly.Msg.VARIABLES_SET_HELPURL);
this.setColour(330);
this.appendValueInput('VALUE')
.appendField(Plane.getMsg('Plane_setSeats'));
this.setTooltip(Blockly.Msg.VARIABLES_SET_TOOLTIP);
this.setDeletable(false);
}
|
javascript
|
{
"resource": ""
}
|
|
q48426
|
train
|
function() {
this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL);
this.setColour(330);
this.appendDummyInput()
.appendField(Plane.getMsg('Plane_getRows2'), 'title');
this.setOutput(true, 'Number');
}
|
javascript
|
{
"resource": ""
}
|
|
q48427
|
formatChange
|
train
|
function formatChange() {
var mask = document.getElementById('blocklyMask');
var languagePre = document.getElementById('languagePre');
var languageTA = document.getElementById('languageTA');
if (document.getElementById('format').value == 'Manual') {
Blockly.hideChaff();
mask.style.display = 'block';
languagePre.style.display = 'none';
languageTA.style.display = 'block';
var code = languagePre.textContent.trim();
languageTA.value = code;
languageTA.focus();
updatePreview();
} else {
mask.style.display = 'none';
languageTA.style.display = 'none';
languagePre.style.display = 'block';
updateLanguage();
}
disableEnableLink();
}
|
javascript
|
{
"resource": ""
}
|
q48428
|
updateLanguage
|
train
|
function updateLanguage() {
var rootBlock = getRootBlock();
if (!rootBlock) {
return;
}
var blockType = rootBlock.getFieldValue('NAME').trim().toLowerCase();
if (!blockType) {
blockType = UNNAMED;
}
blockType = blockType.replace(/\W/g, '_').replace(/^(\d)/, '_\\1');
switch (document.getElementById('format').value) {
case 'JSON':
var code = formatJson_(blockType, rootBlock);
break;
case 'JavaScript':
var code = formatJavaScript_(blockType, rootBlock);
break;
}
injectCode(code, 'languagePre');
updatePreview();
}
|
javascript
|
{
"resource": ""
}
|
q48429
|
formatJavaScript_
|
train
|
function formatJavaScript_(blockType, rootBlock) {
var code = [];
code.push("Blockly.Blocks['" + blockType + "'] = {");
code.push(" init: function() {");
// Generate inputs.
var TYPES = {'input_value': 'appendValueInput',
'input_statement': 'appendStatementInput',
'input_dummy': 'appendDummyInput'};
var contentsBlock = rootBlock.getInputTargetBlock('INPUTS');
while (contentsBlock) {
if (!contentsBlock.disabled && !contentsBlock.getInheritedDisabled()) {
var name = '';
// Dummy inputs don't have names. Other inputs do.
if (contentsBlock.type != 'input_dummy') {
name = escapeString(contentsBlock.getFieldValue('INPUTNAME'));
}
code.push(' this.' + TYPES[contentsBlock.type] + '(' + name + ')');
var check = getOptTypesFrom(contentsBlock, 'TYPE');
if (check) {
code.push(' .setCheck(' + check + ')');
}
var align = contentsBlock.getFieldValue('ALIGN');
if (align != 'LEFT') {
code.push(' .setAlign(Blockly.ALIGN_' + align + ')');
}
var fields = getFieldsJs_(contentsBlock.getInputTargetBlock('FIELDS'));
for (var i = 0; i < fields.length; i++) {
code.push(' .appendField(' + fields[i] + ')');
}
// Add semicolon to last line to finish the statement.
code[code.length - 1] += ';';
}
contentsBlock = contentsBlock.nextConnection &&
contentsBlock.nextConnection.targetBlock();
}
// Generate inline/external switch.
if (rootBlock.getFieldValue('INLINE') == 'EXT') {
code.push(' this.setInputsInline(false);');
} else if (rootBlock.getFieldValue('INLINE') == 'INT') {
code.push(' this.setInputsInline(true);');
}
// Generate output, or next/previous connections.
switch (rootBlock.getFieldValue('CONNECTIONS')) {
case 'LEFT':
code.push(connectionLineJs_('setOutput', 'OUTPUTTYPE'));
break;
case 'BOTH':
code.push(connectionLineJs_('setPreviousStatement', 'TOPTYPE'));
code.push(connectionLineJs_('setNextStatement', 'BOTTOMTYPE'));
break;
case 'TOP':
code.push(connectionLineJs_('setPreviousStatement', 'TOPTYPE'));
break;
case 'BOTTOM':
code.push(connectionLineJs_('setNextStatement', 'BOTTOMTYPE'));
break;
}
// Generate colour.
var colourBlock = rootBlock.getInputTargetBlock('COLOUR');
if (colourBlock && !colourBlock.disabled) {
var hue = parseInt(colourBlock.getFieldValue('HUE'), 10);
if (!isNaN(hue)) {
code.push(' this.setColour(' + hue + ');');
}
}
code.push(" this.setTooltip('');");
code.push(" this.setHelpUrl('http://www.example.com/');");
code.push(' }');
code.push('};');
return code.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q48430
|
connectionLineJs_
|
train
|
function connectionLineJs_(functionName, typeName) {
var type = getOptTypesFrom(getRootBlock(), typeName);
if (type) {
type = ', ' + type;
} else {
type = '';
}
return ' this.' + functionName + '(true' + type + ');';
}
|
javascript
|
{
"resource": ""
}
|
q48431
|
updatePreview
|
train
|
function updatePreview() {
// Toggle between LTR/RTL if needed (also used in first display).
var newDir = document.getElementById('direction').value;
if (oldDir != newDir) {
if (previewWorkspace) {
previewWorkspace.dispose();
}
var rtl = newDir == 'rtl';
previewWorkspace = Blockly.inject('preview',
{rtl: rtl,
media: '../../media/',
scrollbars: true});
oldDir = newDir;
}
previewWorkspace.clear();
// Fetch the code and determine its format (JSON or JavaScript).
var format = document.getElementById('format').value;
if (format == 'Manual') {
var code = document.getElementById('languageTA').value;
// If the code is JSON, it will parse, otherwise treat as JS.
try {
JSON.parse(code);
format = 'JSON';
} catch (e) {
format = 'JavaScript';
}
} else {
var code = document.getElementById('languagePre').textContent;
}
if (!code.trim()) {
// Nothing to render. Happens while cloud storage is loading.
return;
}
// Backup Blockly.Blocks object so that main workspace and preview don't
// collide if user creates a 'factory_base' block, for instance.
var backupBlocks = Blockly.Blocks;
try {
// Make a shallow copy.
Blockly.Blocks = {};
for (var prop in backupBlocks) {
Blockly.Blocks[prop] = backupBlocks[prop];
}
if (format == 'JSON') {
var json = JSON.parse(code);
Blockly.Blocks[json.id || UNNAMED] = {
init: function() {
this.jsonInit(json);
}
};
} else if (format == 'JavaScript') {
eval(code);
} else {
throw 'Unknown format: ' + format;
}
// Look for a block on Blockly.Blocks that does not match the backup.
var blockType = null;
for (var type in Blockly.Blocks) {
if (typeof Blockly.Blocks[type].init == 'function' &&
Blockly.Blocks[type] != backupBlocks[type]) {
blockType = type;
break;
}
}
if (!blockType) {
return;
}
// Create the preview block.
var previewBlock = previewWorkspace.newBlock(blockType);
previewBlock.initSvg();
previewBlock.render();
previewBlock.setMovable(false);
previewBlock.setDeletable(false);
previewBlock.moveBy(15, 10);
previewWorkspace.clearUndo();
updateGenerator(previewBlock);
} finally {
Blockly.Blocks = backupBlocks;
}
}
|
javascript
|
{
"resource": ""
}
|
q48432
|
getRootBlock
|
train
|
function getRootBlock() {
var blocks = mainWorkspace.getTopBlocks(false);
for (var i = 0, block; block = blocks[i]; i++) {
if (block.type == 'factory_base') {
return block;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q48433
|
init
|
train
|
function init() {
if ('BlocklyStorage' in window) {
BlocklyStorage.HTTPREQUEST_ERROR =
'There was a problem with the request.\n';
BlocklyStorage.LINK_ALERT =
'Share your blocks with this link:\n\n%1';
BlocklyStorage.HASH_ERROR =
'Sorry, "%1" doesn\'t correspond with any saved Blockly file.';
BlocklyStorage.XML_ERROR = 'Could not load your saved file.\n'+
'Perhaps it was created with a different version of Blockly?';
var linkButton = document.getElementById('linkButton');
linkButton.style.display = 'inline-block';
linkButton.addEventListener('click',
function() {BlocklyStorage.link(mainWorkspace);});
disableEnableLink();
}
document.getElementById('helpButton').addEventListener('click',
function() {
open('https://developers.google.com/blockly/custom-blocks/block-factory',
'BlockFactoryHelp');
});
var expandList = [
document.getElementById('blockly'),
document.getElementById('blocklyMask'),
document.getElementById('preview'),
document.getElementById('languagePre'),
document.getElementById('languageTA'),
document.getElementById('generatorPre')
];
var onresize = function(e) {
for (var i = 0, expand; expand = expandList[i]; i++) {
expand.style.width = (expand.parentNode.offsetWidth - 2) + 'px';
expand.style.height = (expand.parentNode.offsetHeight - 2) + 'px';
}
};
onresize();
window.addEventListener('resize', onresize);
var toolbox = document.getElementById('toolbox');
mainWorkspace = Blockly.inject('blockly',
{collapse: false,
toolbox: toolbox,
media: '../../media/'});
// Create the root block.
if ('BlocklyStorage' in window && window.location.hash.length > 1) {
BlocklyStorage.retrieveXml(window.location.hash.substring(1),
mainWorkspace);
} else {
var xml = '<xml><block type="factory_base" deletable="false" movable="false"></block></xml>';
Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(xml), mainWorkspace);
}
mainWorkspace.clearUndo();
mainWorkspace.addChangeListener(updateLanguage);
document.getElementById('direction')
.addEventListener('change', updatePreview);
document.getElementById('languageTA')
.addEventListener('change', updatePreview);
document.getElementById('languageTA')
.addEventListener('keyup', updatePreview);
document.getElementById('format')
.addEventListener('change', formatChange);
document.getElementById('language')
.addEventListener('change', updatePreview);
}
|
javascript
|
{
"resource": ""
}
|
q48434
|
train
|
function() {
this.setHelpUrl(Blockly.Msg.MATH_NUMBER_HELPURL);
this.setColour(Blockly.Blocks.math.HUE);
this.appendDummyInput()
.appendField(new Blockly.FieldTextInput('0',
Blockly.FieldTextInput.numberValidator), 'NUM');
this.setOutput(true, 'Number');
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
// Number block is trivial. Use tooltip of parent block if it exists.
this.setTooltip(function() {
var parent = thisBlock.getParent();
return (parent && parent.tooltip) || Blockly.Msg.MATH_NUMBER_TOOLTIP;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48435
|
train
|
function() {
this.jsonInit({
"message0": "%1 %2 %3",
"args0": [
{
"type": "input_value",
"name": "A",
"check": "Number"
},
{
"type": "field_dropdown",
"name": "OP",
"options":
[[Blockly.Msg.MATH_ADDITION_SYMBOL, 'ADD'],
[Blockly.Msg.MATH_SUBTRACTION_SYMBOL, 'MINUS'],
[Blockly.Msg.MATH_MULTIPLICATION_SYMBOL, 'MULTIPLY'],
[Blockly.Msg.MATH_DIVISION_SYMBOL, 'DIVIDE'],
[Blockly.Msg.MATH_POWER_SYMBOL, 'POWER']]
},
{
"type": "input_value",
"name": "B",
"check": "Number"
}
],
"inputsInline": true,
"output": "Number",
"colour": Blockly.Blocks.math.HUE,
"helpUrl": Blockly.Msg.MATH_ARITHMETIC_HELPURL
});
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
this.setTooltip(function() {
var mode = thisBlock.getFieldValue('OP');
var TOOLTIPS = {
'ADD': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD,
'MINUS': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS,
'MULTIPLY': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY,
'DIVIDE': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE,
'POWER': Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER
};
return TOOLTIPS[mode];
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48436
|
train
|
function() {
this.jsonInit({
"message0": "%1 %2",
"args0": [
{
"type": "field_dropdown",
"name": "OP",
"options": [
[Blockly.Msg.MATH_SINGLE_OP_ROOT, 'ROOT'],
[Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE, 'ABS'],
['-', 'NEG'],
['ln', 'LN'],
['log10', 'LOG10'],
['e^', 'EXP'],
['10^', 'POW10']
]
},
{
"type": "input_value",
"name": "NUM",
"check": "Number"
}
],
"output": "Number",
"colour": Blockly.Blocks.math.HUE,
"helpUrl": Blockly.Msg.MATH_SINGLE_HELPURL
});
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
this.setTooltip(function() {
var mode = thisBlock.getFieldValue('OP');
var TOOLTIPS = {
'ROOT': Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT,
'ABS': Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS,
'NEG': Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG,
'LN': Blockly.Msg.MATH_SINGLE_TOOLTIP_LN,
'LOG10': Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10,
'EXP': Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP,
'POW10': Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10
};
return TOOLTIPS[mode];
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48437
|
train
|
function() {
this.jsonInit({
"message0": "%1 %2",
"args0": [
{
"type": "field_dropdown",
"name": "OP",
"options": [
[Blockly.Msg.MATH_TRIG_SIN, 'SIN'],
[Blockly.Msg.MATH_TRIG_COS, 'COS'],
[Blockly.Msg.MATH_TRIG_TAN, 'TAN'],
[Blockly.Msg.MATH_TRIG_ASIN, 'ASIN'],
[Blockly.Msg.MATH_TRIG_ACOS, 'ACOS'],
[Blockly.Msg.MATH_TRIG_ATAN, 'ATAN']
]
},
{
"type": "input_value",
"name": "NUM",
"check": "Number"
}
],
"output": "Number",
"colour": Blockly.Blocks.math.HUE,
"helpUrl": Blockly.Msg.MATH_TRIG_HELPURL
});
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
this.setTooltip(function() {
var mode = thisBlock.getFieldValue('OP');
var TOOLTIPS = {
'SIN': Blockly.Msg.MATH_TRIG_TOOLTIP_SIN,
'COS': Blockly.Msg.MATH_TRIG_TOOLTIP_COS,
'TAN': Blockly.Msg.MATH_TRIG_TOOLTIP_TAN,
'ASIN': Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN,
'ACOS': Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS,
'ATAN': Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN
};
return TOOLTIPS[mode];
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48438
|
train
|
function() {
var PROPERTIES =
[[Blockly.Msg.MATH_IS_EVEN, 'EVEN'],
[Blockly.Msg.MATH_IS_ODD, 'ODD'],
[Blockly.Msg.MATH_IS_PRIME, 'PRIME'],
[Blockly.Msg.MATH_IS_WHOLE, 'WHOLE'],
[Blockly.Msg.MATH_IS_POSITIVE, 'POSITIVE'],
[Blockly.Msg.MATH_IS_NEGATIVE, 'NEGATIVE'],
[Blockly.Msg.MATH_IS_DIVISIBLE_BY, 'DIVISIBLE_BY']];
this.setColour(Blockly.Blocks.math.HUE);
this.appendValueInput('NUMBER_TO_CHECK')
.setCheck('Number');
var dropdown = new Blockly.FieldDropdown(PROPERTIES, function(option) {
var divisorInput = (option == 'DIVISIBLE_BY');
this.sourceBlock_.updateShape_(divisorInput);
});
this.appendDummyInput()
.appendField(dropdown, 'PROPERTY');
this.setInputsInline(true);
this.setOutput(true, 'Boolean');
this.setTooltip(Blockly.Msg.MATH_IS_TOOLTIP);
}
|
javascript
|
{
"resource": ""
}
|
|
q48439
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.MATH_CHANGE_TITLE,
"args0": [
{
"type": "field_variable",
"name": "VAR",
"variable": Blockly.Msg.MATH_CHANGE_TITLE_ITEM
},
{
"type": "input_value",
"name": "DELTA",
"check": "Number"
}
],
"previousStatement": null,
"nextStatement": null,
"colour": Blockly.Blocks.math.HUE,
"helpUrl": Blockly.Msg.MATH_CHANGE_HELPURL
});
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
this.setTooltip(function() {
return Blockly.Msg.MATH_CHANGE_TOOLTIP.replace('%1',
thisBlock.getFieldValue('VAR'));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48440
|
train
|
function() {
this.jsonInit({
"message0": "%1 %2",
"args0": [
{
"type": "field_dropdown",
"name": "OP",
"options": [
[Blockly.Msg.MATH_ROUND_OPERATOR_ROUND, 'ROUND'],
[Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP, 'ROUNDUP'],
[Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN, 'ROUNDDOWN']
]
},
{
"type": "input_value",
"name": "NUM",
"check": "Number"
}
],
"output": "Number",
"colour": Blockly.Blocks.math.HUE,
"tooltip": Blockly.Msg.MATH_ROUND_TOOLTIP,
"helpUrl": Blockly.Msg.MATH_ROUND_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48441
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.MATH_MODULO_TITLE,
"args0": [
{
"type": "input_value",
"name": "DIVIDEND",
"check": "Number"
},
{
"type": "input_value",
"name": "DIVISOR",
"check": "Number"
}
],
"inputsInline": true,
"output": "Number",
"colour": Blockly.Blocks.math.HUE,
"tooltip": Blockly.Msg.MATH_MODULO_TOOLTIP,
"helpUrl": Blockly.Msg.MATH_MODULO_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48442
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.MATH_CONSTRAIN_TITLE,
"args0": [
{
"type": "input_value",
"name": "VALUE",
"check": "Number"
},
{
"type": "input_value",
"name": "LOW",
"check": "Number"
},
{
"type": "input_value",
"name": "HIGH",
"check": "Number"
}
],
"inputsInline": true,
"output": "Number",
"colour": Blockly.Blocks.math.HUE,
"tooltip": Blockly.Msg.MATH_CONSTRAIN_TOOLTIP,
"helpUrl": Blockly.Msg.MATH_CONSTRAIN_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48443
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM,
"output": "Number",
"colour": Blockly.Blocks.math.HUE,
"tooltip": Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP,
"helpUrl": Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48444
|
cacheList
|
train
|
function cacheList() {
if (list.match(/^\w+$/)) {
return '';
}
var listVar = Blockly.PHP.variableDB_.getDistinctName(
'tmp_list', Blockly.Variables.NAME_TYPE);
var code = listVar + ' = &' + list + ';\n';
list = listVar;
return code;
}
|
javascript
|
{
"resource": ""
}
|
q48445
|
train
|
function() {
this.setHelpUrl(Blockly.Msg.LISTS_CREATE_WITH_HELPURL);
this.setColour(Blockly.Blocks.lists.HUE);
this.itemCount_ = 3;
this.updateShape_();
this.setOutput(true, 'Array');
this.setMutator(new Blockly.Mutator(['lists_create_with_item']));
this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP);
}
|
javascript
|
{
"resource": ""
}
|
|
q48446
|
train
|
function() {
this.setColour(Blockly.Blocks.lists.HUE);
this.appendDummyInput()
.appendField(Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP);
this.contextMenu = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q48447
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.LISTS_REPEAT_TITLE,
"args0": [
{
"type": "input_value",
"name": "ITEM"
},
{
"type": "input_value",
"name": "NUM",
"check": "Number"
}
],
"output": "Array",
"colour": Blockly.Blocks.lists.HUE,
"tooltip": Blockly.Msg.LISTS_REPEAT_TOOLTIP,
"helpUrl": Blockly.Msg.LISTS_REPEAT_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48448
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.LISTS_LENGTH_TITLE,
"args0": [
{
"type": "input_value",
"name": "VALUE",
"check": ['String', 'Array']
}
],
"output": 'Number',
"colour": Blockly.Blocks.lists.HUE,
"tooltip": Blockly.Msg.LISTS_LENGTH_TOOLTIP,
"helpUrl": Blockly.Msg.LISTS_LENGTH_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48449
|
train
|
function() {
this.jsonInit({
"message0": Blockly.Msg.LISTS_ISEMPTY_TITLE,
"args0": [
{
"type": "input_value",
"name": "VALUE",
"check": ['String', 'Array']
}
],
"output": 'Boolean',
"colour": Blockly.Blocks.lists.HUE,
"tooltip": Blockly.Msg.LISTS_ISEMPTY_TOOLTIP,
"helpUrl": Blockly.Msg.LISTS_ISEMPTY_HELPURL
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48450
|
train
|
function() {
var MODE =
[[Blockly.Msg.LISTS_GET_INDEX_GET, 'GET'],
[Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE, 'GET_REMOVE'],
[Blockly.Msg.LISTS_GET_INDEX_REMOVE, 'REMOVE']];
this.WHERE_OPTIONS =
[[Blockly.Msg.LISTS_GET_INDEX_FROM_START, 'FROM_START'],
[Blockly.Msg.LISTS_GET_INDEX_FROM_END, 'FROM_END'],
[Blockly.Msg.LISTS_GET_INDEX_FIRST, 'FIRST'],
[Blockly.Msg.LISTS_GET_INDEX_LAST, 'LAST'],
[Blockly.Msg.LISTS_GET_INDEX_RANDOM, 'RANDOM']];
this.setHelpUrl(Blockly.Msg.LISTS_GET_INDEX_HELPURL);
this.setColour(Blockly.Blocks.lists.HUE);
var modeMenu = new Blockly.FieldDropdown(MODE, function(value) {
var isStatement = (value == 'REMOVE');
this.sourceBlock_.updateStatement_(isStatement);
});
this.appendValueInput('VALUE')
.setCheck('Array')
.appendField(Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST);
this.appendDummyInput()
.appendField(modeMenu, 'MODE')
.appendField('', 'SPACE');
this.appendDummyInput('AT');
if (Blockly.Msg.LISTS_GET_INDEX_TAIL) {
this.appendDummyInput('TAIL')
.appendField(Blockly.Msg.LISTS_GET_INDEX_TAIL);
}
this.setInputsInline(true);
this.setOutput(true);
this.updateAt_(true);
// Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this;
this.setTooltip(function() {
var combo = thisBlock.getFieldValue('MODE') + '_' +
thisBlock.getFieldValue('WHERE');
return Blockly.Msg['LISTS_GET_INDEX_TOOLTIP_' + combo];
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48451
|
train
|
function() {
var container = document.createElement('mutation');
var isStatement = !this.outputConnection;
container.setAttribute('statement', isStatement);
var isAt = this.getInput('AT').type == Blockly.INPUT_VALUE;
container.setAttribute('at', isAt);
return container;
}
|
javascript
|
{
"resource": ""
}
|
|
q48452
|
train
|
function(xmlElement) {
// Note: Until January 2013 this block did not have mutations,
// so 'statement' defaults to false and 'at' defaults to true.
var isStatement = (xmlElement.getAttribute('statement') == 'true');
this.updateStatement_(isStatement);
var isAt = (xmlElement.getAttribute('at') != 'false');
this.updateAt_(isAt);
}
|
javascript
|
{
"resource": ""
}
|
|
q48453
|
train
|
function(newStatement) {
var oldStatement = !this.outputConnection;
if (newStatement != oldStatement) {
this.unplug(true, true);
if (newStatement) {
this.setOutput(false);
this.setPreviousStatement(true);
this.setNextStatement(true);
} else {
this.setPreviousStatement(false);
this.setNextStatement(false);
this.setOutput(true);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48454
|
train
|
function() {
// Assign 'this' to a variable for use in the closures below.
var thisBlock = this;
var dropdown = new Blockly.FieldDropdown(
[[Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT, 'SPLIT'],
[Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST, 'JOIN']],
function(newMode) {
thisBlock.updateType_(newMode);
});
this.setHelpUrl(Blockly.Msg.LISTS_SPLIT_HELPURL);
this.setColour(Blockly.Blocks.lists.HUE);
this.appendValueInput('INPUT')
.setCheck('String')
.appendField(dropdown, 'MODE');
this.appendValueInput('DELIM')
.setCheck('String')
.appendField(Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER);
this.setInputsInline(true);
this.setOutput(true, 'Array');
this.setTooltip(function() {
var mode = thisBlock.getFieldValue('MODE');
if (mode == 'SPLIT') {
return Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT;
} else if (mode == 'JOIN') {
return Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN;
}
throw 'Unknown mode: ' + mode;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48455
|
train
|
function(newMode) {
if (newMode == 'SPLIT') {
this.outputConnection.setCheck('Array');
this.getInput('INPUT').setCheck('String');
} else {
this.outputConnection.setCheck('String');
this.getInput('INPUT').setCheck('Array');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48456
|
train
|
function(arg, suffix) {
if (Blockly.isNumber(arg)) {
// Simple number.
arg = parseFloat(arg);
} else if (arg.match(/^\w+$/)) {
// Variable.
arg = 'float(' + arg + ')';
} else {
// It's complicated.
var varName = Blockly.Python.variableDB_.getDistinctName(
variable0 + suffix, Blockly.Variables.NAME_TYPE);
code += varName + ' = float(' + arg + ')\n';
arg = varName;
}
return arg;
}
|
javascript
|
{
"resource": ""
}
|
|
q48457
|
Rocky
|
train
|
function Rocky (opts) {
if (!(this instanceof Rocky)) return new Rocky(opts)
opts = opts || {}
Base.call(this, opts)
this.server = null
this.router = router(opts.router)
this._setupMiddleware()
}
|
javascript
|
{
"resource": ""
}
|
q48458
|
setSingle
|
train
|
function setSingle(store, key, value, flag) {
const { _store, _subscriptions } = store
// Uncurry alfa action functions
if (typeof value === 'function' && value.alfaAction) {
value = value.alfaAction(store)
}
// Save the value to the store.
_store[key] = value
if (flag === 'merge') {
return
}
// Call subscribed functions if we have.
const subs = _subscriptions[key]
if (subs) {
var changed = {
[key]: value
}
subs.forEach(function(subFn) {
// Make sure the subFn is still legit at the time we are calling it since
// all subscribing functions are actually `setStat`. And previous
// `setState` calls could trigger unmount component which later `setState`
// belongs to.
// Need to make the below code reproducible by test.
// var _subs = subscriptions[key]
// if (_subs.indexOf(subFn) === -1) {
// return
// }
if (subFn.maps) {
var maps = subFn.maps
Object.keys(maps).some(function(injectKey) {
const realKey = maps[injectKey]
if (realKey === key) {
changed = {
[injectKey]: value
}
return true
}
return false
})
}
subFn(changed)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q48459
|
getDynamicProps
|
train
|
function getDynamicProps({ keys, maps, inputs }, outputs, alfaStore) {
const _props = getInjectedProps(inputs, outputs, alfaStore)
if (maps) {
keys.forEach(key => {
_props[key] = _props[maps[key]]
})
// Map outputs
if (outputs && 'function' === typeof _props.set) {
// The `set` of `props` which is obtained from calling
// `alfaStore.setWithOutputs(outputs)`
const _setWithOutputs = _props.set
// Call `_setWithOutputs` with maps if
_props.set = function(key, value) {
_setWithOutputs(key, value, maps)
}
}
return _props
} else {
// No mapped props
return _props
}
}
|
javascript
|
{
"resource": ""
}
|
q48460
|
setupBundler
|
train
|
function setupBundler(cwd, entryPoints, flags, noWatchify, ready) {
noWatchify ?
onlocalwatchify() :
resolve('watchify', {basedir: cwd}, onlocalwatchify)
function onlocalwatchify(err, localDir) {
if(err || !localDir) {
return resolve('browserify', {basedir: cwd}, onlocalbrowserify)
}
setupWatchify(path.dirname(localDir), entryPoints, flags, ready)
}
function onlocalbrowserify(err, localDir) {
if(err || !localDir) {
return findGlobals(onglobals)
}
setupBrowserify(path.dirname(localDir), entryPoints, flags, ready)
}
function onglobals(err, dirs) {
if(err) {
return ready(err)
}
dirs = dirs.sort()
for(var i = 0, len = dirs.length; i < len; ++i) {
if(!noWatchify && path.basename(dirs[i]) === 'watchify') {
return setupWatchify(dirs[i], entryPoints, flags, ready)
}
if(path.basename(dirs[i]) === 'browserify') {
return setupBrowserify(dirs[i], entryPoints, flags, ready)
}
}
return ready(new Error('Could not find a suitable bundler!'))
}
}
|
javascript
|
{
"resource": ""
}
|
q48461
|
TableFormatter
|
train
|
function TableFormatter(options) {
const table = new Table(options);
this.format = format;
function format(result, formatOptions) {
let data = [];
_.each(result, function (item) {
data.push(_.values(_.pick(item, options.values)));
});
if (formatOptions.format === 'csv') {
_.each(data, function(row) {
console.log(row.join(','));
});
} else if ( formatOptions.format === 'json') {
console.log(JSON.stringify(result));
} else {
table.push.apply(table, data);
console.log(table.toString());
}
}
}
|
javascript
|
{
"resource": ""
}
|
q48462
|
MessageFormatter
|
train
|
function MessageFormatter() {
this.format = format;
function format(result) {
_.each(result, function(message) {
console.log(message);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q48463
|
init
|
train
|
function init(options) {
self.email = options.email;
self.key = options.token;
self.cloudflareClient = new CloudFlareClient(options.email, options.token);
}
|
javascript
|
{
"resource": ""
}
|
q48464
|
runCommand
|
train
|
function runCommand(command, options) {
let cmd = getCommand(command);
if (!cmd || command === 'help') {
cmd = getCommand('help');
} else {
try {
validateConfig(options);
} catch (error) {
console.log(error.message);
process.exit(1);
}
}
let fn = cmd.callback;
let opts = mapParams(cmd, options);
fn(opts).then(function (result) {
if (cmd.formatter) {
cmd.formatter.format(result.messages, options);
} else {
console.log(result);
}
}).catch(function (error) {
let formatter = new formatters.MessageFormatter();
if (error.response) {
console.log(error);
formatter.format(['Error response received: ' + error.response.data.errors[0].message]);
} else {
formatter.format([error.message]);
}
process.exit(1);
});
}
|
javascript
|
{
"resource": ""
}
|
q48465
|
addRecord
|
train
|
function addRecord(options) {
options.type = options.type || 'CNAME';
return getZone(options.domain)
.then(function (zone) {
return self.cloudflareClient.addRecord(
zone.id,
_.extend({ttl: 1}, mapRecordOptions(options)));
})
.then(function (response) {
return new Result([
format(
'Added %s record %s -> %s',
response.data.result.type,
response.data.result.name,
response.data.result.content
)
]);
}
)
}
|
javascript
|
{
"resource": ""
}
|
q48466
|
editRecord
|
train
|
function editRecord(options) {
return find(options.domain, getQueryParams(options, ['name', 'type', 'query'])).then(function (response) {
const records = response.data.result;
//Properties that are editable
options = mapRecordOptions(options);
if (records.length === 0) {
throw new Error('No matching records found');
} else if (records.length === 1) {
let record = records[0];
options.type = options.type || record.type;
options.content = options.content || record.content;
return self.cloudflareClient.editRecord(record.zone_id, record.id, options);
} else {
throw new Error(format('%d matching records found, unable to update', records.count));
}
}).then(function (response) {
let record = response.data.result;
return new Result([
format('Updated %s record %s (id: %s)', record.type, record.name, record.id)
]);
});
}
|
javascript
|
{
"resource": ""
}
|
q48467
|
find
|
train
|
function find(domain, query) {
if (query.name && !query.name.includes(domain)) {
query.name = query.name + '.' + domain;
}
if (query.query) {
query = _.extend(query, query.query);
delete query.query;
}
return getZone(domain).then(function (zone) {
return self.cloudflareClient.findRecord(zone.id, query);
});
}
|
javascript
|
{
"resource": ""
}
|
q48468
|
listRecords
|
train
|
function listRecords(options) {
return getZone(options.domain).then(function (zone) {
return self.cloudflareClient.findRecord(zone.id, {page: 1, per_page: self.perPage})
.then(function (response) {
let promises = [Promise.resolve(response)];
for (let i = 2; i <= response.data['result_info']['total_pages']; i++) {
promises.push(self.cloudflareClient.findRecord(zone.id, {page: i, per_page: self.perPage}));
}
return Promise.all(promises);
});
}).then(function (responses) {
let rows = [];
_.each(responses, function (response) {
_.each(response.data.result, function (item) {
item.ttl = (item.ttl === 1) ? 'Auto' : item.ttl;
rows.push(item);
});
});
return new Result(rows);
});
}
|
javascript
|
{
"resource": ""
}
|
q48469
|
listZones
|
train
|
function listZones() {
return self.cloudflareClient.findZones({page: 1, per_page: self.perPage})
.then(function (response) {
let promises = [Promise.resolve(response)];
for (let i = 2; i <= response.data['result_info']['total_pages']; i++) {
promises.push(self.cloudflareClient.findZones({page: i, per_page: self.perPage}));
}
return Promise.all(promises);
})
.then(function (responses) {
let rows = [];
_.each(responses, function (response) {
_.each(response.data.result, function (item) {
rows.push(_.extend(
item,
{
planName: item.plan.name,
accountName: item.account.name
}
));
})
});
return new Result(rows);
});
}
|
javascript
|
{
"resource": ""
}
|
q48470
|
purgeCache
|
train
|
function purgeCache(options) {
return getZone(options.domain).then(function (zone) {
let query = (options._[1]) ? {files: options._.slice(1)} : {purge_everything: true};
return self.cloudflareClient.purgeCache(zone.id, query);
}).then(function () {
return new Result('Purged cache successfully');
});
}
|
javascript
|
{
"resource": ""
}
|
q48471
|
getCommand
|
train
|
function getCommand(commandName) {
return _.find(commands, function (command) {
return _.includes(command.aliases, commandName);
});
}
|
javascript
|
{
"resource": ""
}
|
q48472
|
mapRecordOptions
|
train
|
function mapRecordOptions(options) {
if (options.type === 'SRV') {
let contentParts = options.content.split(' ');
let serverParts = options.name.split('.');
options.data = {
service: serverParts[0],
proto: serverParts[1],
name: _.slice(serverParts, 2).join('.'),
priority: parseInt(contentParts[0]),
weight: parseInt(contentParts[1]),
port: parseInt(contentParts[2]),
target: contentParts[3]
}
}
if (options.activate !== undefined) {
options.proxied = options.activate;
}
options = _.omit(options, ['domain', 'email', 'token', '_', 'activate', 'a']);
return options;
}
|
javascript
|
{
"resource": ""
}
|
q48473
|
validateConfig
|
train
|
function validateConfig(config) {
let missing = [];
_.each(requiredOptions, function (option) {
if (config[option] === undefined) {
missing.push(option);
}
});
if (missing.length > 0) {
throw new Error('The following required parameters were not provided: ' + missing.join(','));
}
}
|
javascript
|
{
"resource": ""
}
|
q48474
|
ConfigReader
|
train
|
function ConfigReader(path) {
const self = this;
const fs = require('fs');
const util = require('util');
const yaml = require('js-yaml');
const _ = require('lodash');
const allowedEnvironmentVars = {
token: 'CF_API_KEY',
email: 'CF_API_EMAIL',
domain: 'CF_API_DOMAIN'
};
const homePath = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
path = path ? path.replace('~', homePath) : false;
self.readConfig = readConfig;
function readConfig(account) {
let config = {};
//Load allowed environment variables
const envConfig = _.fromPairs(
_.filter(_.map(allowedEnvironmentVars, function (envVar, key) {
if (process.env[envVar]) {
return [key, process.env[envVar]];
} else {
return false;
}
}
), function (value) {
return value !== false;
})
);
if (path && fs.existsSync(path)) {
try {
const ymlConfig = yaml.safeLoad(fs.readFileSync(path, 'utf8'));
if (ymlConfig !== undefined) {
if (ymlConfig.defaults.account || account) {
account = (account) ? account : ymlConfig.defaults.account;
if (ymlConfig.accounts[account] !== undefined) {
config = ymlConfig.accounts[account];
} else {
console.log(util.format('Unable to find account %s', account));
console.log('Available accounts: ');
_.each(ymlConfig.accounts, function (acc, name) {
console.log(util.format(' - %s', name));
});
return false;
}
} else {
config = ymlConfig.defaults;
}
} else {
throw new Error(util.format('Unable to parse file: %s', path));
}
} catch (error) {
throw new Error(util.format('Invalid config file: %s message: ', path, error.message));
}
}
return _.extend(config, envConfig);
}
}
|
javascript
|
{
"resource": ""
}
|
q48475
|
normalizeLimit
|
train
|
function normalizeLimit (options) {
const limit = options.limit || options.resultRecordCount || options.count || options.maxFeatures
// If there is a limit, add 1 to it so we can later calculate a limitExceeded. The result set will be resized accordingly, post SQL
if (limit) return limit + 1
}
|
javascript
|
{
"resource": ""
}
|
q48476
|
normalizeIdField
|
train
|
function normalizeIdField (options, features = []) {
const collection = options.collection || {}
const metadata = collection.metadata || {}
const feature = features[0] || {}
const featureProperties = feature.properties || feature.attributes || {}
let idField = null
// First, check metadata for idField
if (metadata.idField) idField = metadata.idField
// Check metadata.fields for and OBJECTID property
else if (_.find(metadata.fields, { name: 'OBJECTID' })) idField = 'OBJECTID'
// Check features for an OBJECTID property that is not null
else if (features.length > 0 && !_.isUndefined(featureProperties.OBJECTID) && !_.isNull(featureProperties.OBJECTID)) idField = 'OBJECTID'
// If there are features, check that the idField is one of the properties
if (process.env.NODE_ENV !== 'production' && process.env.KOOP_WARNINGS !== 'suppress' && idField && features.length > 0 && !featureProperties[idField]) {
console.warn(`WARNING: requested provider has "idField" assignment, but this property is not found in properties of all features.`)
}
return idField
}
|
javascript
|
{
"resource": ""
}
|
q48477
|
createClause
|
train
|
function createClause (options = {}, idField = null) {
// Default clause
let clause = `type, properties as properties`
// Comma-delimited list of date-fields is needed for formatting ESRI specific output
let dateFields = options.dateFields.join(',')
let requiresObjectId = !!options.returnIdsOnly || !(options.fields instanceof Array && !options.fields.includes('OBJECTID'))
// If options.fields defined, selected only a subset of teh GeoJSON properties
if (options.fields) {
// if option.fields is an Array, join with comma; if already a comma delimited list, remove any spaces
let fields = (options.fields instanceof Array) ? options.fields.join(',') : options.fields.replace(/,\s+/g, ',')
// For ESRI specific output, process w/ "pickAndEsriFy"; for simple GeoJSON output, process with "pick"
clause = (options.toEsri) ? `pickAndEsriFy(properties, geometry, "${fields}", "${dateFields}", "${requiresObjectId}", "${options.idField}") as attributes` : `pick(properties, "${fields}") as properties`
} else if (options.toEsri) {
// For ESRI specific output, process w/ "esriFy"
clause = `esriFy(properties, geometry, "${dateFields}", "${requiresObjectId}", "${options.idField}") as attributes`
}
return clause
}
|
javascript
|
{
"resource": ""
}
|
q48478
|
normalizeFields
|
train
|
function normalizeFields (options) {
const fields = options.fields || options.outFields
const idField = _.get(options, 'collection.metadata.idField')
if (options.returnIdsOnly === true && idField) return [idField]
else if (options.returnIdsOnly === true) return ['OBJECTID']
if (fields === '*') return undefined
if (typeof fields === 'string' || fields instanceof String) return fields.split(',')
if (fields instanceof Array) return fields
return undefined
}
|
javascript
|
{
"resource": ""
}
|
q48479
|
handleExpr
|
train
|
function handleExpr (node, options) {
let expr
if (node.type === 'unary_expr') {
expr = `${node.operator} ${traverse(node.expr, options)}`
} else if (node.operator === '=' && node.left.value === 1 && node.right.value === 1) {
// a special case related to arcgis server
return '1=1'
} else if (node.operator === 'BETWEEN') {
expr = traverse(node.left, options) + ' ' + (node.operator) + ' ' + (traverse(node.right.value[0], options)) + 'AND' + (traverse(node.right.value[1], options))
} else {
// store the column node for value decoding
if (node.left.type === 'column_ref') {
node.right.columnNode = node.left
}
if (node.right.type === 'column_ref') {
node.left.columnNode = node.right
}
expr = `${traverse(node.left, options)} ${node.operator} ${traverse(node.right, options)}`
}
if (node.parentheses) {
expr = `(${expr})`
}
return expr
}
|
javascript
|
{
"resource": ""
}
|
q48480
|
handleExprList
|
train
|
function handleExprList (node, options) {
const values = node.value.map((valueNode) => traverse(valueNode, options)).join(',')
return `(${values})`
}
|
javascript
|
{
"resource": ""
}
|
q48481
|
handleFunction
|
train
|
function handleFunction (node, options) {
const args = handleExprList(node.args, options)
return `${node.name}${args}`
}
|
javascript
|
{
"resource": ""
}
|
q48482
|
handleValue
|
train
|
function handleValue (node, options) {
let value = node.value
if (node.columnNode) {
const field = _.find(options.esriFields, { name: node.columnNode.column })
if (_.has(field, 'domain.codedValues')) {
const actual = _.find(field.domain.codedValues, { code: value })
if (actual) {
value = actual.name
}
}
}
if (typeof value === 'string') {
value = `'${value}'`
}
return value
}
|
javascript
|
{
"resource": ""
}
|
q48483
|
traverse
|
train
|
function traverse (node, options) {
if (!node) {
return ''
}
switch (node.type) {
case 'unary_expr':
case 'binary_expr':
return handleExpr(node, options)
case 'function':
return handleFunction(node, options)
case 'expr_list':
return handleExprList(node, options)
case 'column_ref':
return handleColumn(node, options)
case 'string':
case 'number':
case 'null':
case 'bool':
return handleValue(node, options)
case 'timestamp':
return handleTimestampValue(node, options)
default:
throw new Error('Unrecognized AST node: \n' + JSON.stringify(node, null, 2))
}
}
|
javascript
|
{
"resource": ""
}
|
q48484
|
esriFy
|
train
|
function esriFy (properties, geometry, dateFields, requiresObjectId, idField) {
const parsedDateFields = (dateFields.length === 0) ? [] : dateFields.split(',')
if (parsedDateFields.length) {
parsedDateFields.forEach(field => {
properties[field] = new Date(properties[field]).getTime()
})
}
// If the object ID is not needed, return here
if (requiresObjectId === 'false') return properties
// Coerce idField
idField = (idField === 'null') ? null : idField
// If the idField for the model set use its value as OBJECTID
if (idField) {
if (process.env.NODE_ENV !== 'production' && process.env.KOOP_WARNINGS !== 'suppress' && (!Number.isInteger(properties[idField]) || properties[idField] > 2147483647)) {
console.warn(`WARNING: OBJECTIDs created from provider's "idField" are not integers from 0 to 2147483647`)
}
} else {
// Create an OBJECTID by creating a numeric hash from the stringified feature
// Note possibility of OBJECTID collisions with this method still exists, but should be small
properties.OBJECTID = createIntHash(JSON.stringify({ properties, geometry }))
}
return properties
}
|
javascript
|
{
"resource": ""
}
|
q48485
|
train
|
function(a, msg) {
a = !!a;
var details = {
result: a,
message: msg
};
msg = escapeInnerText(msg);
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: a,
message: msg
});
}
|
javascript
|
{
"resource": ""
}
|
|
q48486
|
train
|
function(actual, expected, message) {
QUnit.push(expected == actual, actual, expected, message);
}
|
javascript
|
{
"resource": ""
}
|
|
q48487
|
train
|
function() {
extend(config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
filter: "",
queue: [],
semaphore: 0
});
var tests = id( "qunit-tests" ),
banner = id( "qunit-banner" ),
result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = 'Running...<br/> ';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48488
|
train
|
function() {
if ( window.jQuery ) {
jQuery( "#qunit-fixture" ).html( config.fixture );
} else {
var main = id( 'qunit-fixture' );
if ( main ) {
main.innerHTML = config.fixture;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48489
|
train
|
function( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q48490
|
diff
|
train
|
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q48491
|
runLoggingCallbacks
|
train
|
function runLoggingCallbacks(key, scope, args) {
//debugger;
var callbacks;
if ( QUnit.hasOwnProperty(key) ) {
QUnit[key].call(scope, args);
} else {
callbacks = config[key];
for( var i = 0; i < callbacks.length; i++ ) {
callbacks[i].call( scope, args );
}
}
}
|
javascript
|
{
"resource": ""
}
|
q48492
|
useStrictEquality
|
train
|
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a
// declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
|
javascript
|
{
"resource": ""
}
|
q48493
|
o
|
train
|
function o(name, value) {
return {
name: name,
tokens: value || "",
semantic: value || "",
children: []
};
}
|
javascript
|
{
"resource": ""
}
|
q48494
|
displayName
|
train
|
function displayName() {
return wrap('display-name', function phraseFixedSemantic() {
var result = phrase();
if (result !== null) {
result.semantic = collapseWhitespace(result.semantic);
}
return result;
}());
}
|
javascript
|
{
"resource": ""
}
|
q48495
|
searchNodeInTree
|
train
|
function searchNodeInTree(treeRoot, nodeId){
if (treeRoot.childNodes){
for (var i = 0; i < treeRoot.childNodes.length; ++i){
var currentNode = treeRoot.childNodes[i];
if (currentNode._id == nodeId){
return currentNode;
} else {
var found = searchNodeInTree(currentNode, nodeId);
if (found) {
return found;
}
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q48496
|
createTree
|
train
|
function createTree(){
for (var i = 0; i < gRootNodes.length; ++i){
var node = {
_id : gRootNodes[i]._id, //todo : id instead of name?
node : gRootNodes[i],
parent : "root",
childNodes : loadChildNodes(gRootNodes[i])
};
gTree.childNodes.push(node);
}
}
|
javascript
|
{
"resource": ""
}
|
q48497
|
loadChildNodes
|
train
|
function loadChildNodes(parentNode){
if (gNodesWithChildren[parentNode._id]){
var children = [];
for (var i = 0; i < gNodesWithChildren[parentNode._id].length; ++i){
var currentNode = gNodesWithChildren[parentNode._id][i];
children.push({
_id : currentNode._id, //todo : id instead of name?
node : currentNode,
parent : parentNode._id, //todo id instead of name?
childNodes : loadChildNodes(currentNode)
});
}
return children;
}
}
|
javascript
|
{
"resource": ""
}
|
q48498
|
displayNameDOM
|
train
|
function displayNameDOM(node){
$('.nodeLabel').remove();
var nodePos = layout.getNodePosition(node._id);
var domPos = {
x: nodePos.x,
y: nodePos.y
};
graphics.transformGraphToClientCoordinates(domPos);
var labelStyle = generateDOMLabel(node).style;
labelStyle.left = domPos.x;
labelStyle.top = domPos.y;
}
|
javascript
|
{
"resource": ""
}
|
q48499
|
generateDOMLabel
|
train
|
function generateDOMLabel(node) {
var label = document.createElement('span');
label.className = 'nodeLabel';
label.id = node._id;
if (node.name){
label.innerText = node.name;
} else {
label.innerText = node._id;
}
divGraph.appendChild(label);
return label;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.