text:
'use strict';

goog.provide('Blockly.JavaScript.System');

goog.require('Blockly.JavaScript');

// translations
Blockly.Words = {};
Blockly.Words['System'] = {'en': 'System', 'de': 'System', 'ru': 'Системные'};

Blockly.CustomBlocks = Blockly.CustomBlocks || [];
Blockly.CustomBlocks.push('System');

function getHelp(word) {
    return 'https://github.com/ioBroker/ioBroker.javascript/blob/master/README.md#' + Blockly.Words[word][systemLang];
}

Blockly.System = {
    HUE: 210,
    blocks: {}
};

// --- Debug output --------------------------------------------------
Blockly.Words['debug']         = {'en': 'debug output', 'de': 'debug output',   'ru': 'debug output'};
Blockly.Words['debug_tooltip'] = {'en': 'Debug',        'de': 'Debug',          'ru': 'Debug'};
Blockly.Words['debug_help']    = {'en': 'log---gives-out-the-message-into-log', 'de': 'log---gives-out-the-message-into-log', 'ru': 'log---gives-out-the-message-into-log'};

Blockly.System.blocks['debug'] =
      '<block type="debug">'
    + '     <value name="TEXT">'
    + '         <shadow type="text">'
    + '             <field name="TEXT">test</field>'
    + '         </shadow>'
    + '     </value>'
    + '</block>';

Blockly.Blocks['debug'] = {
    init: function() {
        this.appendValueInput('TEXT')
            .setCheck(null)
            .appendField(Blockly.Words['debug'][systemLang]);

        this.appendDummyInput()
            .appendField(new Blockly.FieldDropdown([["info", "log"], ["debug", "debug"], ["warning", "warn"], ["error", "error"]]), "Severity");

        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setInputsInline(false);
        this.setColour(Blockly.System.HUE);
        this.setTooltip(Blockly.Words['debug_tooltip'][systemLang]);
        this.setHelpUrl(getHelp('debug_help'));
    }
};

Blockly.JavaScript['debug'] = function(block) {
    var value_text = Blockly.JavaScript.valueToCode(block, 'TEXT', Blockly.JavaScript.ORDER_ATOMIC);
    var dropdown_severity = block.getFieldValue('Severity');
    return 'console.' + dropdown_severity + '(' + value_text + ');\n';
};

// --- comment --------------------------------------------------
Blockly.Words['comment']         = {'en': 'comment',                           'de': 'Kommentar',      'ru': 'описание'};
Blockly.Words['comment_tooltip'] = {'en': 'Enter comment to explain the code', 'de': 'Debug',          'ru': 'Debug'};

Blockly.System.blocks['comment'] =
    '<block type="comment">'
    + '     <value name="COMMENT">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['comment'] = {
    init: function() {
        this.appendDummyInput('COMMENT')
            .appendField(new Blockly.FieldTextInput(Blockly.Words['comment'][systemLang]), 'COMMENT');

        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setInputsInline(false);
        this.setColour('#FFFF00');
        this.setTooltip(Blockly.Words['comment_tooltip'][systemLang]);
    }
};

Blockly.JavaScript['comment'] = function(block) {
    var comment = block.getFieldValue('COMMENT');
    return '// ' + comment + '\n';
};

// --- control -----------------------------------------------------------
Blockly.Words['control']                = {'en': 'сontrol',        'de': 'steuere',             'ru': 'установить'};
Blockly.Words['control_tooltip']        = {'en': 'Control state',  'de': 'Steuere Zustand',     'ru': 'Установить состояние'};
Blockly.Words['control_help']           = {'en': 'setstate',       'de': 'setstate',            'ru': 'setstate'};
Blockly.Words['control_with']           = {'en': 'with',           'de': 'mit',                 'ru': 'на'};
Blockly.Words['control_delay']          = {'en': 'with delay',     'de': 'mit Verzögerung',     'ru': 'с задержкой'};
Blockly.Words['control_ms']             = {'en': 'in ms',          'de': 'in ms',               'ru': 'в мс'};
Blockly.Words['control_clear_running']  = {'en': ', clear running',  'de': ', löschen falls läuft', 'ru': ', остановить уже запущенный'};

Blockly.System.blocks['control'] =
    '<block type="control">'
    + '     <value name="OID">'
    + '     </value>'
    + '     <value name="VALUE">'
    + '     </value>'
    + '     <value name="WITH_DELAY">'
    + '     </value>'
    + '     <mutation delay_input="false"></mutation>'
    + '     <value name="DELAY_MS">'
    + '     </value>'
    + '     <value name="CLEAR_RUNNING">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['control'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Words['control'][systemLang]);

        this.appendDummyInput('OID')
            .appendField(new Blockly.FieldOID('Object ID', main.initSelectId(), main.objects), 'OID');

        this.appendValueInput('VALUE')
            .setCheck(null)
            .appendField(Blockly.Words['control_with'][systemLang]);

        this.appendDummyInput('WITH_DELAY')
            .appendField(Blockly.Words['control_delay'][systemLang])
            .appendField(new Blockly.FieldCheckbox('FALSE', function(option) {
                var delayInput = (option == true);
                this.sourceBlock_.updateShape_(delayInput);
            }), 'WITH_DELAY');

        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(Blockly.System.HUE);
        this.setTooltip(Blockly.Words['control_tooltip'][systemLang]);
        this.setHelpUrl(getHelp('control_help'));
    },
    mutationToDom: function() {
        var container = document.createElement('mutation');
        container.setAttribute('delay_input', this.getFieldValue('WITH_DELAY') === 'TRUE');
        return container;
    },
    domToMutation: function(xmlElement) {
        this.updateShape_(xmlElement.getAttribute('delay_input') == 'true');
    },
    updateShape_: function(delayInput) {
        // Add or remove a delay Input.
        var inputExists = this.getInput('DELAY');

        if (delayInput) {
            if (!inputExists) {
                this.appendDummyInput('DELAY')
                    .appendField(' ')
                    .appendField(new Blockly.FieldTextInput('1000'), 'DELAY_MS')
                    .appendField(Blockly.Words['control_ms'][systemLang]);
            }
        } else if (inputExists) {
            this.removeInput('DELAY');
        }

        inputExists = this.getInput('CLEAR_RUNNING_INPUT');

        if (delayInput) {
            if (!inputExists) {
                this.appendDummyInput('CLEAR_RUNNING_INPUT')
                    .appendField(Blockly.Words['control_clear_running'][systemLang])
                    .appendField(new Blockly.FieldCheckbox(), 'CLEAR_RUNNING');
            }
        } else if (inputExists) {
            this.removeInput('CLEAR_RUNNING_INPUT');
        }
    }
};

Blockly.JavaScript['control'] = function(block) {
    var valueObjectID = block.getFieldValue('OID');

    Blockly.Msg.VARIABLES_DEFAULT_NAME = 'value';

    var valueDelay   = parseInt(block.getFieldValue('DELAY_MS'), 10);
    var clearRunning = block.getFieldValue('CLEAR_RUNNING') === 'TRUE';
    var valueValue   = Blockly.JavaScript.valueToCode(block, 'VALUE', Blockly.JavaScript.ORDER_ATOMIC);
    var objectName   = main.objects[valueObjectID] && main.objects[valueObjectID].common && main.objects[valueObjectID].common.name ? main.objects[valueObjectID].common.name : '';
    var code;

    if (this.getFieldValue('WITH_DELAY') === 'TRUE') {
        code = 'setStateDelayed("' + valueObjectID + '"' + (objectName ? '/*' + objectName + '*/' : '') + ', ' + valueValue + ', ' + valueDelay + ', ' + clearRunning + ');\n';
    } else {
        code = 'setState("' + valueObjectID + '"' + (objectName ? '/*' + objectName + '*/' : '') + ', ' + valueValue + ');\n';
    }

    return code;
};

// --- update -----------------------------------------------------------
Blockly.Words['update']         = {'en': 'update',          'de': 'aktualisiere',           'ru': 'обновить'};
Blockly.Words['update_tooltip'] = {'en': 'Update state',    'de': 'Zustand aktualisieren',  'ru': 'Обновить состояние'};
Blockly.Words['update_help']    = {'en': 'setstate',        'de': 'setstate',               'ru': 'setstate'};
Blockly.Words['update_with']    = {'en': 'with',            'de': 'mit',                    'ru': 'с'};
Blockly.Words['update_delay']   = {'en': 'with delay',      'de': 'mit Verzögerung',        'ru': 'с задержкой'};
Blockly.Words['update_ms']      = {'en': 'in ms',           'de': 'in ms',                  'ru': 'в мс'};

Blockly.System.blocks['update'] =
    '<block type="update">'
    + '     <value name="OID">'
    + '     </value>'
    + '     <value name="VALUE">'
    + '     </value>'
    + '     <value name="WITH_DELAY">'
    + '     </value>'
    + '     <mutation delay_input="false"></mutation>'
    + '     <value name="DELAY_MS">'
    + '     </value>'
    + '     <value name="CLEAR_RUNNING">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['update'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Words['update'][systemLang]);

        this.appendDummyInput('OID')
            .appendField(new Blockly.FieldOID("Object ID", main.initSelectId(), main.objects), 'OID');

        this.appendValueInput('VALUE')
            .setCheck(null)
            .appendField(Blockly.Words['update_with'][systemLang]);

        this.appendDummyInput('WITH_DELAY')
            .appendField(Blockly.Words['update_delay'][systemLang])
            .appendField(new Blockly.FieldCheckbox("FALSE", function(option) {
                this.sourceBlock_.updateShape_(option == true);
            }), 'WITH_DELAY');

        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(Blockly.System.HUE);
        this.setTooltip(Blockly.Words['update_tooltip'][systemLang]);
        this.setHelpUrl(getHelp('update_help'));
    },
    mutationToDom: function() {
        var container = document.createElement('mutation');
        container.setAttribute('delay_input', this.getFieldValue('WITH_DELAY') === 'TRUE');
        return container;
    },
    domToMutation: function(xmlElement) {
        this.updateShape_(xmlElement.getAttribute('delay_input') == 'true');
    },
    updateShape_: function(delayInput) {
        // Add or remove a delay Input.
        var inputExists = this.getInput('DELAY');

        if (delayInput) {
            if (!inputExists) {
                this.appendDummyInput('DELAY')
                    .appendField(' ')
                    .appendField(new Blockly.FieldTextInput('1000'), 'DELAY_MS')
                    .appendField(Blockly.Words['update_ms'][systemLang]);
            }
        } else if (inputExists) {
            this.removeInput('DELAY');
        }

        inputExists = this.getInput('CLEAR_RUNNING_INPUT');

        if (delayInput) {
            if (!inputExists) {
                this.appendDummyInput('CLEAR_RUNNING_INPUT')
                    .appendField(Blockly.Words['control_clear_running'][systemLang])
                    .appendField(new Blockly.FieldCheckbox(), 'CLEAR_RUNNING');
            }
        } else if (inputExists) {
            this.removeInput('CLEAR_RUNNING_INPUT');
        }
    }
};

Blockly.JavaScript['update'] = function(block) {
    var value_objectid = block.getFieldValue('OID');

    Blockly.Msg.VARIABLES_DEFAULT_NAME = 'value';

    var value_value  = Blockly.JavaScript.valueToCode(block, 'VALUE', Blockly.JavaScript.ORDER_ATOMIC);
    var value_delay  = parseInt(block.getFieldValue('DELAY_MS'), 10);
    var clearRunning = block.getFieldValue('CLEAR_RUNNING') === 'true' || block.getFieldValue('CLEAR_RUNNING') === true;

    var objectname = main.objects[value_objectid] && main.objects[value_objectid].common && main.objects[value_objectid].common.name ? main.objects[value_objectid].common.name : '';
    var code;
    if (this.getFieldValue('WITH_DELAY') === 'TRUE') {
        code = 'setStateDelayed("' + value_objectid + '"' + (objectname ? '/*' + objectname + '*/' : '') + ', ' + value_value + ', true, ' + value_delay + ', ' + clearRunning + ');\n';
    } else {
        code = 'setState("' + value_objectid + '"' + (objectname ? '/*' + objectname + '*/' : '') + ', ' + value_value + ', true);\n';
    }

    return code;
};

// --- direct binding -----------------------------------------------------------
Blockly.Words['direct']                 = {'en': 'bind',           'de': 'binde',            'ru': 'связять'};
Blockly.Words['direct_tooltip']         = {'en': 'Bind two states with each other',          'de': 'Binde zwei Zustände miteinander',     'ru': 'Связать два состояния между собой'};
Blockly.Words['direct_help']            = {'en': 'setstate',       'de': 'setstate',         'ru': 'setstate'};
Blockly.Words['direct_oid_src']         = {'en': '',               'de': '',                 'ru': ''};
Blockly.Words['direct_only_changes']    = {'en': 'only changes',   'de': 'nur Änderungen',   'ru': 'только изменения'};
Blockly.Words['direct_oid_dst']         = {'en': 'with',           'de': 'mit',              'ru': 'c'};

Blockly.System.blocks['direct'] =
    '<block type="direct">'
    + '     <value name="OID_SRC">'
    + '         <shadow type="field_oid">'
    + '             <field name="oid">Object ID 1</field>'
    + '         </shadow>'
    + '     </value>'
    + '     <value name="OID_DST">'
    + '         <shadow type="field_oid">'
    + '             <field name="oid">Object ID 2</field>'
    + '         </shadow>'
    + '     </value>'
    + '     <value name="ONLY_CHANGES">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['direct'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Words['direct'][systemLang]);

        this.appendValueInput('OID_SRC')
            .setCheck('String')
            .appendField(Blockly.Words['direct_oid_src'][systemLang]);

        this.appendValueInput('OID_DST')
            .setCheck('String')
            .appendField(Blockly.Words['direct_oid_dst'][systemLang]);

        this.appendDummyInput('ONLY_CHANGES')
            .appendField(Blockly.Words['direct_only_changes'][systemLang])
            .appendField(new Blockly.FieldCheckbox('TRUE'), 'ONLY_CHANGES');

        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(Blockly.System.HUE);
        this.setTooltip(Blockly.Words['direct_tooltip'][systemLang]);
        this.setHelpUrl(getHelp('direct_help'));
    }
};

Blockly.JavaScript['direct'] = function(block) {
    var oidSrc = Blockly.JavaScript.valueToCode(block, 'OID_SRC', Blockly.JavaScript.ORDER_ATOMIC);
    var onlyChanges = block.getFieldValue('ONLY_CHANGES');
    var oidDest = Blockly.JavaScript.valueToCode(block, 'OID_DST', Blockly.JavaScript.ORDER_ATOMIC);

    return 'on({id: ' + oidSrc + ', change: "' + (onlyChanges == 'TRUE' ? 'ne' : 'any') + '"}, function (obj) {\n  setState(' + oidDest + ', obj.state.val);\n});';
};

// --- control ex -----------------------------------------------------------
Blockly.Words['control_ex']                = {'en': 'write',          'de': 'schreibe',            'ru': 'записать'};
Blockly.Words['control_ex_tooltip']        = {'en': 'Control state',  'de': 'Steuere Zustand',     'ru': 'Установить состояние'};
Blockly.Words['control_ex_control']        = {'en': 'сontrol',        'de': 'steuere',             'ru': 'установить'};
Blockly.Words['control_ex_update']         = {'en': 'update',         'de': 'aktualisiere',        'ru': 'обновить'};
Blockly.Words['control_ex_delay']          = {'en': 'delay in ms',    'de': 'Verzögerung in ms',   'ru': 'Задержка в мс'};
Blockly.Words['control_ex_value']          = {'en': 'value',          'de': 'Wert',                'ru': 'значение'};
Blockly.Words['control_ex_clear_running']  = {'en': 'clear running',  'de': 'löschen falls läuft', 'ru': 'остановить уже запущенный'};

Blockly.System.blocks['control_ex'] =
    '<block type="control_ex">'
    + '     <value name="OID">'
    + '         <shadow type="field_oid">'
    + '             <field name="oid">Object ID</field>'
    + '         </shadow>'
    + '     </value>'
    + '     <value name="VALUE">'
    + '         <shadow type="logic_boolean">'
    + '             <field name="BOOL">TRUE</field>'
    + '         </shadow>'
    + '     </value>'
    + '     <value name="TYPE">'
    + '     </value>'
    + '     <value name="DELAY_MS">'
    + '         <shadow type="math_number">'
    + '             <field name="NUM">0</field>'
    + '         </shadow>'
    + '     </value>'
    + '     <value name="CLEAR_RUNNING">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['control_ex'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Words['control_ex'][systemLang]);

        this.appendValueInput('OID')
            .setCheck('String')
            .appendField(Blockly.Words['field_oid_OID'][systemLang]);

        this.appendDummyInput('TYPE')
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Words['control_ex_control'][systemLang],   'false'],
                [Blockly.Words['control_ex_update'][systemLang],    'true']
            ]), 'TYPE');

        this.appendValueInput('VALUE')
            .setCheck(null)
            .appendField(Blockly.Words['control_ex_value'][systemLang]);

        this.appendValueInput('DELAY_MS')
            .setCheck('Number')
            .appendField(Blockly.Words['control_ex_delay'][systemLang]);

        this.appendDummyInput('CLEAR_RUNNING_INPUT')
            .appendField(Blockly.Words['control_ex_clear_running'][systemLang])
            .appendField(new Blockly.FieldCheckbox(), 'CLEAR_RUNNING');

        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(Blockly.System.HUE);
        this.setTooltip(Blockly.Words['control_tooltip'][systemLang]);
        this.setHelpUrl(getHelp('control_help'));
    }
};

Blockly.JavaScript['control_ex'] = function(block) {
    var valueObjectID = Blockly.JavaScript.valueToCode(block, 'OID', Blockly.JavaScript.ORDER_ATOMIC);
    var value         = Blockly.JavaScript.valueToCode(block, 'VALUE', Blockly.JavaScript.ORDER_ATOMIC);
    var valueDelay    = Blockly.JavaScript.valueToCode(block, 'DELAY_MS', Blockly.JavaScript.ORDER_ATOMIC);
    var clearRunning  = block.getFieldValue('CLEAR_RUNNING') === 'TRUE';
    var type          = block.getFieldValue('TYPE') === 'true';
    return 'setStateDelayed(' + valueObjectID + ', ' + value + ', ' + type + ', parseInt(' + valueDelay + ', 10), ' + clearRunning + ');\n';
};

// --- create state --------------------------------------------------
Blockly.Words['create']         = {'en': 'create state',    'de': 'Zustand erzeugen',   'ru': 'создать состояние'};
Blockly.Words['create_jsState'] = {'en': 'jsState',         'de': 'jsState',            'ru': 'jsState'};
Blockly.Words['create_tooltip'] = {'en': 'create state',    'de': 'Zustand erzeugen',   'ru': 'создать состояние'};
Blockly.Words['create_help']    = {'en': 'createstate',     'de': 'createstate',        'ru': 'createstate'};

Blockly.System.blocks['create'] =
    '<block type="create">'
    + '     <value name="NAME">'
    + '     </value>'
    + '     <value name="STATEMENT">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['create'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Words['create'][systemLang]);

        this.appendDummyInput('NAME')
            .appendField(new Blockly.FieldTextInput(Blockly.Words['create_jsState'][systemLang]), 'NAME');

        this.appendStatementInput('STATEMENT')
            .setCheck(null);

        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);

        this.setInputsInline(true);
        this.setColour(Blockly.System.HUE);
        this.setTooltip(Blockly.Words['create_tooltip'][systemLang]);
        this.setHelpUrl(getHelp('create_help'));
    }
};

Blockly.JavaScript['create'] = function(block) {
    var name = block.getFieldValue('NAME');
    var statement = Blockly.JavaScript.statementToCode(block, 'STATEMENT');

    return 'createState("' + name + '", function () {\n' + statement + '});\n';
};

// --- get value --------------------------------------------------
Blockly.Words['get_value']         = {'en': 'Get state value',                  'de': 'Zustandswert nehmen',                'ru': 'Взять значение состояния'};
Blockly.Words['get_value_OID']     = {'en': 'of Object ID',                     'de': 'vom Objekt ID',                      'ru': 'у объекта'};
Blockly.Words['get_value_tooltip'] = {'en': 'Select object ID with dialog',     'de': 'Objekt ID mit Dialog selektieren',   'ru': 'Выбрать ID объекта'};
Blockly.Words['get_value_help']    = {'en': 'getstate',                         'de': 'getstate',                           'ru': 'getstate'};
Blockly.Words['get_value_default'] = {'en': 'select ID',                        'de': 'ID auswählen',                       'ru': 'Выбрать ID'};

Blockly.Words['get_value_val']     = {'en': 'Value',                            'de': 'Wert',                               'ru': 'Значение'};
Blockly.Words['get_value_ack']     = {'en': 'Acknowledge',                      'de': 'anerkannt',                          'ru': 'Подтверждение'};
Blockly.Words['get_value_ts']      = {'en': 'Timestamp',                        'de': 'Zeitstempel',                        'ru': 'Время'};
Blockly.Words['get_value_lc']      = {'en': 'Last change ',                     'de': 'Letze Änderung',                     'ru': 'Последнее изменеие'};
Blockly.Words['get_value_q']       = {'en': 'Quality',                          'de': 'Qualität',                           'ru': 'Качество'};
Blockly.Words['get_value_from']    = {'en': 'Source',                           'de': 'Quelle',                             'ru': 'Происхождение'};

Blockly.System.blocks['get_value'] =
    '<block type="get_value">'
    + '     <value name="ATTR">'
    + '     </value>'
    + '     <value name="OID">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['get_value'] = {
    // Checkbox.
    init: function() {

        this.appendDummyInput('ATTR')
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Words['get_value_val'][systemLang],    'val'],
                [Blockly.Words['get_value_ack'][systemLang],    'ack'],
                [Blockly.Words['get_value_ts'][systemLang],     'ts'],
                [Blockly.Words['get_value_lc'][systemLang],     'lc'],
                [Blockly.Words['get_value_q'][systemLang] ,     'q'],
                [Blockly.Words['get_value_from'][systemLang],   'from']
            ]), 'ATTR');

        this.appendDummyInput()
            .appendField(Blockly.Words['get_value_OID'][systemLang]);

        this.appendDummyInput()
            .appendField(new Blockly.FieldOID(Blockly.Words['get_value_default'][systemLang], main.initSelectId(), main.objects), 'OID');

        this.setInputsInline(true);
        this.setOutput(true);
        this.setColour(Blockly.System.HUE);
        this.setTooltip(Blockly.Words['get_value_tooltip'][systemLang]);
        this.setHelpUrl(getHelp('get_value_help'));
    }
};

Blockly.JavaScript['get_value'] = function(block) {
    var oid  = block.getFieldValue('OID');
    var attr = block.getFieldValue('ATTR');
    return ['getState("' + oid + '").' + attr, Blockly.JavaScript.ORDER_ATOMIC];
};

// --- select OID --------------------------------------------------
Blockly.Words['field_oid']         = {'en': 'Select OID',    'de': 'Zustand erzeugen',   'ru': 'создать состояние'};
Blockly.Words['field_oid_OID']     = {'en': 'Object ID',         'de': 'Objekt ID',            'ru': 'ID объекта'};
Blockly.Words['field_oid_tooltip'] = {'en': 'Select object ID with dialog',    'de': 'Objekt ID mit Dialog selektieren',   'ru': 'Выбрать ID объекта'};

Blockly.System.blocks['field_oid'] =
    '<block type="field_oid">'
    + '     <value name="TEXT">'
    + '     </value>'
    + '</block>';

Blockly.Blocks['field_oid'] = {
    // Checkbox.
    init: function() {

        this.appendDummyInput()
            .appendField(Blockly.Words['field_oid_OID'][systemLang]);

        this.appendDummyInput()
            .appendField(new Blockly.FieldOID('default', main.initSelectId(), main.objects), 'oid');

        this.setInputsInline(true);
        this.setColour(Blockly.System.HUE);
        this.setOutput(true, "String");
        this.setTooltip(Blockly.Words['field_oid_tooltip'][systemLang]);
    }
};

Blockly.JavaScript['field_oid'] = function(block) {
    var oid = block.getFieldValue('oid');
    return ['\'' + oid + '\'', Blockly.JavaScript.ORDER_ATOMIC]
};


text:
package org.apache.geode.cache;

import org.apache.geode.GemFireException;

/**
 * A generic exception, which indicates a cache error has occurred. All the other cache exceptions
 * are subclasses of this class. This class is abstract and therefore only subclasses are
 * instantiated.
 *
 *
 * @since GemFire 2.0
 */
public abstract class CacheException extends GemFireException {
  public static final long serialVersionUID = 7699432887938858940L;

  /** Constructs a new CacheException. */
  public CacheException() {
    super();
  }

  /** Constructs a new CacheException with a message string. */
  public CacheException(String s) {
    super(s);
  }

  /**
   * Constructs a CacheException with a message string and a base exception
   */
  public CacheException(String s, Throwable cause) {
    super(s, cause);
  }

  /** Constructs a CacheException with a cause */
  public CacheException(Throwable cause) {
    super(cause);
  }

  @Override
  public String toString() {
    String result = super.toString();
    Throwable cause = getCause();
    if (cause != null) {
      String causeStr = cause.toString();
      final String glue = ", caused by ";
      StringBuffer sb = new StringBuffer(result.length() + causeStr.length() + glue.length());
      sb.append(result).append(glue).append(causeStr);
      result = sb.toString();
    }
    return result;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package jodd.proxetta.data;

import jodd.proxetta.ProxyAdvice;
import jodd.proxetta.ProxyTarget;

public class FooProxyAdvice implements ProxyAdvice {

	static int count;

	public static int getCount() {
		return count++;
	}

	public Object execute() {
		return ProxyTarget.invoke();
	}
}


text:
require 'librarian'
require 'librarian/mock'

module Librarian
  describe Lockfile do

    let(:env) { Mock::Environment.new }

    before do
      env.registry :clear => true do
        source 'source-1' do
          spec 'alpha', '1.1'
        end
      end
    end

    let(:spec) do
      env.dsl do
        src 'source-1'
        dep 'alpha', '1.1'
      end
    end

    let(:resolver) { env.resolver }
    let(:resolution) { resolver.resolve(spec) }

    context "sanity" do
      context "the resolution" do
        subject { resolution }

        it { should be_correct }
        it { should have(1).manifests }
      end
    end

    describe "#save" do
      let(:lockfile) { env.ephemeral_lockfile }
      let(:lockfile_text) { lockfile.save(resolution) }

      context "just saving" do
        it "should return the lockfile text" do
          expect(lockfile_text).to_not be_nil
        end
      end

      context "saving and reloading" do
        let(:reloaded_resolution) { lockfile.load(lockfile_text) }

        it "should have the expected manifests" do
          expect(reloaded_resolution.manifests.count).to eq resolution.manifests.count
        end
      end

      context "bouncing" do
        let(:bounced_resolution) { lockfile.load(lockfile_text) }
        let(:bounced_lockfile_text) { lockfile.save(bounced_resolution) }

        it "should return the same lockfile text after bouncing as before bouncing" do
          expect(bounced_lockfile_text).to eq lockfile_text
        end
      end
    end

  end
end


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	//errorHandler = require('./errors.server.controller'),
	Bid = mongoose.model('Bid'),
	_ = require('lodash');

/**
 * Create a Bid
 */
exports.create = function(req, res) {
	var bid = new Bid(req.body);
	bid.user = req.user;

	bid.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(bid);
		}
	});
};

/**
 * Show the current Bid
 */
exports.read = function(req, res) {
	res.jsonp(req.bid);
};

/**
 * Update a Bid
 */
exports.update = function(req, res) {
	var bid = req.bid ;

	bid = _.extend(bid , req.body);

	bid.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(bid);
		}
	});
};

/**
 * Delete an Bid
 */
exports.delete = function(req, res) {
	var bid = req.bid ;

	bid.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(bid);
		}
	});
};

/**
 * List of Bids
 */
exports.list = function(req, res) {
	Bid.find().sort('-created').populate('owner', 'name').populate('player').populate('origOwner', 'name').exec(function(err, bids) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(bids);
		}
	});
};

/**
 * Bid middleware
 */
exports.bidByID = function(req, res, next, id) {
	Bid.findById(id).populate('user', 'displayName').exec(function(err, bid) {
		if (err) return next(err);
		if (! bid) return next(new Error('Failed to load Bid ' + id));
		req.bid = bid ;
		next();
	});
};

/**
 * Bid authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.bid.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
package org.apache.spark.sql.parser

import scala.collection.mutable
import scala.language.implicitConversions

import org.apache.spark.sql.{CarbonToSparkAdapter, DeleteRecords, UpdateTable}
import org.apache.spark.sql.catalyst.{CarbonDDLSqlParser, TableIdentifier}
import org.apache.spark.sql.catalyst.CarbonTableIdentifierImplicit._
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.execution.command._
import org.apache.spark.sql.execution.command.datamap.{CarbonCreateDataMapCommand, CarbonDataMapRebuildCommand, CarbonDataMapShowCommand, CarbonDropDataMapCommand}
import org.apache.spark.sql.execution.command.management._
import org.apache.spark.sql.execution.command.partition.{CarbonAlterTableDropPartitionCommand, CarbonAlterTableSplitPartitionCommand}
import org.apache.spark.sql.execution.command.schema.{CarbonAlterTableAddColumnCommand, CarbonAlterTableColRenameDataTypeChangeCommand, CarbonAlterTableDropColumnCommand}
import org.apache.spark.sql.execution.command.table.CarbonCreateTableCommand
import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.CarbonExpressions.CarbonUnresolvedRelation
import org.apache.spark.sql.catalyst.analysis.UnresolvedRelation
import org.apache.spark.sql.execution.command.stream.{CarbonCreateStreamCommand, CarbonDropStreamCommand, CarbonShowStreamsCommand}
import org.apache.spark.sql.util.CarbonException
import org.apache.spark.util.CarbonReflectionUtils

import org.apache.carbondata.api.CarbonStore.LOGGER
import org.apache.carbondata.common.exceptions.sql.MalformedCarbonCommandException
import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.spark.CarbonOption
import org.apache.carbondata.spark.util.{CarbonScalaUtil, CommonUtil}

/**
 * TODO remove the duplicate code and add the common methods to common class.
 * Parser for All Carbon DDL, DML cases in Unified context
 */
class CarbonSpark2SqlParser extends CarbonDDLSqlParser {

  override def parse(input: String): LogicalPlan = {
    synchronized {
      // Initialize the Keywords.
      initLexical
      phrase(start)(new lexical.Scanner(input)) match {
        case Success(plan, _) =>
          CarbonScalaUtil.cleanParserThreadLocals()
          plan match {
            case x: CarbonLoadDataCommand =>
              x.inputSqlString = input
              x
            case x: CarbonAlterTableCompactionCommand =>
              x.alterTableModel.alterSql = input
              x
            case logicalPlan => logicalPlan
        }
        case failureOrError =>
          CarbonScalaUtil.cleanParserThreadLocals()
          CarbonException.analysisException(failureOrError.toString)
      }
    }
  }

  protected lazy val start: Parser[LogicalPlan] = explainPlan | startCommand

  protected lazy val startCommand: Parser[LogicalPlan] =
    loadManagement | showLoads | alterTable | restructure | updateTable | deleteRecords |
    alterPartition | datamapManagement | alterTableFinishStreaming | stream | cli

  protected lazy val loadManagement: Parser[LogicalPlan] =
    deleteLoadsByID | deleteLoadsByLoadDate | cleanFiles | loadDataNew

  protected lazy val restructure: Parser[LogicalPlan] =
    alterTableColumnRenameAndModifyDataType | alterTableDropColumn | alterTableAddColumns

  protected lazy val alterPartition: Parser[LogicalPlan] =
    alterAddPartition | alterSplitPartition | alterDropPartition

  protected lazy val datamapManagement: Parser[LogicalPlan] =
    createDataMap | dropDataMap | showDataMap | refreshDataMap

  protected lazy val stream: Parser[LogicalPlan] =
    createStream | dropStream | showStreams

  protected lazy val alterAddPartition: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident ~ (ADD ~> PARTITION ~>
      "(" ~> repsep(stringLit, ",") <~ ")") <~ opt(";") ^^ {
      case dbName ~ table ~ addInfo =>
        val alterTableAddPartitionModel = AlterTableSplitPartitionModel(dbName, table, "0", addInfo)
        CarbonAlterTableSplitPartitionCommand(alterTableAddPartitionModel)
    }

  protected lazy val alterSplitPartition: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident ~ (SPLIT ~> PARTITION ~>
       "(" ~> numericLit <~ ")") ~ (INTO ~> "(" ~> repsep(stringLit, ",") <~ ")") <~ opt(";") ^^ {
      case dbName ~ table ~ partitionId ~ splitInfo =>
        val alterTableSplitPartitionModel =
          AlterTableSplitPartitionModel(dbName, table, partitionId, splitInfo)
        if (partitionId == 0) {
          sys.error("Please use [Alter Table Add Partition] statement to split default partition!")
        }
        CarbonAlterTableSplitPartitionCommand(alterTableSplitPartitionModel)
    }

  protected lazy val alterDropPartition: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident ~ (DROP ~> PARTITION ~>
      "(" ~> numericLit <~ ")") ~ (WITH ~> DATA).? <~ opt(";") ^^ {
      case dbName ~ table ~ partitionId ~ withData =>
        val dropWithData = withData.getOrElse("NO") match {
          case "NO" => false
          case _ => true
        }
        val alterTableDropPartitionModel =
          AlterTableDropPartitionModel(dbName, table, partitionId, dropWithData)
        CarbonAlterTableDropPartitionCommand(alterTableDropPartitionModel)
    }

  protected lazy val alterTable: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident ~ (COMPACT ~ stringLit) ~
      (WHERE ~> (SEGMENT ~ "." ~ ID) ~> IN ~> "(" ~> repsep(segmentId, ",") <~ ")").? <~
      opt(";") ^^ {
      case dbName ~ table ~ (compact ~ compactType) ~ segs =>
        val altertablemodel =
          AlterTableModel(convertDbNameToLowerCase(dbName), table, None, compactType,
          Some(System.currentTimeMillis()), null, segs)
        CarbonAlterTableCompactionCommand(altertablemodel)
    }

  /**
   * The below syntax is used to change the status of the segment
   * from "streaming" to "streaming finish".
   * ALTER TABLE tableName FINISH STREAMING
   */
  protected lazy val alterTableFinishStreaming: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident <~ FINISH <~ STREAMING <~ opt(";") ^^ {
      case dbName ~ table =>
        CarbonAlterTableFinishStreaming(dbName, table)
    }

  /**
   * The syntax of CREATE STREAM
   * CREATE STREAM [IF NOT EXISTS] streamName ON TABLE [dbName.]tableName
   * [STMPROPERTIES('KEY'='VALUE')]
   * AS SELECT COUNT(COL1) FROM tableName
   */
  protected lazy val createStream: Parser[LogicalPlan] =
    CREATE ~> STREAM ~>  opt(IF ~> NOT ~> EXISTS) ~ ident ~
    (ON ~> TABLE ~> (ident <~ ".").?) ~ ident ~
    (STMPROPERTIES ~> "(" ~> repsep(loadOptions, ",") <~ ")").? ~
    (AS ~> restInput) <~ opt(";") ^^ {
      case ifNotExists ~ streamName ~ dbName ~ tableName ~ options ~ query =>
        val optionMap = options.getOrElse(List[(String, String)]()).toMap[String, String]
        CarbonCreateStreamCommand(
          streamName, dbName, tableName, ifNotExists.isDefined, optionMap, query)
    }

  /**
   * The syntax of DROP STREAM
   * DROP STREAM [IF EXISTS] streamName
   */
  protected lazy val dropStream: Parser[LogicalPlan] =
    DROP ~> STREAM ~> opt(IF ~> EXISTS) ~ ident <~ opt(";") ^^ {
      case ifExists ~ streamName =>
        CarbonDropStreamCommand(streamName, ifExists.isDefined)
    }

  /**
   * The syntax of SHOW STREAMS
   * SHOW STREAMS [ON TABLE dbName.tableName]
   */
  protected lazy val showStreams: Parser[LogicalPlan] =
    SHOW ~> STREAMS ~> opt(ontable) <~ opt(";") ^^ {
      case tableIdent =>
        CarbonShowStreamsCommand(tableIdent)
    }

  /**
   * The syntax of datamap creation is as follows.
   * CREATE DATAMAP IF NOT EXISTS datamapName [ON TABLE tableName]
   * USING 'DataMapProviderName'
   * [WITH DEFERRED REBUILD]
   * DMPROPERTIES('KEY'='VALUE') AS SELECT COUNT(COL1) FROM tableName
   */
  protected lazy val createDataMap: Parser[LogicalPlan] =
    CREATE ~> DATAMAP ~> opt(IF ~> NOT ~> EXISTS) ~ ident ~
    opt(ontable) ~
    (USING ~> stringLit) ~
    opt(WITH ~> DEFERRED ~> REBUILD) ~
    (DMPROPERTIES ~> "(" ~> repsep(loadOptions, ",") <~ ")").? ~
    (AS ~> restInput).? <~ opt(";") ^^ {
      case ifnotexists ~ dmname ~ tableIdent ~ dmProviderName ~ deferred ~ dmprops ~ query =>
        val map = dmprops.getOrElse(List[(String, String)]()).toMap[String, String]
        CarbonCreateDataMapCommand(dmname, tableIdent, dmProviderName, map, query,
          ifnotexists.isDefined, deferred.isDefined)
    }

  protected lazy val ontable: Parser[TableIdentifier] =
    ON ~> TABLE ~>  (ident <~ ".").? ~ ident ^^ {
      case dbName ~ tableName =>
        TableIdentifier(tableName, dbName)
    }

  /**
   * The below syntax is used to drop the datamap.
   * DROP DATAMAP IF EXISTS datamapName ON TABLE tablename
   */
  protected lazy val dropDataMap: Parser[LogicalPlan] =
    DROP ~> DATAMAP ~> opt(IF ~> EXISTS) ~ ident ~ opt(ontable) <~ opt(";")  ^^ {
      case ifexists ~ dmname ~ tableIdent =>
        CarbonDropDataMapCommand(dmname, ifexists.isDefined, tableIdent)
    }

  /**
   * The syntax of show datamap is used to show datamaps on the table
   * SHOW DATAMAP ON TABLE tableName
   */
  protected lazy val showDataMap: Parser[LogicalPlan] =
    SHOW ~> DATAMAP ~> opt(ontable) <~ opt(";") ^^ {
      case tableIdent =>
        CarbonDataMapShowCommand(tableIdent)
    }

  /**
   * The syntax of show datamap is used to show datamaps on the table
   * REBUILD DATAMAP datamapname [ON TABLE] tableName
   */
  protected lazy val refreshDataMap: Parser[LogicalPlan] =
    REBUILD ~> DATAMAP ~> ident ~ opt(ontable) <~ opt(";") ^^ {
      case datamap ~ tableIdent =>
        CarbonDataMapRebuildCommand(datamap, tableIdent)
    }

  protected lazy val deleteRecords: Parser[LogicalPlan] =
    (DELETE ~> FROM ~> aliasTable) ~ restInput.? <~ opt(";") ^^ {
      case table ~ rest =>
        val tableName = getTableName(table._2)
        val relation: LogicalPlan = table._3 match {
          case Some(a) =>
            DeleteRecords(
              "select tupleId from " + tableName + " " + table._3.getOrElse("")
                + rest.getOrElse(""),
              Some(table._3.get),
              table._1)
          case None =>
            DeleteRecords(
              "select tupleId from " + tableName + " " + rest.getOrElse(""),
              None,
              table._1)
        }
        relation
    }

  protected lazy val updateTable: Parser[LogicalPlan] =
    UPDATE ~> aliasTable ~
    (SET ~> "(" ~> repsep(element, ",") <~ ")") ~
    ("=" ~> restInput) <~ opt(";") ^^ {
      case tab ~ columns ~ rest =>
        val (sel, where) = splitQuery(rest)
        val (selectStmt, relation) =
          if (!sel.toLowerCase.startsWith("select ")) {
            if (sel.trim.isEmpty) {
              sys.error("At least one source column has to be specified ")
            }
            // only list of expression are given, need to convert that list of expressions into
            // select statement on destination table
            val relation : UnresolvedRelation = tab._1 match {
              case r@CarbonUnresolvedRelation(tableIdentifier) =>
                tab._3 match {
                  case Some(a) => updateRelation(r, tableIdentifier, tab._4, Some(tab._3.get))
                  case None => updateRelation(r, tableIdentifier, tab._4, None)
                }
              case _ => tab._1
            }

            tab._3 match {
              case Some(a) =>
                ("select " + sel + " from " + getTableName(tab._2) + " " + tab._3.get, relation)
              case None =>
                ("select " + sel + " from " + getTableName(tab._2), relation)
            }

          } else {
            (sel, updateRelation(tab._1, tab._2, tab._4, tab._3))
          }
        val rel = tab._3 match {
          case Some(a) => UpdateTable(relation, columns, selectStmt, Some(tab._3.get), where)
          case None => UpdateTable(relation,
            columns,
            selectStmt,
            Some(tab._1.tableIdentifier.table),
            where)
        }
        rel
    }

  private def updateRelation(
      r: UnresolvedRelation,
      tableIdent: Seq[String],
      tableIdentifier: TableIdentifier,
      alias: Option[String]): UnresolvedRelation = {
    alias match {
      case Some(_) => r
      case _ =>
        val tableAlias = tableIdent match {
          case Seq(dbName, tableName) => Some(tableName)
          case Seq(tableName) => Some(tableName)
        }
        // Use Reflection to choose between Spark2.1 and Spark2.2
        // Move UnresolvedRelation(tableIdentifier, tableAlias) to reflection.
        CarbonReflectionUtils.getUnresolvedRelation(tableIdentifier, tableAlias)
    }
  }

  protected lazy val element: Parser[String] =
    (ident <~ ".").? ~ ident ^^ {
      case table ~ column => column.toLowerCase
    }

  protected lazy val table: Parser[UnresolvedRelation] = {
    rep1sep(attributeName, ".") ~ opt(ident) ^^ {
      case tableIdent ~ alias => UnresolvedRelation(tableIdent)
    }
  }

  protected lazy val aliasTable: Parser[(UnresolvedRelation, List[String], Option[String],
    TableIdentifier)] = {
    rep1sep(attributeName, ".") ~ opt(ident) ^^ {
      case tableIdent ~ alias =>

        val tableIdentifier: TableIdentifier = toTableIdentifier(tableIdent)

        // Use Reflection to choose between Spark2.1 and Spark2.2
        // Move (UnresolvedRelation(tableIdent, alias), tableIdent, alias) to reflection.
        val unresolvedRelation = CarbonReflectionUtils.getUnresolvedRelation(tableIdentifier, alias)

        (unresolvedRelation, tableIdent, alias, tableIdentifier)
    }
  }

  private def splitQuery(query: String): (String, String) = {
    val stack = scala.collection.mutable.Stack[Char]()
    var foundSingleQuotes = false
    var foundDoubleQuotes = false
    var foundEscapeChar = false
    var ignoreChar = false
    var stop = false
    var bracketCount = 0
    val (selectStatement, where) = query.span {
      ch => {
        if (stop) {
          false
        } else {
          ignoreChar = false
          if (foundEscapeChar && (ch == '\'' || ch == '\"' || ch == '\\')) {
            foundEscapeChar = false
            ignoreChar = true
          }
          // If escaped single or double quotes found, no need to consider
          if (!ignoreChar) {
            if (ch == '\\') {
              foundEscapeChar = true
            } else if (ch == '\'') {
              foundSingleQuotes = !foundSingleQuotes
            } else if (ch == '\"') {
              foundDoubleQuotes = !foundDoubleQuotes
            }
            else if (ch == '(' && !foundSingleQuotes && !foundDoubleQuotes) {
              bracketCount = bracketCount + 1
              stack.push(ch)
            } else if (ch == ')' && !foundSingleQuotes && !foundDoubleQuotes) {
              bracketCount = bracketCount + 1
              stack.pop()
              if (0 == stack.size) {
                stop = true
              }
            }
          }
          true
        }
      }
    }
    if (bracketCount == 0 || bracketCount % 2 != 0) {
      sys.error("Parsing error, missing bracket ")
    }
    val select = selectStatement.trim
    select.substring(1, select.length - 1).trim -> where.trim
  }

  protected lazy val attributeName: Parser[String] = acceptMatch("attribute name", {
    case lexical.Identifier(str) => str.toLowerCase
    case lexical.Keyword(str) if !lexical.delimiters.contains(str) => str.toLowerCase
  })

  private def getTableName(tableIdentifier: Seq[String]): String = {
    if (tableIdentifier.size > 1) {
      tableIdentifier.head + "." + tableIdentifier(1)
    } else {
      tableIdentifier.head
    }
  }

  protected lazy val loadDataNew: Parser[LogicalPlan] =
    LOAD ~> DATA ~> opt(LOCAL) ~> INPATH ~> stringLit ~ opt(OVERWRITE) ~
    (INTO ~> TABLE ~> (ident <~ ".").? ~ ident) ~
    (PARTITION ~>"("~> repsep(partitions, ",") <~ ")").? ~
    (OPTIONS ~> "(" ~> repsep(loadOptions, ",") <~ ")").? <~ opt(";") ^^ {
      case filePath ~ isOverwrite ~ table ~ partitions ~ optionsList =>
        val (databaseNameOp, tableName) = table match {
          case databaseName ~ tableName => (databaseName, tableName.toLowerCase())
        }
        if (optionsList.isDefined) {
          validateOptions(optionsList)
        }
        val optionsMap = optionsList.getOrElse(List.empty[(String, String)]).toMap
        val partitionSpec = partitions.getOrElse(List.empty[(String, Option[String])]).toMap
        CarbonLoadDataCommand(
          databaseNameOp = convertDbNameToLowerCase(databaseNameOp),
          tableName = tableName,
          factPathFromUser = filePath,
          dimFilesPath = Seq(),
          options = optionsMap,
          isOverwriteTable = isOverwrite.isDefined,
          inputSqlString = null,
          dataFrame = None,
          updateModel = None,
          tableInfoOp = None,
          internalOptions = Map.empty,
          partition = partitionSpec)
    }

  protected lazy val deleteLoadsByID: Parser[LogicalPlan] =
    DELETE ~> FROM ~ TABLE ~> (ident <~ ".").? ~ ident ~
    (WHERE ~> (SEGMENT ~ "." ~ ID) ~> IN ~> "(" ~> repsep(segmentId, ",")) <~ ")" ~
    opt(";") ^^ {
      case dbName ~ tableName ~ loadids =>
        CarbonDeleteLoadByIdCommand(loadids, dbName, tableName.toLowerCase())
    }

  protected lazy val deleteLoadsByLoadDate: Parser[LogicalPlan] =
    DELETE ~> FROM ~> TABLE ~> (ident <~ ".").? ~ ident ~
    (WHERE ~> (SEGMENT ~ "." ~ STARTTIME ~> BEFORE) ~ stringLit) <~
    opt(";") ^^ {
      case database ~ table ~ condition =>
        condition match {
          case dateField ~ dateValue =>
            CarbonDeleteLoadByLoadDateCommand(convertDbNameToLowerCase(database),
              table.toLowerCase(),
              dateField,
              dateValue)
        }
    }

  protected lazy val cleanFiles: Parser[LogicalPlan] =
    CLEAN ~> FILES ~> FOR ~> TABLE ~> (ident <~ ".").? ~ ident <~ opt(";") ^^ {
      case databaseName ~ tableName =>
        CarbonCleanFilesCommand(
          convertDbNameToLowerCase(databaseName),
          Option(tableName.toLowerCase()))
    }

  protected lazy val explainPlan: Parser[LogicalPlan] =
    (EXPLAIN ~> opt(EXTENDED)) ~ startCommand ^^ {
      case isExtended ~ logicalPlan =>
        logicalPlan match {
          case _: CarbonCreateTableCommand =>
            ExplainCommand(logicalPlan, extended = isExtended.isDefined)
          case _ => CarbonToSparkAdapter.getExplainCommandObj
        }
    }

  protected lazy val showLoads: Parser[LogicalPlan] =
    (SHOW ~> opt(HISTORY) <~ SEGMENTS <~ FOR <~ TABLE) ~ (ident <~ ".").? ~ ident ~
    (LIMIT ~> numericLit).? <~
    opt(";") ^^ {
      case showHistory ~ databaseName ~ tableName ~ limit =>
        CarbonShowLoadsCommand(
          convertDbNameToLowerCase(databaseName), tableName.toLowerCase(), limit,
          showHistory.isDefined)
    }

  protected lazy val cli: Parser[LogicalPlan] =
    (CARBONCLI ~> FOR ~> TABLE) ~> (ident <~ ".").? ~ ident ~
    (OPTIONS ~> "(" ~> commandOptions <~ ")").? <~
    opt(";") ^^ {
      case databaseName ~ tableName ~ commandList =>
        var commandOptions: String = null
        if (commandList.isDefined) {
          commandOptions = commandList.get
        }
        CarbonCliCommand(
          convertDbNameToLowerCase(databaseName),
          tableName.toLowerCase(),
          commandOptions)
    }

  protected lazy val alterTableColumnRenameAndModifyDataType: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident ~ CHANGE ~ ident ~ ident ~
    ident ~ opt("(" ~> rep1sep(valueOptions, ",") <~ ")") <~ opt(";") ^^ {
      case dbName ~ table ~ change ~ columnName ~ columnNameCopy ~ dataType ~ values =>

        var isColumnRename = false
        // If both the column name are not same, then its a call for column rename
        if (!columnName.equalsIgnoreCase(columnNameCopy)) {
          isColumnRename = true
        }
        val alterTableColRenameAndDataTypeChangeModel =
          AlterTableDataTypeChangeModel(parseDataType(dataType.toLowerCase,
            values,
            isColumnRename),
            convertDbNameToLowerCase(dbName),
            table.toLowerCase,
            columnName.toLowerCase,
            columnNameCopy.toLowerCase,
            isColumnRename)
        CarbonAlterTableColRenameDataTypeChangeCommand(alterTableColRenameAndDataTypeChangeModel)
    }

  protected lazy val alterTableAddColumns: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident ~
    (ADD ~> COLUMNS ~> "(" ~> repsep(anyFieldDef, ",") <~ ")") ~
    (TBLPROPERTIES ~> "(" ~> repsep(loadOptions, ",") <~ ")").? <~ opt(";") ^^ {
      case dbName ~ table ~ fields ~ tblProp =>
        fields.foreach{ f =>
          if (isComplexDimDictionaryExclude(f.dataType.get)) {
            throw new MalformedCarbonCommandException(
              s"Add column is unsupported for complex datatype column: ${f.column}")
          }
        }
        val tableProps = if (tblProp.isDefined) {
          tblProp.get.groupBy(_._1.toLowerCase).foreach(f =>
            if (f._2.size > 1) {
              val name = f._1.toLowerCase
              val colName = name.substring(14)
              if (name.startsWith("default.value.") &&
                  fields.count(p => p.column.equalsIgnoreCase(colName)) == 1) {
                sys.error(s"Duplicate default value exist for new column: ${ colName }")
              }
            }
          )
          // default value should not be converted to lower case
          val tblProps = tblProp.get
            .map(f => if (CarbonCommonConstants.TABLE_BLOCKSIZE.equalsIgnoreCase(f._1) ||
                          CarbonCommonConstants.SORT_COLUMNS.equalsIgnoreCase(f._1) ||
                          CarbonCommonConstants.LOCAL_DICTIONARY_ENABLE.equalsIgnoreCase(f._1) ||
                          CarbonCommonConstants.LOCAL_DICTIONARY_THRESHOLD.equalsIgnoreCase(f._1)) {
              throw new MalformedCarbonCommandException(
                s"Unsupported Table property in add column: ${ f._1 }")
            } else if (f._1.toLowerCase.startsWith("default.value.")) {
              if (fields.count(field => checkFieldDefaultValue(field.column,
                f._1.toLowerCase)) == 1) {
                 f._1 -> f._2
            } else {
                 throw new MalformedCarbonCommandException(
                   s"Default.value property does not matches with the columns in ALTER command. " +
                     s"Column name in property is: ${ f._1}")
               }
            } else {
              f._1 -> f._2.toLowerCase
            })
          scala.collection.mutable.Map(tblProps: _*)
        } else {
          scala.collection.mutable.Map.empty[String, String]
        }

        val tableModel = prepareTableModel (false,
          convertDbNameToLowerCase(dbName),
          table.toLowerCase,
          fields.map(convertFieldNamesToLowercase),
          Seq.empty,
          tableProps,
          None,
          true)

        val alterTableAddColumnsModel = AlterTableAddColumnsModel(
          convertDbNameToLowerCase(dbName),
          table,
          tableProps.toMap,
          tableModel.dimCols,
          tableModel.msrCols,
          tableModel.highcardinalitydims.getOrElse(Seq.empty))
        CarbonAlterTableAddColumnCommand(alterTableAddColumnsModel)
    }

  private def checkFieldDefaultValue(fieldName: String, defaultValueColumnName: String): Boolean = {
    defaultValueColumnName.equalsIgnoreCase("default.value." + fieldName)
  }

  private def convertFieldNamesToLowercase(field: Field): Field = {
    val name = field.column.toLowerCase
    field.copy(column = name, name = Some(name))
  }
  protected lazy val alterTableDropColumn: Parser[LogicalPlan] =
    ALTER ~> TABLE ~> (ident <~ ".").? ~ ident ~ DROP ~ COLUMNS ~
    ("(" ~> rep1sep(ident, ",") <~ ")") <~ opt(";") ^^ {
      case dbName ~ table ~ drop ~ columns ~ values =>
        // validate that same column name is not repeated
        values.map(_.toLowerCase).groupBy(identity).collect {
          case (x, ys) if ys.lengthCompare(1) > 0 =>
            throw new MalformedCarbonCommandException(s"$x is duplicate. Duplicate columns not " +
                                                      s"allowed")
        }
        val alterTableDropColumnModel = AlterTableDropColumnModel(convertDbNameToLowerCase(dbName),
          table.toLowerCase,
          values.map(_.toLowerCase))
        CarbonAlterTableDropColumnCommand(alterTableDropColumnModel)
    }

  def getFields(schema: Seq[StructField]): Seq[Field] = {
    schema.map { col =>
      var columnComment: String = ""
      var plainComment: String = ""
      if (col.getComment().isDefined) {
        columnComment = " comment \"" + col.getComment().get + "\""
        plainComment = col.getComment().get
      }
      val x =
        if (col.dataType.catalogString == "float") {
          '`' + col.name + '`' + " double" + columnComment
        } else {
          '`' + col.name + '`' + ' ' + col.dataType.catalogString + columnComment
        }
      val f: Field = anyFieldDef(new lexical.Scanner(x.toLowerCase))
      match {
        case Success(field, _) => field.asInstanceOf[Field]
        case failureOrError => throw new MalformedCarbonCommandException(
          s"Unsupported data type: ${ col.dataType }")
      }
      // the data type of the decimal type will be like decimal(10,0)
      // so checking the start of the string and taking the precision and scale.
      // resetting the data type with decimal
      if (f.dataType.getOrElse("").startsWith("decimal")) {
        val (precision, scale) = CommonUtil.getScaleAndPrecision(col.dataType.catalogString)
        f.precision = precision
        f.scale = scale
        f.dataType = Some("decimal")
      }
      if (f.dataType.getOrElse("").startsWith("char")) {
        f.dataType = Some("char")
      }
      else if (f.dataType.getOrElse("").startsWith("float")) {
        f.dataType = Some("double")
      }
      f.rawSchema = x
      f.columnComment = plainComment
      f
    }
  }

  def addPreAggFunction(sql: String): String = {
    addPreAgg(new lexical.Scanner(sql.toLowerCase)) match {
      case Success(query, _) => query
      case _ =>
        throw new MalformedCarbonCommandException(s"Unsupported query")
    }
  }

  def addPreAggLoadFunction(sql: String): String = {
    addPreAggLoad(new lexical.Scanner(sql.toLowerCase)) match {
      case Success(query, _) => query
      case _ =>
        throw new MalformedCarbonCommandException(s"Unsupported query")
    }
  }

  def getBucketFields(
      properties: mutable.Map[String, String],
      fields: Seq[Field],
      options: CarbonOption): Option[BucketFields] = {
    if (!CommonUtil.validateTblProperties(properties,
      fields)) {
      throw new MalformedCarbonCommandException("Invalid table properties")
    }
    if (options.isBucketingEnabled) {
      if (options.bucketNumber.toString.contains("-") ||
          options.bucketNumber.toString.contains("+") ||  options.bucketNumber == 0) {
        throw new MalformedCarbonCommandException("INVALID NUMBER OF BUCKETS SPECIFIED")
      }
      else {
        Some(BucketFields(options.bucketColumns.toLowerCase.split(",").map(_.trim),
          options.bucketNumber))
      }
    } else {
      None
    }
  }
}


text:
Ti=Grant of Rights

1.=[GH/FutureCommerce/ULOM/Bryan/Sec/Grant_Exclusivity_v0.md]

2.Ti=Sublicenses

3.Ti=Scope of Grant

4.Ti=Implied Rights and other Restrictions

=[Z/ol/4]


text:
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Animator))]
public class Player : Actor
{
    public float restartLevelDelay = 1f;
    public int pointsPerFood = 10;
    public int pointsPerSoda = 20;
    public int wallDamage = 1;
    public int enemyDamage = 1;
    public Text healthText;

    public AudioClip[] moveSounds;
    public AudioClip[] drinkSounds;
    public AudioClip[] eatSounds;

    private Animator animator;
    private int health;

    // Use this for initialization
    protected override void Start()
    {
        animator = GetComponent<Animator>();
        health = GameManager.instance.playerHealth;
        base.Start();

        // TODO: This should be handled by a UI layer
        healthText.text = "Health " + health;
    }

    private void OnDisable()
    {
        // Store health across level loads
        GameManager.instance.playerHealth = health;
    }

    // Update is called once per frame
    void Update()
    {
        if (!GameManager.instance.playersTurn)
        {
            return;
        }

        int horizontal = (int)Input.GetAxisRaw("Horizontal");
        int vertical = (int)Input.GetAxisRaw("Vertical");

        // Only allow movement in a cardinal direction
        if (horizontal != 0)
        {
            vertical = 0;
        }

        if (horizontal != 0 || vertical != 0)
        {
            // Attempt to move
            AttemptMove(horizontal, vertical);
        }
    }

    protected override bool AttemptMove(int xDir, int yDir)
    {
        health--;
        healthText.text = "Health " + health;
        CheckIfGameOver(true);

        bool canMove = base.AttemptMove(xDir, yDir);

        if (canMove)
        {
            SoundManager.Instance.PlayRandom(drinkSounds);
        }

        GameManager.instance.playersTurn = false;
        return canMove;
    }

    protected override void OnCollide(GameObject hitObject)
    {
        if (hitObject.tag == "Wall")
        {
            Wall hitWall = hitObject.GetComponent<Wall>();
            hitWall.DamageWall(wallDamage);
            animator.SetTrigger("PlayerChop");
        }
        else if (hitObject.tag == "Enemy")
        {
            Enemy hitEnemy = hitObject.GetComponent<Enemy>();
            hitEnemy.LoseHealth(enemyDamage);
            animator.SetTrigger("PlayerChop");
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Exit")
        {
            Invoke("OnExit", restartLevelDelay);
            enabled = false;
        }
        else if (other.tag == "Food")
        {
            health += pointsPerFood;
            healthText.text = "+" + pointsPerFood + "! Health " + health;
            other.gameObject.SetActive(false);
            SoundManager.Instance.PlayRandom(eatSounds);
        }
        else if (other.tag == "Soda")
        {
            health += pointsPerSoda;
            healthText.text = "+" + pointsPerSoda + "! Health " + health;
            other.gameObject.SetActive(false);
            SoundManager.Instance.PlayRandom(drinkSounds);
        }
    }

    private void OnExit()
    {
        GameManager.instance.NextLevel();
    }

    public void LoseHealth(int loss)
    {
        animator.SetTrigger("PlayerHit");
        health -= loss;
        healthText.text = "-" + loss + "! Health " + health;
        CheckIfGameOver(false);
    }

    private void CheckIfGameOver(bool starved)
    {
        if (health <= 0)
        {
            GameManager.instance.GameOver(starved);
        }
    }
}


text:
package nestapp.websocketserver

import akka.actor.{Actor, ActorLogging, Props}
import spray.can.Http

/**
  * Actor which acts as simple WebSocketServer
  * For documentation look spray.io and spray-websocket
  */

class WebSocketServer extends Actor with ActorLogging {
  def receive = {
    // when a new connection comes in we register a WebSocketConnection actor as the per connection handler
    case Http.Connected(remoteAddress, localAddress) =>
      val serverConnection = sender()
      val conn = context.actorOf(Props(classOf[WebSocketWorker], serverConnection))
      serverConnection ! Http.Register(conn)
    case PushToChildren(msg: String) =>
      val children = context.children
      println("pushing to all children : " + msg)
      children.foreach(ref => ref ! Push(msg))
  }
}


text:
'use strict';

var ReactTools = require('react-tools');

module.exports = {
  process: ReactTools.transform
};


text:
module Fog
  module Vsphere
    class Compute
      class Real
        def vm_reconfig_cpus(options = {})
          raise ArgumentError, 'cpus is a required parameter' unless options.key? 'cpus'
          raise ArgumentError, 'instance_uuid is a required parameter' unless options.key? 'instance_uuid'
          hardware_spec = { 'numCPUs' => options['cpus'], 'numCoresPerSocket' => options['corespersocket'] }
          vm_reconfig_hardware('instance_uuid' => options['instance_uuid'], 'hardware_spec' => hardware_spec)
        end
      end

      class Mock
        def vm_reconfig_cpus(options = {})
          raise ArgumentError, 'cpus is a required parameter' unless options.key? 'cpus'
          raise ArgumentError, 'instance_uuid is a required parameter' unless options.key? 'instance_uuid'
          hardware_spec = { 'numCPUs' => options['cpus'], 'numCoresPerSocket' => options['corespersocket'] }
          vm_reconfig_hardware('instance_uuid' => options['instance_uuid'], 'hardware_spec' => hardware_spec)
        end
      end
    end
  end
end


text:
var assert = require('assert')
  , Mongoose = require('mongoose')
  , common = require('./support/common')
  , db = common.db
  , DNode = require('dnode')
  , Backbone = require('backbone')
  , _ = require('underscore')._
  , CRUD = require(__dirname + '/../lib/crud')
  , middleware = require(__dirname + '/../browser/dnode.backbone')

// Settings
var port = 9999
  , Schema = Mongoose.Schema
  , ObjectId = Schema.ObjectId
  , server
  , BlogPost
  , Blog
  , Model

// Mongoose schema
BlogSchema = new Schema({
  title: String
, count: Number
})
Blog = Mongoose.model('blog', BlogSchema)

// Backbone model
Model = Backbone.Model.extend({
  type: 'blog'
, sync: _.sync
, url: 'blogtest'
, idAttribute: '_id'
})

// Backbone collection
Collection = Backbone.Collection.extend({
  model: Model
, type: 'blog'
, sync: _.sync
, url: 'blogtest'
})

// Create DNode server
server = DNode()
  .use(CRUD({
    database: db
  }))
  .listen(port)

describe('CRUD', function() {

  before(function () {
    Blog.remove(function (err) {
      assert.strictEqual(err, null)
    })
  })

  var apple = new Model()
  var fruits = new Collection()
  var blog = new Blog({
    title: 'raw'
  , count: 1337
  })

  var remote
    , connection

  // CRUD testing
  it('should inject the CRUD middleware', function(done) {
    DNode()
      .use(middleware())
      .use(function(client, conn) {
        remote = client
        connection = conn
        assert.strictEqual(typeof this.created, 'function')
        assert.strictEqual(typeof this.read, 'function')
        assert.strictEqual(typeof this.updated, 'function')
        assert.strictEqual(typeof this.deleted, 'function')
        assert.strictEqual(typeof this.subscribed, 'function')
        assert.strictEqual(typeof this.unsubscribed, 'function')

        conn.on('ready', function() {
          assert.strictEqual(typeof conn.remote.create, 'function')
          assert.strictEqual(typeof conn.remote.read, 'function')
          assert.strictEqual(typeof conn.remote.update, 'function')
          assert.strictEqual(typeof conn.remote.delete, 'function')
          done()
        })
      })
      .connect(port)
  })

  // Creation test
  it('should create a new backbone model', function(done) {
    apple.save({
      title: 'creating'
    , count: 42
    }, {
      finished: function() {
        assert.strictEqual(typeof apple.get('title'), 'string')
        assert.strictEqual(typeof apple.get('count'), 'number')
        assert.strictEqual(apple.get('title'), 'creating')
        assert.strictEqual(apple.get('count'), 42)
        done()
      }
    , error: function(model, resp) { done(new Error(resp)) }
    })
  })

  // Updating test
  it('should update the record', function(done) {
    apple.save({ title: 'updating' }, {
      finished: function() {
        assert.strictEqual(apple.get('title'), 'updating')
        done()
      }
    , error: function(model, resp) { done(new Error(resp)) }
    })
  })

  it('should have manually created a record', function(done) {
    blog.save(function(err) {
      assert.strictEqual(err, null)
      done(err)
    })
  })

  // Read / fetching test
  it('should read all records', function(done) {
    fruits.fetch({
      success: function(model, resp) {
        assert.deepEqual(Object.prototype.toString.call(resp), '[object Array]')
        assert.equal(resp.length, 2)
        done()
      }
    , error: function(model, resp) { done(new Error(resp)) }
    })
  })

  it('should delete the record', function(done) {
    var l = fruits.length
      , x = 0

    var finished = function() {
      x += 1
      if (x === l) return done()
    }

    fruits.each(function(model) {
      model.destroy({
        finished: finished
      , error: function(model, resp) { done(new Error(resp)) }
      })
    })
  })

  it('should find no records', function(done) {
    fruits.fetch({
      success: function(model, resp) {
        assert.deepEqual(Object.prototype.toString.call(resp), '[object Array]')
        assert.equal(resp.length, 0)
        done()
      }
    , error: function(model, resp) { done(new Error(resp)) }
    })
  })

  it('should disconnect from DNode', function(done) {
    connection.on('end', function() {
      done()
    })
    connection.end()
  })
})


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

          <title>Controller - play.api.mvc.Controller</title>
          <meta name="description" content="Controller - play.api.mvc.Controller" />
          <meta name="keywords" content="Controller play.api.mvc.Controller" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

play.api.mvc

Controller

        trait

        Controller extends Results with BodyParsers with Status with HeaderNames with ContentTypes with RequestExtractors with Rendering

Defines utility methods to generate Action and Results types.

For example:

object Application extends Controller {

def hello(name:String) = Action { request =>
  Ok("Hello " + name)
}

}

Source

Controller.scala

          Linear Supertypes

Rendering, RequestExtractors, AcceptExtractors, ContentTypes, HeaderNames, http.Status, BodyParsers, Results, AnyRef, Any

          Known Subclasses

Assets, AssetsBuilder, Default, ExternalAssets

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By inheritance

                Inherited

Controller

Rendering

RequestExtractors

AcceptExtractors

ContentTypes

HeaderNames

Status

BodyParsers

Results

AnyRef

Any

Hide All

Show all

            Learn more about member selection

            Visibility

Public

All

Type Members

        class

        Status extends SimpleResult[EmptyContent]

Generates default SimpleResult from a content type, headers and content.

Value Members

        final
        def

        !=(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        object

        &

Convenient extractor allowing to apply two extractors.

        final
        def

        ==(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

Any

        val

        ACCEPT: String

Definition Classes

HeaderNames

        val

        ACCEPTED: Int

Definition Classes

Status

        val

        ACCEPT_CHARSET: String

Definition Classes

HeaderNames

        val

        ACCEPT_ENCODING: String

Definition Classes

HeaderNames

        val

        ACCEPT_LANGUAGE: String

Definition Classes

HeaderNames

        val

        ACCEPT_RANGES: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_ALLOW_CREDENTIALS: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_ALLOW_HEADERS: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_ALLOW_METHODS: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_ALLOW_ORIGIN: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_EXPOSE_HEADERS: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_MAX_AGE: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_REQUEST_HEADERS: String

Definition Classes

HeaderNames

        val

        ACCESS_CONTROL_REQUEST_METHOD: String

Definition Classes

HeaderNames

        val

        AGE: String

Definition Classes

HeaderNames

        val

        ALLOW: String

Definition Classes

HeaderNames

        val

        AUTHORIZATION: String

Definition Classes

HeaderNames

        val

        Accepted: Status

Generates a '202 ACCEPTED' result.

Generates a '202 ACCEPTED' result.

Definition Classes

Results

        object

        Accepts

Common extractors to check if a request accepts JSON, Html, etc.

        def

        Async(promise: Future[Result]): AsyncResult

Definition Classes

Results

        val

        BAD_GATEWAY: Int

Definition Classes

Status

        val

        BAD_REQUEST: Int

Definition Classes

Status

        val

        BINARY: String

Content-Type of binary data.

Content-Type of binary data.

Definition Classes

ContentTypes

        val

        BadGateway: Status

Generates a '502 BAD_GATEWAY' result.

Generates a '502 BAD_GATEWAY' result.

Definition Classes

Results

        val

        BadRequest: Status

Generates a '400 BAD_REQUEST' result.

Generates a '400 BAD_REQUEST' result.

Definition Classes

Results

        val

        CACHE_CONTROL: String

Definition Classes

HeaderNames

        val

        CONFLICT: Int

Definition Classes

Status

        val

        CONNECTION: String

Definition Classes

HeaderNames

        val

        CONTENT_DISPOSITION: String

Definition Classes

HeaderNames

        val

        CONTENT_ENCODING: String

Definition Classes

HeaderNames

        val

        CONTENT_LANGUAGE: String

Definition Classes

HeaderNames

        val

        CONTENT_LENGTH: String

Definition Classes

HeaderNames

        val

        CONTENT_LOCATION: String

Definition Classes

HeaderNames

        val

        CONTENT_MD5: String

Definition Classes

HeaderNames

        val

        CONTENT_RANGE: String

Definition Classes

HeaderNames

        val

        CONTENT_TRANSFER_ENCODING: String

Definition Classes

HeaderNames

        val

        CONTENT_TYPE: String

Definition Classes

HeaderNames

        val

        CONTINUE: Int

Definition Classes

Status

        val

        COOKIE: String

Definition Classes

HeaderNames

        val

        CREATED: Int

Definition Classes

Status

        def

        CSS(implicit codec: Codec): String

Content-Type of css.

Content-Type of css.

Definition Classes

ContentTypes

        val

        Conflict: Status

Generates a '409 CONFLICT' result.

Generates a '409 CONFLICT' result.

Definition Classes

Results

        val

        Created: Status

Generates a '201 CREATED' result.

Generates a '201 CREATED' result.

Definition Classes

Results

        val

        DATE: String

Definition Classes

HeaderNames

        val

        ETAG: String

Definition Classes

HeaderNames

        def

        EVENT_STREAM(implicit codec: Codec): String

Content-Type of server sent events.

Content-Type of server sent events.

Definition Classes

ContentTypes

        val

        EXPECT: String

Definition Classes

HeaderNames

        val

        EXPECTATION_FAILED: Int

Definition Classes

Status

        val

        EXPIRES: String

Definition Classes

HeaderNames

        val

        EntityTooLarge: Status

Generates a '413 REQUEST_ENTITY_TOO_LARGE' result.

Generates a '413 REQUEST_ENTITY_TOO_LARGE' result.

Definition Classes

Results

        val

        ExpectationFailed: Status

Generates a '417 EXPECTATION_FAILED' result.

Generates a '417 EXPECTATION_FAILED' result.

Definition Classes

Results

        val

        FAILED_DEPENDENCY: Int

Definition Classes

Status

        val

        FORBIDDEN: Int

Definition Classes

Status

        def

        FORM(implicit codec: Codec): String

Content-Type of form-urlencoded.

Content-Type of form-urlencoded.

Definition Classes

ContentTypes

        val

        FOUND: Int

Definition Classes

Status

        val

        FROM: String

Definition Classes

HeaderNames

        val

        FailedDependency: Status

Generates a '424 FAILED_DEPENDENCY' result.

Generates a '424 FAILED_DEPENDENCY' result.

Definition Classes

Results

        val

        Forbidden: Status

Generates a '403 FORBIDDEN' result.

Generates a '403 FORBIDDEN' result.

Definition Classes

Results

        def

        Found(url: String): SimpleResult[EmptyContent]

Generates a '302 FOUND' simple result.

Generates a '302 FOUND' simple result.

url

the URL to redirect to

Definition Classes

Results

        val

        GATEWAY_TIMEOUT: Int

Definition Classes

Status

        val

        GONE: Int

Definition Classes

Status

        val

        GatewayTimeout: Status

Generates a '504 GATEWAY_TIMEOUT' result.

Generates a '504 GATEWAY_TIMEOUT' result.

Definition Classes

Results

        val

        Gone: Status

Generates a '410 GONE' result.

Generates a '410 GONE' result.

Definition Classes

Results

        val

        HOST: String

Definition Classes

HeaderNames

        def

        HTML(implicit codec: Codec): String

Content-Type of html.

Content-Type of html.

Definition Classes

ContentTypes

        val

        HTTP_VERSION_NOT_SUPPORTED: Int

Definition Classes

Status

        val

        HttpVersionNotSupported: Status

Generates a '505 HTTP_VERSION_NOT_SUPPORTED' result.

Generates a '505 HTTP_VERSION_NOT_SUPPORTED' result.

Definition Classes

Results

        val

        IF_MATCH: String

Definition Classes

HeaderNames

        val

        IF_MODIFIED_SINCE: String

Definition Classes

HeaderNames

        val

        IF_NONE_MATCH: String

Definition Classes

HeaderNames

        val

        IF_RANGE: String

Definition Classes

HeaderNames

        val

        IF_UNMODIFIED_SINCE: String

Definition Classes

HeaderNames

        val

        INSUFFICIENT_STORAGE: Int

Definition Classes

Status

        val

        INTERNAL_SERVER_ERROR: Int

Definition Classes

Status

        val

        InsufficientStorage: Status

Generates a '507 INSUFFICIENT_STORAGE' result.

Generates a '507 INSUFFICIENT_STORAGE' result.

Definition Classes

Results

        val

        InternalServerError: Status

Generates a '500 INTERNAL_SERVER_ERROR' result.

Generates a '500 INTERNAL_SERVER_ERROR' result.

Definition Classes

Results

        def

        JAVASCRIPT(implicit codec: Codec): String

Content-Type of javascript.

Content-Type of javascript.

Definition Classes

ContentTypes

        def

        JSON(implicit codec: Codec): String

Content-Type of json.

Content-Type of json.

Definition Classes

ContentTypes

        val

        LAST_MODIFIED: String

Definition Classes

HeaderNames

        val

        LENGTH_REQUIRED: Int

Definition Classes

Status

        val

        LOCATION: String

Definition Classes

HeaderNames

        val

        LOCKED: Int

Definition Classes

Status

        val

        Locked: Status

Generates a '423 LOCKED' result.

Generates a '423 LOCKED' result.

Definition Classes

Results

        val

        MAX_FORWARDS: String

Definition Classes

HeaderNames

        val

        METHOD_NOT_ALLOWED: Int

Definition Classes

Status

        val

        MOVED_PERMANENTLY: Int

Definition Classes

Status

        val

        MULTIPLE_CHOICES: Int

Definition Classes

Status

        val

        MULTI_STATUS: Int

Definition Classes

Status

        val

        MethodNotAllowed: Status

Generates a '405 METHOD_NOT_ALLOWED' result.

Generates a '405 METHOD_NOT_ALLOWED' result.

Definition Classes

Results

        def

        MovedPermanently(url: String): SimpleResult[EmptyContent]

Generates a '301 MOVED_PERMANENTLY' simple result.

Generates a '301 MOVED_PERMANENTLY' simple result.

url

the URL to redirect to

Definition Classes

Results

        val

        MultiStatus: Status

Generates a '207 MULTI_STATUS' result.

Generates a '207 MULTI_STATUS' result.

Definition Classes

Results

        val

        NON_AUTHORITATIVE_INFORMATION: Int

Definition Classes

Status

        val

        NOT_ACCEPTABLE: Int

Definition Classes

Status

        val

        NOT_FOUND: Int

Definition Classes

Status

        val

        NOT_IMPLEMENTED: Int

Definition Classes

Status

        val

        NOT_MODIFIED: Int

Definition Classes

Status

        val

        NO_CONTENT: Int

Definition Classes

Status

        val

        NoContent: SimpleResult[EmptyContent]

Generates a '204 NO_CONTENT' result.

Generates a '204 NO_CONTENT' result.

Definition Classes

Results

        val

        NonAuthoritativeInformation: Status

Generates a '203 NON_AUTHORITATIVE_INFORMATION' result.

Generates a '203 NON_AUTHORITATIVE_INFORMATION' result.

Definition Classes

Results

        val

        NotAcceptable: Status

Generates a '406 NOT_ACCEPTABLE' result.

Generates a '406 NOT_ACCEPTABLE' result.

Definition Classes

Results

        val

        NotFound: Status

Generates a '404 NOT_FOUND' result.

Generates a '404 NOT_FOUND' result.

Definition Classes

Results

        val

        NotImplemented: Status

Generates a '501 NOT_IMPLEMENTED' result.

Generates a '501 NOT_IMPLEMENTED' result.

Definition Classes

Results

        val

        NotModified: SimpleResult[EmptyContent]

Generates a '304 NOT_MODIFIED' result.

Generates a '304 NOT_MODIFIED' result.

Definition Classes

Results

        val

        OK: Int

Definition Classes

Status

        val

        ORIGIN: String

Definition Classes

HeaderNames

        val

        Ok: Status

Generates a '200 OK' result.

Generates a '200 OK' result.

Definition Classes

Results

        val

        PARTIAL_CONTENT: Int

Definition Classes

Status

        val

        PAYMENT_REQUIRED: Int

Definition Classes

Status

        val

        PRAGMA: String

Definition Classes

HeaderNames

        val

        PRECONDITION_FAILED: Int

Definition Classes

Status

        val

        PROXY_AUTHENTICATE: String

Definition Classes

HeaderNames

        val

        PROXY_AUTHENTICATION_REQUIRED: Int

Definition Classes

Status

        val

        PROXY_AUTHORIZATION: String

Definition Classes

HeaderNames

        val

        PartialContent: Status

Generates a '206 PARTIAL_CONTENT' result.

Generates a '206 PARTIAL_CONTENT' result.

Definition Classes

Results

        val

        PreconditionFailed: Status

Generates a '412 PRECONDITION_FAILED' result.

Generates a '412 PRECONDITION_FAILED' result.

Definition Classes

Results

        val

        RANGE: String

Definition Classes

HeaderNames

        val

        REFERER: String

Definition Classes

HeaderNames

        val

        REQUESTED_RANGE_NOT_SATISFIABLE: Int

Definition Classes

Status

        val

        REQUEST_ENTITY_TOO_LARGE: Int

Definition Classes

Status

        val

        REQUEST_TIMEOUT: Int

Definition Classes

Status

        val

        REQUEST_URI_TOO_LONG: Int

Definition Classes

Status

        val

        RESET_CONTENT: Int

Definition Classes

Status

        val

        RETRY_AFTER: String

Definition Classes

HeaderNames

        def

        Redirect(call: Call): SimpleResult[EmptyContent]

Generates a redirect simple result.

Generates a redirect simple result.

call

Call defining the URL to redirect to, which typically comes from the reverse router

Definition Classes

Results

        def

        Redirect(url: String, queryString: Map[String, Seq[String]] = Map.empty, status: Int = SEE_OTHER): SimpleResult[EmptyContent]

Generates a redirect simple result.

Generates a redirect simple result.

url

the URL to redirect to

queryString

queryString parameters to add to the queryString

status

HTTP status

Definition Classes

Results

        def

        Redirect(url: String, status: Int): SimpleResult[EmptyContent]

Generates a redirect simple result.

Generates a redirect simple result.

url

the URL to redirect to

status

HTTP status

Definition Classes

Results

        val

        RequestTimeout: Status

Generates a '408 REQUEST_TIMEOUT' result.

Generates a '408 REQUEST_TIMEOUT' result.

Definition Classes

Results

        val

        ResetContent: SimpleResult[EmptyContent]

Generates a '205 RESET_CONTENT' result.

Generates a '205 RESET_CONTENT' result.

Definition Classes

Results

        val

        SEE_OTHER: Int

Definition Classes

Status

        val

        SERVER: String

Definition Classes

HeaderNames

        val

        SERVICE_UNAVAILABLE: Int

Definition Classes

Status

        val

        SET_COOKIE: String

Definition Classes

HeaderNames

        val

        SET_COOKIE2: String

Definition Classes

HeaderNames

        val

        SWITCHING_PROTOCOLS: Int

Definition Classes

Status

        def

        SeeOther(url: String): SimpleResult[EmptyContent]

Generates a '303 SEE_OTHER' simple result.

Generates a '303 SEE_OTHER' simple result.

url

the URL to redirect to

Definition Classes

Results

        val

        ServiceUnavailable: Status

Generates a '503 SERVICE_UNAVAILABLE' result.

Generates a '503 SERVICE_UNAVAILABLE' result.

Definition Classes

Results

        def

        Status(code: Int): Status

Generates a simple result.

Generates a simple result.

code

the status code

Definition Classes

Results

        val

        TE: String

Definition Classes

HeaderNames

        val

        TEMPORARY_REDIRECT: Int

Definition Classes

Status

        def

        TEXT(implicit codec: Codec): String

Content-Type of text.

Content-Type of text.

Definition Classes

ContentTypes

        val

        TODO: Action[AnyContent]

Provides an empty Action implementation: the result is a standard 'Not implemented yet' result page.

Provides an empty Action implementation: the result is a standard 'Not implemented yet' result page.

For example:

def index(name:String) = TODO

        val

        TOO_MANY_REQUEST: Int

Definition Classes

Status

        val

        TRAILER: String

Definition Classes

HeaderNames

        val

        TRANSFER_ENCODING: String

Definition Classes

HeaderNames

        def

        TemporaryRedirect(url: String): SimpleResult[EmptyContent]

Generates a '307 TEMPORARY_REDIRECT' simple result.

Generates a '307 TEMPORARY_REDIRECT' simple result.

url

the URL to redirect to

Definition Classes

Results

        val

        TooManyRequest: Status

Generates a '429 TOO_MANY_REQUEST' result.

Generates a '429 TOO_MANY_REQUEST' result.

Definition Classes

Results

        val

        UNAUTHORIZED: Int

Definition Classes

Status

        val

        UNPROCESSABLE_ENTITY: Int

Definition Classes

Status

        val

        UNSUPPORTED_MEDIA_TYPE: Int

Definition Classes

Status

        val

        UPGRADE: String

Definition Classes

HeaderNames

        val

        USER_AGENT: String

Definition Classes

HeaderNames

        val

        USE_PROXY: Int

Definition Classes

Status

        val

        Unauthorized: Status

Generates a '401 UNAUTHORIZED' result.

Generates a '401 UNAUTHORIZED' result.

Definition Classes

Results

        val

        UnprocessableEntity: Status

Generates a '422 UNPROCESSABLE_ENTITY' result.

Generates a '422 UNPROCESSABLE_ENTITY' result.

Definition Classes

Results

        val

        UnsupportedMediaType: Status

Generates a '415 UNSUPPORTED_MEDIA_TYPE' result.

Generates a '415 UNSUPPORTED_MEDIA_TYPE' result.

Definition Classes

Results

        val

        UriTooLong: Status

Generates a '414 REQUEST_URI_TOO_LONG' result.

Generates a '414 REQUEST_URI_TOO_LONG' result.

Definition Classes

Results

        val

        VARY: String

Definition Classes

HeaderNames

        val

        VIA: String

Definition Classes

HeaderNames

        val

        WARNING: String

Definition Classes

HeaderNames

        val

        WWW_AUTHENTICATE: String

Definition Classes

HeaderNames

        def

        XML(implicit codec: Codec): String

Content-Type of xml.

Content-Type of xml.

Definition Classes

ContentTypes

        val

        X_FORWARDED_FOR: String

Definition Classes

HeaderNames

        val

        X_FORWARDED_HOST: String

Definition Classes

HeaderNames

        val

        X_FORWARDED_PORT: String

Definition Classes

HeaderNames

        val

        X_FORWARDED_PROTO: String

Definition Classes

HeaderNames

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws()

        implicit
        def

        flash(implicit request: RequestHeader): Flash

Retrieve the flash scope implicitly from the request.

Retrieve the flash scope implicitly from the request.

For example:

def index(name:String) = Action { implicit request =>
val message = flash("message")
Ok("Got " + message)
}

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        implicit
        def

        lang(implicit request: RequestHeader): Lang

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        object

        parse

Default body parsers.

        def

        render(f: PartialFunction[MediaRange, Result])(implicit request: RequestHeader): Result

Tries to render the most acceptable result according to the request's Accept header value.

Tries to render the most acceptable result according to the request's Accept header value.

render {
case Accepts.Html() => Ok(views.html.show(value))
case Accepts.Json() => Ok(Json.toJson(value))
}

f

A partial function returning a Result for a given request media range

returns

A result provided by f, if it is defined for the current request media ranges, otherwise NotAcceptable

Definition Classes

Rendering

        implicit
        def

        session(implicit request: RequestHeader): Session

Retrieves the session implicitly from the request.

Retrieves the session implicitly from the request.

For example:

def index(name:String) = Action { implicit request =>
val username = session("username")
Ok("Hello " + username)
}

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toString(): String

Definition Classes

AnyRef → Any

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws()

        def

        withCharset(mimeType: String)(implicit codec: Codec): String

returns

the codec charset appended to mimeType

Definition Classes

ContentTypes

Inherited from Rendering

Inherited from RequestExtractors

Inherited from AcceptExtractors

Inherited from ContentTypes

Inherited from HeaderNames

Inherited from http.Status

Inherited from BodyParsers

Inherited from Results

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
<?php if (!defined('PmWiki')) exit();

##   Some recipes do page updates outside of the built-in posting
##   cycle, so $EnableBlocklistImmediate is used to determine if
##   we need to catch these.  Currently this defaults to enabled,
##   but at some point we may change the default to disabled.
if (IsEnabled($EnableBlocklistImmediate, 1)) {
  SDVA($BlocklistActions, array('comment' => 1));
  if (isset($_POST['text']) && @$BlocklistActions[$action]) {
    Blocklist($pagename, $_POST['text']);
    if (!$EnablePost) {
      unset($_POST['post']);
      unset($_POST['postattr']);
      unset($_POST['postedit']);
    }
  }
}

##   If $EnableBlocklist is set to 10 or higher, then arrange to
##   periodically download the "chongqed" and "moinmaster" blacklists.
if ($EnableBlocklist >= 10) {
#  SDVA($BlocklistDownload['SiteAdmin.Blocklist-Chongqed'], array(
#    'url' => 'http://blacklist.chongqed.org/',
#    'format' => 'regex'));
  SDVA($BlocklistDownload['SiteAdmin.Blocklist-MoinMaster'], array(
    'url' => 'http://moinmo.in/BadContent?action=raw',
    'format' => 'regex'));
}

##   CheckBlocklist is inserted into $EditFunctions, to automatically
##   check for blocks on anything being posted through the normal
##   "update a page cycle"
array_unshift($EditFunctions, 'CheckBlocklist');
function CheckBlocklist($pagename, &$page, &$new) {
  StopWatch("CheckBlocklist: begin $pagename");
  $ptext = implode('', @$_POST);
  if (@$ptext) Blocklist($pagename, $ptext);
  StopWatch("CheckBlocklist: end $pagename");
}

##   Blocklist is the function that does all of the work of
##   checking for reasons to block a posting.  It reads
##   the available blocklist pages ($BlocklistPages) and
##   builds an array of strings and regular expressiongs to
##   be checked against the page; if any are found, then
##   posting is blocked (via $EnablePost=0).  The function
##   also checks the REMOTE_ADDR against any blocked IP addresses.
function Blocklist($pagename, $text) {
  global $BlocklistPages, $BlockedMessagesFmt, $BlocklistDownload,
    $BlocklistDownloadRefresh, $Now, $EnablePost, $WhyBlockedFmt,
    $MessagesFmt, $BlocklistMessageFmt, $EnableWhyBlocked, $IsBlocked;

  StopWatch("Blocklist: begin $pagename");

  $BlocklistDownload = (array)@$BlocklistDownload;
  SDV($BlocklistPages,
    array_merge(array('$SiteAdminGroup.Blocklist',
                      '$SiteAdminGroup.Blocklist-Farm'),
                array_keys($BlocklistDownload)));
  SDV($BlocklistMessageFmt, "
$[This post has been blocked by the administrator]
");
  SDVA($BlockedMessagesFmt, array(
    'ip' => '$[Address blocked from posting]: ',
    'text' => '$[Text blocked from posting]: '));
  SDV($BlocklistDownloadRefresh, 86400);

  ##  Loop over all blocklist pages
  foreach((array)$BlocklistPages as $b) {

    ##  load the current blocklist page
    $pn = FmtPageName($b, $pagename);
    $page = ReadPage($pn, READPAGE_CURRENT);
    if (!$page) continue;

    ##  if the page being checked is a blocklist page, stop blocking
    if ($pagename == $pn) return;

    ##  If the blocklist page is managed by automatic download,
    ##  schedule any new downloads here
    if (@$BlocklistDownload[$pn]) {
      $bd = &$BlocklistDownload[$pn];
      SDVA($bd, array(
        'refresh' => $BlocklistDownloadRefresh,
        'url' => "http://www.pmwiki.org/blocklists/$pn" ));
      if (!@$page['text'] || $page['time'] < $Now - $bd['refresh'])
        register_shutdown_function('BlocklistDownload', $pn, getcwd());
    }

    ##  If the blocklist is simply a list of regexes to be matched, load
    ##  them into $terms['block'] and continue to the next blocklist page.
    ##  Some regexes from remote sites aren't well-formed, so we have
    ##  to escape any slashes that aren't already escaped.
    if (strpos(@$page['text'], 'blocklist-format: regex') !==false) {
      if (preg_match_all('/^([^\\s#].+)/m', $page['text'], $match))
        foreach($match[0] as $m) {
          $m = preg_replace('#(?<!\\\\)/#', '\\/', trim($m));
          $terms['block'][] = "/$m/";
        }
      continue;
    }

    ##  Treat the page as a pmwiki-format blocklist page, with
    ##  IP addresses and "block:"-style declarations.  First, see
    ##  if we need to block the author based on a.b.c.d or a.b.c.*
    ##  IP addresses.
    $ip = preg_quote($_SERVER['REMOTE_ADDR']);
    $ip = preg_replace('/\\d+$/', '($0\\b|\\*)', $ip);
    if (preg_match("/\\b$ip/", @$page['text'], $match)) {
      $EnablePost = 0;
      $IsBlocked = 1;
      $WhyBlockedFmt[] = $BlockedMessagesFmt['ip'] . $match[0];
    }

    ##  Now we'll load any "block:" or "unblock:" specifications
    ##  from the page text.
    if (preg_match_all('/(un)?(?:block|regex):(.*)/', @$page['text'],
                       $match, PREG_SET_ORDER))
      foreach($match as $m) $terms[$m[1].'block'][] = trim($m[2]);
  }

  ##  okay, we've loaded all of the terms, now subtract any 'unblock'
  ##  terms from the block set.
  StopWatch("Blocklist: diff unblock");
  $blockterms = array_diff((array)@$terms['block'], (array)@$terms['unblock']);

  ##  go through each of the remaining blockterms and see if it matches the
  ##  text -- if so, disable posting and add a message to $WhyBlockedFmt.
  StopWatch('Blocklist: blockterms (count='.count($blockterms).')');
  $itext = strtolower($text);
  foreach($blockterms as $b) {
    if ($b{0} == '/') {
      if (!preg_match($b, $text)) continue;
    } else if (strpos($itext, strtolower($b)) === false) continue;
    $EnablePost = 0;
    $IsBlocked = 1;
    $WhyBlockedFmt[] = $BlockedMessagesFmt['text'] . $b;
  }
  StopWatch('Blocklist: blockterms done');

  ##  If we came across any reasons to block, let's provide a message
  ##  to the author that it was blocked.  If $EnableWhyBlocked is set,
  ##  we'll even tell the author why.  :-)
  if (@$WhyBlockedFmt) {
    $MessagesFmt[] = $BlocklistMessageFmt;
    if (IsEnabled($EnableWhyBlocked, 0))
      foreach((array)$WhyBlockedFmt as $why)
        $MessagesFmt[] = "
$why
\n";
  }
  StopWatch("Blocklist: end $pagename");
}

##   BlocklistDownload() handles retrieving blocklists from
##   external sources into PmWiki pages.  If it's able to
##   download an updated list, it uses that; otherwise it leaves
##   any existing list alone.
function BlocklistDownload($pagename, $dir = '') {
  global $BlocklistDownloadFmt, $BlocklistDownload, $FmtV;

  if ($dir) { flush(); chdir($dir); }
  SDV($BlocklistDownloadFmt, "
  [@
## blocklist-note:   NOTE: This page is automatically generated by blocklist.php
## blocklist-note:   NOTE: Any edits to this page may be lost!
## blocklist-url:    \$BlocklistDownloadUrl
## blocklist-when:   \$CurrentTimeISO
#  blocklist-format: \$BlocklistFormat
\$BlocklistData
  @]
");

  ##  get the existing blocklist page
  $bd = &$BlocklistDownload[$pagename];
  $page = ReadPage($pagename, READPAGE_CURRENT);

  ##  try to retrieve the remote data
  $blocklistdata = @file($bd['url']);

  ##  if we didn't get it, and we don't already have text, save a
  ##  note in the page so we know what happened
  if (!$blocklistdata && !@$page['text']) {
    $auf = ini_get('allow_url_fopen');
    $blocklistdata = "#### Unable to download blocklist (allow_url_fopen=$auf)";
  }

  ##  if we have some new text to save, let's format it and save it
  if ($blocklistdata) {
    $blocklistdata = implode('', (array)$blocklistdata);
    $blocklistdata = preg_replace('/^##blocklist.*/m', '', $blocklistdata);
    $FmtV['$BlocklistData'] = $blocklistdata;
    $FmtV['$BlocklistDownloadUrl'] = $bd['url'];
    $FmtV['$BlocklistFormat'] = $bd['format'];
    $page['text'] = FmtPageName($BlocklistDownloadFmt, $pagename);
    SDV($page['passwdread'], '@lock');
  }

  ##  save our updated(?) blocklist page
  WritePage($pagename, $page);
}


text:
import { AbstractAbiTest } from "./abi-test";
import { TestCase } from "./test";
export declare class Eip712Test extends AbstractAbiTest<TestCase.Eip712> {
    generateTest(): TestCase.Eip712;
}