text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2004 Brent Cook                                        |
// +----------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or        |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This library is distributed in the hope that it will be useful,      |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// |                                                                      |
// | You should have received a copy of the GNU Lesser General Public     |
// | License along with this library; if not, write to the Free Software  |
// | Foundation, Inc., 59 Temple Place, Suite 330,Boston,MA 02111-1307 USA|
// +----------------------------------------------------------------------+
// | Authors: Brent Cook <busterbcook@yahoo.com>                          |
// |          Jason Pell <jasonpell@hotmail.com>                          |
// |          Lauren Matheson <inan@canada.com>                           |
// |          John Griffin <jgriffin316@netscape.net>                     |
// +----------------------------------------------------------------------+
//
// $Id: Parser.php,v 1.23 2004/05/11 05:09:02 busterb Exp $
//

require_once 'PEAR.php';
require_once 'SQL/Lexer.php';

/**
 * A sql parser
 *
 * @author  Brent Cook <busterbcook@yahoo.com>
 * @version 0.5
 * @access  public
 * @package SQL_Parser
 */
class SQL_Parser
{
    var $lexer;
    var $token;

// symbol definitions
    var $functions = array();
    var $types = array();
    var $symbols = array();
    var $operators = array();
    var $synonyms = array();

    var $dialects = array("ANSI", "MySQL");

// {{{ function SQL_Parser($string = null)
    function SQL_Parser($string = null, $dialect = "ANSI") {
        $this->setDialect($dialect);

        if (is_string($string)) {
            $this->lexer = new Lexer($string, 1);
            $this->lexer->symbols =& $this->symbols;
        }
    }
// }}}

// {{{ function setDialect($dialect)
    function setDialect($dialect) {
        if (in_array($dialect, $this->dialects)) {
            include 'SQL/Dialect_'.$dialect.'.php';
            $this->types = array_flip($dialect['types']);
            $this->functions = array_flip($dialect['functions']);
            $this->operators = array_flip($dialect['operators']);
            $this->commands = array_flip($dialect['commands']);
            $this->synonyms = $dialect['synonyms'];
            $this->symbols = array_merge(
                $this->types,
                $this->functions,
                $this->operators,
                $this->commands,
                array_flip($dialect['reserved']),
                array_flip($dialect['conjunctions']));
        } else {
            return $this->raiseError('Unknown SQL dialect:'.$dialect);
        }
    }
// }}}

// {{{ getParams(&$values, &$types)
    function getParams(&$values, &$types) {
        $values = array();
        $types = array();
        while ($this->token != ')') {
            $this->getTok();
            if ($this->isVal() || ($this->token == 'ident')) {
                $values[] = $this->lexer->tokText;
                $types[] = $this->token;
            } elseif ($this->token == ')') {
                return false;
            } else {
                return $this->raiseError('Expected a value');
            }
            $this->getTok();
            if (($this->token != ',') && ($this->token != ')')) {
                return $this->raiseError('Expected , or )');
            }
        }
    }
// }}}

    // {{{ raiseError($message)
    function raiseError($message) {
        $end = 0;
        if ($this->lexer->string != '') {
            while (($this->lexer->lineBegin+$end < $this->lexer->stringLen)
               && ($this->lexer->string{$this->lexer->lineBegin+$end} != "\n")){
                ++$end;
            }
        }

        $message = 'Parse error: '.$message.' on line '.
            ($this->lexer->lineNo+1)."\n";
        $message .= substr($this->lexer->string, $this->lexer->lineBegin, $end)."\n";
        $length = is_null($this->token) ? 0 : strlen($this->lexer->tokText);
        $message .= str_repeat(' ', abs($this->lexer->tokPtr -
                               $this->lexer->lineBegin - $length))."^";
        $message .= ' found: "'.$this->lexer->tokText.'"';

        return PEAR::raiseError($message);
    }
    // }}}

    // {{{ isType()
    function isType() {
        return isset($this->types[$this->token]);
    }
    // }}}

    // {{{ isVal()
    function isVal() {
       return (($this->token == 'real_val') ||
               ($this->token == 'int_val') ||
               ($this->token == 'text_val') ||
               ($this->token == 'null'));
    }
    // }}}

    // {{{ isFunc()
    function isFunc() {
        return isset($this->functions[$this->token]);
    }
    // }}}

    // {{{ isCommand()
    function isCommand() {
        return isset($this->commands[$this->token]);
    }
    // }}}

    // {{{ isReserved()
    function isReserved() {
        return isset($this->symbols[$this->token]);
    }
    // }}}

    // {{{ isOperator()
    function isOperator() {
        return isset($this->operators[$this->token]);
    }
    // }}}

    // {{{ getTok()
    function getTok() {
        $this->token = $this->lexer->lex();
        //echo $this->token."\t".$this->lexer->tokText."\n";
    }
    // }}}

    // {{{ &parseFieldOptions()
    function parseFieldOptions()
    {
        // parse field options
        $namedConstraint = false;
        $options = array();
        while (($this->token != ',') && ($this->token != ')') &&
                ($this->token != null)) {
            $option = $this->token;
            $haveValue = true;
            switch ($option) {
                case 'constraint':
                    $this->getTok();
                    if ($this->token = 'ident') {
                        $constraintName = $this->lexer->tokText;
                        $namedConstraint = true;
                        $haveValue = false;
                    } else {
                        return $this->raiseError('Expected a constraint name');
                    }
                    break;
                case 'default':
                    $this->getTok();
                    if ($this->isVal()) {
                        $constraintOpts = array('type'=>'default_value',
                                                'value'=>$this->lexer->tokText);
                    } elseif ($this->isFunc()) {
                        $results = $this->parseFunctionOpts();
                        if (PEAR::isError($results)) {
                            return $results;
                        }
                        $results['type'] = 'default_function';
                        $constraintOpts = $results;
                    } else {
                        return $this->raiseError('Expected default value');
                    }
                    break;
                case 'primary':
                    $this->getTok();
                    if ($this->token == 'key') {
                        $constraintOpts = array('type'=>'primary_key',
                                                'value'=>true);
                    } else {
                        return $this->raiseError('Expected "key"');
                    }
                    break;
                case 'not':
                    $this->getTok();
                    if ($this->token == 'null') {
                        $constraintOpts = array('type'=>'not_null',
                                                'value' => true);
                    } else {
                        return $this->raiseError('Expected "null"');
                    }
                    break;
                case 'check':
                    $this->getTok();
                    if ($this->token != '(') {
                        return $this->raiseError('Expected (');
                    }
                    $results = $this->parseSearchClause();
                    if (PEAR::isError($results)) {
                        return $results;
                    }
                    $results['type'] = 'check';
                    $constraintOpts = $results;
                    if ($this->token != ')') {
                        return $this->raiseError('Expected )');
                    }
                    break;
                case 'unique':
                    $this->getTok();
                    if ($this->token != '(') {
                        return $this->raiseError('Expected (');
                    }
                    $constraintOpts = array('type'=>'unique');
                    $this->getTok();
                    while ($this->token != ')') {
                        if ($this->token != 'ident') {
                            return $this->raiseError('Expected an identifier');
                        }
                        $constraintOpts['column_names'][] = $this->lexer->tokText;
                        $this->getTok();
                        if (($this->token != ')') && ($this->token != ',')) {
                            return $this->raiseError('Expected ) or ,');
                        }
                    }
                    if ($this->token != ')') {
                        return $this->raiseError('Expected )');
                    }
                    break;
                case 'month': case 'year': case 'day': case 'hour':
                case 'minute': case 'second':
                    $intervals = array(
                                    array('month'=>0,
                                          'year'=>1),
                                    array('second'=>0,
                                          'minute'=>1,
                                          'hour'=>2,
                                          'day'=>3));
                    foreach ($intervals as $class) {
                        if (isset($class[$option])) {
                            $constraintOpts = array('quantum_1'=>$this->token);
                            $this->getTok();
                            if ($this->token == 'to') {
                                $this->getTok();
                                if (!isset($class[$this->token])) {
                                    return $this->raiseError(
                                        'Expected interval quanta');
                                }
                                if ($class[$this->token] >=
                                    $class[$constraintOpts['quantum_1']]) {
                                    return $this->raiseError($this->token.
                                        ' is not smaller than '.
                                        $constraintOpts['quantum_1']);
                                }
                                $constraintOpts['quantum_2'] = $this->token;
                            } else {
                                $this->lexer->unget();
                            }
                            break;
                        }
                    }
                    if (!isset($constraintOpts['quantum_1'])) {
                        return $this->raiseError('Expected interval quanta');
                    }
                    $constraintOpts['type'] = 'values';
                    break;
                case 'null':
                    $haveValue = false;
                    break;
                default:
                    return $this->raiseError('Unexpected token '
                                        .$this->lexer->tokText);
            }
            if ($haveValue) {
                if ($namedConstraint) {
                    $options['constraints'][$constraintName] = $constraintOpts;
                    $namedConstraint = false;
                } else {
                    $options['constraints'][] = $constraintOpts;
                }
            }
            $this->getTok();
        }
        return $options;
    }
    // }}}

    // {{{ parseSearchClause()
    function parseSearchClause($subSearch = false)
    {
        $clause = array();
        // parse the first argument
        $this->getTok();
        if ($this->token == 'not') {
            $clause['neg'] = true;
            $this->getTok();
        }

        $foundSubclause = false;
        if ($this->token == '(') {
            $clause['arg_1']['value'] = $this->parseSearchClause(true);
            $clause['arg_1']['type'] = 'subclause';
            if ($this->token != ')') {
                return $this->raiseError('Expected ")"');
            }
            $foundSubclause = true;
        } else if ($this->isReserved()) {
            return $this->raiseError('Expected a column name or value');
        } else {
            $clause['arg_1']['value'] = $this->lexer->tokText;
            $clause['arg_1']['type'] = $this->token;
        }

        // parse the operator
        if (!$foundSubclause) {
            $this->getTok();
            if (!$this->isOperator()) {
                return $this->raiseError('Expected an operator');
            }
            $clause['op'] = $this->token;

            $this->getTok();
            switch ($clause['op']) {
                case 'is':
                    // parse for 'is' operator
                    if ($this->token == 'not') {
                        $clause['neg'] = true;
                        $this->getTok();
                    }
                    if ($this->token != 'null') {
                        return $this->raiseError('Expected "null"');
                    }
                    $clause['arg_2']['value'] = '';
                    $clause['arg_2']['type'] = $this->token;
                    break;
                case 'not':
                    // parse for 'not in' operator
                    if ($this->token != 'in') {
                        return $this->raiseError('Expected "in"');
                    }
                    $clause['op'] = $this->token;
                    $clause['neg'] = true;
                    $this->getTok();
                case 'in':
                    // parse for 'in' operator
                    if ($this->token != '(') {
                        return $this->raiseError('Expected "("');
                    }

                    // read the subset
                    $this->getTok();
                    // is this a subselect?
                    if ($this->token == 'select') {
                        $clause['arg_2']['value'] = $this->parseSelect(true);
                        $clause['arg_2']['type'] = 'command';
                    } else {
                        $this->lexer->pushBack();
                        // parse the set
                        $result = $this->getParams($clause['arg_2']['value'],
                                                $clause['arg_2']['type']);
                        if (PEAR::isError($result)) {
                            return $result;
                        }
                    }
                    if ($this->token != ')') {
                        return $this->raiseError('Expected ")"');
                    }
                    break;
                case 'and': case 'or':
                    $this->lexer->unget();
                    break;
                default:
                    // parse for in-fix binary operators
                    if ($this->isReserved()) {
                        return $this->raiseError('Expected a column name or value');
                    }
                    if ($this->token == '(') {
                        $clause['arg_2']['value'] = $this->parseSearchClause(true);
                        $clause['arg_2']['type'] = 'subclause';
                        $this->getTok();
                        if ($this->token != ')') {
                            return $this->raiseError('Expected ")"');
                        }
                    } else {
                        $clause['arg_2']['value'] = $this->lexer->tokText;
                        $clause['arg_2']['type'] = $this->token;
                    }
            }
        }

        $this->getTok();
        if (($this->token == 'and') || ($this->token == 'or')) {
            $op = $this->token;
            $subClause = $this->parseSearchClause($subSearch);
            if (PEAR::isError($subClause)) {
                return $subClause;
            } else {
                $clause = array('arg_1' => $clause,
                                'op' => $op,
                                'arg_2' => $subClause);
            }
        } else {
            $this->lexer->unget();
        }
        return $clause;
    }
    // }}}

    // {{{ parseFieldList()
    function parseFieldList()
    {
        $this->getTok();
        if ($this->token != '(') {
            return $this->raiseError('Expected (');
        }

        $fields = array();
        while (1) {
            // parse field identifier
            $this->getTok();
            if ($this->token == 'ident') {
                $name = $this->lexer->tokText;
            } elseif ($this->token == ')') {
                return $fields;
            } else {
                return $this->raiseError('Expected identifier');
            }

            // parse field type
            $this->getTok();
            if ($this->isType($this->token)) {
                $type = $this->token;
            } else {
                return $this->raiseError('Expected a valid type');
            }

            $this->getTok();
            // handle special case two-word types
            if ($this->token == 'precision') {
                // double precision == double
                if ($type == 'double') {
                    return $this->raiseError('Unexpected token');
                }
                $this->getTok();
            } elseif ($this->token == 'varying') {
                // character varying() == varchar()
                if ($type == 'character') {
                    $type == 'varchar';
                    $this->getTok();
                } else {
                    return $this->raiseError('Unexpected token');
                }
            }
            $fields[$name]['type'] = $this->synonyms[$type];
            // parse type parameters
            if ($this->token == '(') {
                $results = $this->getParams($values, $types);
                if (PEAR::isError($results)) {
                    return $results;
                }
                switch ($fields[$name]['type']) {
                    case 'numeric':
                        if (isset($values[1])) {
                            if ($types[1] != 'int_val') {
                                return $this->raiseError('Expected an integer');
                            }
                            $fields[$name]['decimals'] = $values[1];
                        }
                    case 'float':
                        if ($types[0] != 'int_val') {
                            return $this->raiseError('Expected an integer');
                        }
                        $fields[$name]['length'] = $values[0];
                        break;
                    case 'char': case 'varchar':
                    case 'integer': case 'int':
                        if (sizeof($values) != 1) {
                            return $this->raiseError('Expected 1 parameter');
                        }
                        if ($types[0] != 'int_val') {
                            return $this->raiseError('Expected an integer');
                        }
                        $fields[$name]['length'] = $values[0];
                        break;
                    case 'set': case 'enum':
                        if (!sizeof($values)) {
                            return $this->raiseError('Expected a domain');
                        }
                        $fields[$name]['domain'] = $values;
                        break;
                    default:
                        if (sizeof($values)) {
                            return $this->raiseError('Unexpected )');
                        }
                }
                $this->getTok();
            }

            $options = $this->parseFieldOptions();
            if (PEAR::isError($options)) {
                return $options;
            }

            $fields[$name] += $options;

            if ($this->token == ')') {
                return $fields;
            } elseif (is_null($this->token)) {
                return $this->raiseError('Expected )');
            }
        }
    }
    // }}}

    // {{{ parseFunctionOpts()
    function parseFunctionOpts()
    {
        $function = $this->token;
        $opts['name'] = $function;
        $this->getTok();
        if ($this->token != '(') {
            return $this->raiseError('Expected "("');
        }
        switch ($function) {
            case 'count':
                $this->getTok();
                switch ($this->token) {
                    case 'distinct':
                        $opts['distinct'] = true;
                        $this->getTok();
                        if ($this->token != 'ident') {
                            return $this->raiseError('Expected a column name');
                        }
                    case 'ident': case '*':
                        $opts['arg'][] = $this->lexer->tokText;
                        break;
                    default:
                        return $this->raiseError('Invalid argument');
                }
                break;
            case 'concat':
                $this->getTok();
                while ($this->token != ')') {
                    switch ($this->token) {
                        case 'ident': case 'text_val':
                            $opts['arg'][] = $this->lexer->tokText;
                            break;
                        case ',':
                            // do nothing
                            break;
                        default:
                            return $this->raiseError('Expected a string or a column name');
                    }
                    $this->getTok();
                }
                $this->lexer->pushBack();
                break;
            case 'avg': case 'min': case 'max': case 'sum':
            default:
                $this->getTok();
                $opts['arg'] = $this->lexer->tokText;
                break;
        }
        $this->getTok();
        if ($this->token != ')') {
            return $this->raiseError('Expected ")"');
        }

        // check for an alias
        $this->getTok();
        if ($this->token == ',' || $this->token == 'from') {
            $this->lexer->pushBack();
        } elseif ($this->token == 'as') {
            $this->getTok();
            if ($this->token == 'ident' ) {
                $opts['alias'] = $this->lexer->tokText;
            } else {
                return $this->raiseError('Expected column alias');
            }
        } else {
            if ($this->token == 'ident' ) {
                $opts['alias'] = $this->lexer->tokText;
            } else {
                return $this->raiseError('Expected column alias, from or comma');
            }
        }
        return $opts;
    }
    // }}}

    // {{{ parseCreate()
    function parseCreate() {
        $this->getTok();
        switch ($this->token) {
            case 'table':
                $tree = array('command' => 'create_table');
                $this->getTok();
                if ($this->token == 'ident') {
                    $tree['table_names'][] = $this->lexer->tokText;
                    $fields = $this->parseFieldList();
                    if (PEAR::isError($fields)) {
                        return $fields;
                    }
                    $tree['column_defs'] = $fields;
//                    $tree['column_names'] = array_keys($fields);
                } else {
                    return $this->raiseError('Expected table name');
                }
                break;
            case 'index':
                $tree = array('command' => 'create_index');
                break;
            case 'constraint':
                $tree = array('command' => 'create_constraint');
                break;
            case 'sequence':
                $tree = array('command' => 'create_sequence');
                break;
            default:
                return $this->raiseError('Unknown object to create');
        }
        return $tree;
    }
    // }}}

    // {{{ parseInsert()
    function parseInsert() {
        $this->getTok();
        if ($this->token == 'into') {
            $tree = array('command' => 'insert');
            $this->getTok();
            if ($this->token == 'ident') {
                $tree['table_names'][] = $this->lexer->tokText;
                $this->getTok();
            } else {
                return $this->raiseError('Expected table name');
            }
            if ($this->token == '(') {
                $results = $this->getParams($values, $types);
                if (PEAR::isError($results)) {
                    return $results;
                } else {
                    if (sizeof($values)) {
                        $tree['column_names'] = $values;
                    }
                }
                $this->getTok();
            }
            if ($this->token == 'values') {
                $this->getTok();
                $results = $this->getParams($values, $types);
                if (PEAR::isError($results)) {
                    return $results;
                } else {
                    if (isset($tree['column_defs']) &&
                        (sizeof($tree['column_defs']) != sizeof($values))) {
                        return $this->raiseError('field/value mismatch');
                    }
                    if (sizeof($values)) {
                        foreach ($values as $key=>$value) {
                            $values[$key] = array('value'=>$value,
                                                    'type'=>$types[$key]);
                        }
                        $tree['values'] = $values;
                    } else {
                        return $this->raiseError('No fields to insert');
                    }
                }
            } else {
                return $this->raiseError('Expected "values"');
            }
        } else {
            return $this->raiseError('Expected "into"');
        }
        return $tree;
    }
    // }}}

    // {{{ parseUpdate()
    function parseUpdate() {
        $this->getTok();
        if ($this->token == 'ident') {
            $tree = array('command' => 'update');
            $tree['table_names'][] = $this->lexer->tokText;
        } else {
            return $this->raiseError('Expected table name');
        }
        $this->getTok();
        if ($this->token != 'set') {
            return $this->raiseError('Expected "set"');
        }
        while (true) {
            $this->getTok();
            if ($this->token != 'ident') {
                return $this->raiseError('Expected a column name');
            }
            $tree['column_names'][] = $this->lexer->tokText;
            $this->getTok();
            if ($this->token != '=') {
                return $this->raiseError('Expected =');
            }
            $this->getTok();
            if (!$this->isVal($this->token)) {
                return $this->raiseError('Expected a value');
            }
            $tree['values'][] = array('value'=>$this->lexer->tokText,
                                      'type'=>$this->token);
            $this->getTok();
            if ($this->token == 'where') {
                $clause = $this->parseSearchClause();
                if (PEAR::isError($clause)) {
                    return $clause;
                }
                $tree['where_clause'] = $clause;
                break;
            } elseif ($this->token != ',') {
                return $this->raiseError('Expected "where" or ","');
            }
        }
        return $tree;
    }
    // }}}

    // {{{ parseDelete()
    function parseDelete() {
        $this->getTok();
        if ($this->token != 'from') {
            return $this->raiseError('Expected "from"');
        }
        $tree = array('command' => 'delete');
        $this->getTok();
        if ($this->token != 'ident') {
            return $this->raiseError('Expected a table name');
        }
        $tree['table_names'][] = $this->lexer->tokText;
        $this->getTok();
        if ($this->token != 'where') {
            return $this->raiseError('Expected "where"');
        }
        $clause = $this->parseSearchClause();
        if (PEAR::isError($clause)) {
            return $clause;
        }
        $tree['where_clause'] = $clause;
        return $tree;
    }
    // }}}

    // {{{ parseDrop()
    function parseDrop() {
        $this->getTok();
        switch ($this->token) {
            case 'table':
                $tree = array('command' => 'drop_table');
                $this->getTok();
                if ($this->token != 'ident') {
                    return $this->raiseError('Expected a table name');
                }
                $tree['table_names'][] = $this->lexer->tokText;
                $this->getTok();
                if (($this->token == 'restrict') ||
                    ($this->token == 'cascade')) {
                    $tree['drop_behavior'] = $this->token;
                }
                $this->getTok();
                if (!is_null($this->token)) {
                    return $this->raiseError('Unexpected token');
                }
                return $tree;
                break;
            case 'index':
                $tree = array('command' => 'drop_index');
                break;
            case 'constraint':
                $tree = array('command' => 'drop_constraint');
                break;
            case 'sequence':
                $tree = array('command' => 'drop_sequence');
                break;
            default:
                return $this->raiseError('Unknown object to drop');
        }
        return $tree;
    }
    // }}}

    // {{{ parseSelect()
    function parseSelect($subSelect = false) {
        $tree = array('command' => 'select');
        $this->getTok();
        if (($this->token == 'distinct') || ($this->token == 'all')) {
            $tree['set_quantifier'] = $this->token;
            $this->getTok();
        }
        if ($this->token == '*') {
            $tree['column_names'][] = '*';
            $this->getTok();
        } elseif ($this->token == 'ident' || $this->isFunc()) {
            while ($this->token != 'from') {
                if ($this->token == 'ident') {
                    $prevTok = $this->token;
                    $prevTokText = $this->lexer->tokText;
                    $this->getTok();
                    if ($this->token == '.') {
                        $columnTable = $prevTokText;
                        $this->getTok();
                        $prevTok = $this->token;
                        $prevTokText = $this->lexer->tokText;
                    } else {
                        $columnTable = '';
                    }

                    if ($prevTok == 'ident') {
                        $columnName = $prevTokText;
                    } else {
                        return $this->raiseError('Expected column name');
                    }

                    if ($this->token == 'as') {
                        $this->getTok();
                        if ($this->token == 'ident' ) {
                            $columnAlias = $this->lexer->tokText;
                        } else {
                            return $this->raiseError('Expected column alias');
                        }
                    } elseif ($this->token == 'ident') {
                        $columnAlias = $this->lexer->tokText;
                    } else {
                        $columnAlias = '';
                    }

                    $tree['column_tables'][] = $columnTable;
                    $tree['column_names'][] = $columnName;
                    $tree['column_aliases'][] = $columnAlias;
                    if ($this->token != 'from') {
                        $this->getTok();
                    }
                    if ($this->token == ',') {
                        $this->getTok();
                    }
                } elseif ($this->isFunc()) {
                    if (!isset($tree['set_quantifier'])) {
                        $result = $this->parseFunctionOpts();
                        if (PEAR::isError($result)) {
                            return $result;
                        }
                        $tree['set_function'][] = $result;
                        $this->getTok();

                        if ($this->token == 'as') {
                            $this->getTok();
                            if ($this->token == 'ident' ) {
                                $columnAlias = $this->lexer->tokText;
                            } else {
                                return $this->raiseError('Expected column alias');
                            }
                        } else {
                            $columnAlias = '';
                        }
                    } else {
                        return $this->raiseError('Cannot use "'.
                                $tree['set_quantifier'].'" with '.$this->token);
                    }
                } elseif ($this->token == ',') {
                    $this->getTok();
                } else {
                        return $this->raiseError('Unexpected token "'.$this->token.'"');
                }
            }
        } else {
            return $this->raiseError('Expected columns or a set function');
        }
        if ($this->token != 'from') {
            return $this->raiseError('Expected "from"');
        }
        $this->getTok();
        while ($this->token == 'ident') {
            $tree['table_names'][] = $this->lexer->tokText;
            $this->getTok();
            if ($this->token == 'ident') {
                $tree['table_aliases'][] = $this->lexer->tokText;
                $this->getTok();
            } elseif ($this->token == 'as') {
                $this->getTok();
                if ($this->token == 'ident') {
                    $tree['table_aliases'][] = $this->lexer->tokText;
                } else {
                    return $this->raiseError('Expected table alias');
                }
                $this->getTok();
            } else {
                $tree['table_aliases'][] = '';
            }
            if ($this->token == 'on') {
                $clause = $this->parseSearchClause();
                if (PEAR::isError($clause)) {
                    return $clause;
                }
                $tree['table_join_clause'][] = $clause;
            } else {
                $tree['table_join_clause'][] = '';
            }
            if ($this->token == ',') {
                $tree['table_join'][] = ',';
                $this->getTok();
            } elseif ($this->token == 'join') {
                $tree['table_join'][] = 'join';
                $this->getTok();
            } elseif (($this->token == 'cross') ||
                        ($this->token == 'inner')) {
                $join = $this->lexer->tokText;
                $this->getTok();
                if ($this->token != 'join') {
                    return $this->raiseError('Expected token "join"');
                }
                $tree['table_join'][] = $join.' join';
                $this->getTok();
            } elseif (($this->token == 'left') ||
                        ($this->token == 'right')) {
                $join = $this->lexer->tokText;
                $this->getTok();
                if ($this->token == 'join') {
                    $tree['table_join'][] = $join.' join';
                } elseif ($this->token == 'outer') {
                        $join .= ' outer';
                    $this->getTok();
                    if ($this->token == 'join') {
                        $tree['table_join'][] = $join.' join';
                    } else {
                        return $this->raiseError('Expected token "join"');
                    }
                } else {
                    return $this->raiseError('Expected token "outer" or "join"');
                }
                $this->getTok();
            } elseif ($this->token == 'natural') {
                $join = $this->lexer->tokText;
                $this->getTok();
                if ($this->token == 'join') {
                    $tree['table_join'][] = $join.' join';
                } elseif (($this->token == 'left') ||
                            ($this->token == 'right')) {
                        $join .= ' '.$this->token;
                    $this->getTok();
                    if ($this->token == 'join') {
                        $tree['table_join'][] = $join.' join';
                    } elseif ($this->token == 'outer') {
                        $join .= ' '.$this->token;
                        $this->getTok();
                        if ($this->token == 'join') {
                            $tree['table_join'][] = $join.' join';
                        } else {
                            return $this->raiseError('Expected token "join" or "outer"');
                        }
                    } else {
                        return $this->raiseError('Expected token "join" or "outer"');
                    }
                } else {
                    return $this->raiseError('Expected token "left", "right" or "join"');
                }
                $this->getTok();
            } elseif (($this->token == 'where') ||
                        ($this->token == 'order') ||
                        ($this->token == 'limit') ||
                        (is_null($this->token))) {
                break;
            }
        }
        while (!is_null($this->token) && (!$subSelect || $this->token != ')')
               && $this->token != ')') {
            switch ($this->token) {
                case 'where':
                    $clause = $this->parseSearchClause();
                    if (PEAR::isError($clause)) {
                        return $clause;
                    }
                    $tree['where_clause'] = $clause;
                    break;
                case 'order':
                    $this->getTok();
                    if ($this->token != 'by') {
                        return $this->raiseError('Expected "by"');
                    }
                    $this->getTok();
                    while ($this->token == 'ident') {
                        $col = $this->lexer->tokText;
                        $this->getTok();
                        if (isset($this->synonyms[$this->token])) {
                            $order = $this->synonyms[$this->token];
                            if (($order != 'asc') && ($order != 'desc')) {
                                return $this->raiseError('Unexpected token');
                            }
                            $this->getTok();
                        } else {
                            $order = 'asc';
                        }
                        if ($this->token == ',') {
                            $this->getTok();
                        }
                        $tree['sort_order'][$col] = $order;
                    }
                    break;
                case 'limit':
                    $this->getTok();
                    if ($this->token != 'int_val') {
                        return $this->raiseError('Expected an integer value');
                    }
                    $length = $this->lexer->tokText;
                    $start = 0;
                    $this->getTok();
                    if ($this->token == ',') {
                        $this->getTok();
                        if ($this->token != 'int_val') {
                            return $this->raiseError('Expected an integer value');
                        }
                        $start = $length;
                        $length = $this->lexer->tokText;
                        $this->getTok();
                    }
                    $tree['limit_clause'] = array('start'=>$start,
                                                  'length'=>$length);
                    break;
                case 'group':
                    $this->getTok();
                    if ($this->token != 'by') {
                        return $this->raiseError('Expected "by"');
                    }
                    $this->getTok();
                    while ($this->token == 'ident') {
                        $col = $this->lexer->tokText;
                        $this->getTok();
                        if ($this->token == ',') {
                            $this->getTok();
                        }
                        $tree['group_by'][] = $col;
                    }
                    break;
                default:
                    return $this->raiseError('Unexpected clause');
            }
        }
        return $tree;
    }
    // }}}

    // {{{ parse($string)
    function parse($string = null)
    {
        if (is_string($string)) {
            // Initialize the Lexer with a 3-level look-back buffer
            $this->lexer = new Lexer($string, 3);
            $this->lexer->symbols =& $this->symbols;
        } else {
            if (!is_object($this->lexer)) {
                return $this->raiseError('No initial string specified');
            }
        }

        // get query action
        $this->getTok();
        switch ($this->token) {
            case null:
                // null == end of string
                return $this->raiseError('Nothing to do');
            case 'select':
                return $this->parseSelect();
            case 'update':
                return $this->parseUpdate();
            case 'insert':
                return $this->parseInsert();
            case 'delete':
                return $this->parseDelete();
            case 'create':
                return $this->parseCreate();
            case 'drop':
                return $this->parseDrop();
            default:
                return $this->raiseError('Unknown action :'.$this->token);
        }
    }
    // }}}
}
?>


text:
@interface UIImageView (Extension)
-(void)setHeaderImage:(NSString *)imageURL;
@end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.streaming.runtime.tasks;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Defines the current processing time and handles all related actions,
 * such as register timers for tasks to be executed in the future.
 *
 *
The access to the time via {@link #getCurrentProcessingTime()} is always available, regardless of
 * whether the timer service has been shut down.
 *
 *
The registration of timers follows a life cycle of three phases:
 *

 *
In the initial state, it accepts timer registrations and triggers when the time is reached.

 *
After calling {@link #quiesce()}, further calls to
 *         {@link #registerTimer(long, ProcessingTimeCallback)} will not register any further timers, and will
 *         return a "dummy" future as a result. This is used for clean shutdown, where currently firing
 *         timers are waited for and no future timers can be scheduled, without causing hard exceptions.

 *
After a call to {@link #shutdownService()}, all calls to {@link #registerTimer(long, ProcessingTimeCallback)}
 *         will result in a hard exception.

 *

 */
public abstract class ProcessingTimeService {

	/**
	 * Returns the current processing time.
	 */
	public abstract long getCurrentProcessingTime();

	/**
	 * Registers a task to be executed when (processing) time is {@code timestamp}.
	 *
	 * @param timestamp   Time when the task is to be executed (in processing time)
	 * @param target      The task to be executed
	 *
	 * @return The future that represents the scheduled task. This always returns some future,
	 *         even if the timer was shut down
	 */
	public abstract ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target);

	/**
	 * Registers a task to be executed repeatedly at a fixed rate.
	 *
	 * @param callback to be executed after the initial delay and then after each period
	 * @param initialDelay initial delay to start executing callback
	 * @param period after the initial delay after which the callback is executed
	 * @return Scheduled future representing the task to be executed repeatedly
	 */
	public abstract ScheduledFuture<?> scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period);

	/**
	 * Returns <tt>true</tt> if the service has been shut down, <tt>false</tt> otherwise.
	 */
	public abstract boolean isTerminated();

	/**
	 * This method puts the service into a state where it does not register new timers, but
	 * returns for each call to {@link #registerTimer(long, ProcessingTimeCallback)} only a "mock" future.
	 * Furthermore, the method clears all not yet started timers.
	 *
	 *
This method can be used to cleanly shut down the timer service. The using components
	 * will not notice that the service is shut down (as for example via exceptions when registering
	 * a new timer), but the service will simply not fire any timer any more.
	 */
	public abstract void quiesce() throws InterruptedException;

	/**
	 * This method can be used after calling {@link #quiesce()}, and awaits the completion
	 * of currently executing timers.
	 */
	public abstract void awaitPendingAfterQuiesce() throws InterruptedException;

	/**
	 * Shuts down and clean up the timer service provider hard and immediately. This does not wait
	 * for any timer to complete. Any further call to {@link #registerTimer(long, ProcessingTimeCallback)}
	 * will result in a hard exception.
	 */
	public abstract void shutdownService();

	/**
	 * Shuts down and clean up the timer service provider hard and immediately. This does not wait
	 * for any timer to complete. Any further call to {@link #registerTimer(long, ProcessingTimeCallback)}
	 * will result in a hard exception. This call cannot be interrupted and will block until the shutdown is completed
	 * or the timeout is exceeded.
	 *
	 * @param timeoutMs timeout for blocking on the service shutdown in milliseconds.
	 * @return returns true iff the shutdown was completed.
	 */
	public abstract boolean shutdownServiceUninterruptible(long timeoutMs);

	/**
	 * Shuts down and clean up the timer service provider hard and immediately. This does wait
	 * for all timers to complete or until the time limit is exceeded. Any call to
	 * {@link #registerTimer(long, ProcessingTimeCallback)} will result in a hard exception after calling this method.
	 * @param time time to wait for termination.
	 * @param timeUnit time unit of parameter time.
	 * @return {@code true} if this timer service and all pending timers are terminated and
	 *         {@code false} if the timeout elapsed before this happened.
	 */
	public abstract boolean shutdownAndAwaitPending(long time, TimeUnit timeUnit) throws InterruptedException;
}


text:
package com.ning.http.client.providers.netty;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.async.ProviderUtil;
import com.ning.http.client.async.RemoteSiteTest;

public class NettyRemoteSiteTest extends RemoteSiteTest {
    @Override
    public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
        return ProviderUtil.nettyProvider(config);
    }

}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_PTHREAD_GNU_EXT
#define _GNU_SOURCE
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_POLL_H
#include <poll.h>
#else
#ifndef _WIN32
#include <sys/select.h>
#endif
#endif

#include <assert.h>
#include <errno.h>

#include <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/platform.h>

#include "synch.h"
#include "../thread/thread.h"
#include <winpr/thread.h>

/**
 * WaitForSingleObject
 * WaitForSingleObjectEx
 * WaitForMultipleObjectsEx
 * SignalObjectAndWait
 */

#ifndef _WIN32

#include <time.h>
#include <sys/time.h>
#include <sys/wait.h>

#include "../handle/handle.h"

#include "../pipe/pipe.h"

#ifdef __MACH__

#include <mach/mach_time.h>

#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 0

int clock_gettime(int clk_id, struct timespec *t)
{
	UINT64 time;
	double seconds;
	double nseconds;
	mach_timebase_info_data_t timebase;

	mach_timebase_info(&timebase);
	time = mach_absolute_time();

	nseconds = ((double) time * (double) timebase.numer) / ((double) timebase.denom);
	seconds = ((double) time * (double) timebase.numer) / ((double) timebase.denom * 1e9);

	t->tv_sec = seconds;
	t->tv_nsec = nseconds;

	return 0;
}

#endif

/* Drop in replacement for the linux pthread_timedjoin_np and
 * pthread_mutex_timedlock functions.
 */
#if !defined(HAVE_PTHREAD_GNU_EXT)
#include <pthread.h>

static long long ts_difftime(const struct timespec *o,
		const struct timespec *n)
{
	long long oldValue = o->tv_sec * 1000000000LL + o->tv_nsec;
	long long newValue = n->tv_sec * 1000000000LL + n->tv_nsec;

	return newValue - oldValue;
}

static int pthread_timedjoin_np(pthread_t td, void **res,
		struct timespec *timeout)
{
	struct timespec timenow;
	struct timespec sleepytime;
	/* This is just to avoid a completely busy wait */
	sleepytime.tv_sec = 0;
	sleepytime.tv_nsec = 10000000; /* 10ms */

	do
	{
		if (pthread_kill(td, 0))
			return pthread_join(td, res);

		nanosleep(&sleepytime, NULL);

		clock_gettime(CLOCK_MONOTONIC, &timenow);

		if (ts_difftime(timeout, &timenow) >= 0)
		{
			return ETIMEDOUT;
		}
	}
	while (TRUE);

	return ETIMEDOUT;
}

#if defined(__FreeBSD__)
	/*the only way to get it work is to remove the static*/
	int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *timeout)
#else
	static int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *timeout)
#endif
{
	struct timespec timenow;
	struct timespec sleepytime;
	int retcode;

	/* This is just to avoid a completely busy wait */
	sleepytime.tv_sec = 0;
	sleepytime.tv_nsec = 10000000; /* 10ms */

	while ((retcode = pthread_mutex_trylock (mutex)) == EBUSY)
	{
		clock_gettime(CLOCK_MONOTONIC, &timenow);

		if (ts_difftime(timeout, &timenow) >= 0)
		{
			return ETIMEDOUT;
		}

		nanosleep (&sleepytime, NULL);
	}

	return retcode;
}
#endif

static void ts_add_ms(struct timespec *ts, DWORD dwMilliseconds)
{
	ts->tv_sec += dwMilliseconds / 1000L;
	ts->tv_nsec += (dwMilliseconds % 1000L) * 1000000L;

	ts->tv_sec += ts->tv_nsec / 1000000000L;
	ts->tv_nsec = ts->tv_nsec % 1000000000L;
}

static int waitOnFd(int fd, DWORD dwMilliseconds)
{
	int status;

#ifdef HAVE_POLL_H
	struct pollfd pollfds;

	pollfds.fd = fd;
	pollfds.events = POLLIN;
	pollfds.revents = 0;

	do
	{
		status = poll(&pollfds, 1, dwMilliseconds);
	}
	while ((status < 0) && (errno == EINTR));

#else
	struct timeval timeout;
	fd_set rfds;

	FD_ZERO(&rfds);
	FD_SET(fd, &rfds);
	ZeroMemory(&timeout, sizeof(timeout));

	if ((dwMilliseconds != INFINITE) && (dwMilliseconds != 0))
	{
		timeout.tv_sec = dwMilliseconds / 1000;
		timeout.tv_usec = (dwMilliseconds % 1000) * 1000;
	}

	do
	{
		status = select(fd + 1, &rfds, NULL, NULL, (dwMilliseconds == INFINITE) ? NULL : &timeout);
	}
	while (status < 0 && (errno == EINTR));
#endif

	return status;
}

DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds)
{
	ULONG Type;
	PVOID Object;

	if (!winpr_Handle_GetInfo(hHandle, &Type, &Object))
	{
		fprintf(stderr, "WaitForSingleObject failed: invalid hHandle.\n");
		return WAIT_FAILED;
	}

	if (Type == HANDLE_TYPE_THREAD)
	{
		int status = 0;
		WINPR_THREAD* thread;
		void* thread_status = NULL;

		thread = (WINPR_THREAD*) Object;

		if (thread->started)
		{
			if (dwMilliseconds != INFINITE)
			{
				struct timespec timeout;

				/* pthread_timedjoin_np returns ETIMEDOUT in case the timeout is 0,
				 * so set it to the smallest value to get a proper return value. */
				if (dwMilliseconds == 0)
					dwMilliseconds ++;

				clock_gettime(CLOCK_MONOTONIC, &timeout);
				ts_add_ms(&timeout, dwMilliseconds);

				status = pthread_timedjoin_np(thread->thread, &thread_status, &timeout);

				if (ETIMEDOUT == status)
					return WAIT_TIMEOUT;
			}
			else
				status = pthread_join(thread->thread, &thread_status);

			thread->started = FALSE;

			if (status != 0)
			{
				fprintf(stderr, "WaitForSingleObject: pthread_join failure: [%d] %s\n",
						status, strerror(status));
			}

			if (thread_status)
				thread->dwExitCode = ((DWORD) (size_t) thread_status);
		}
	}
	else if (Type == HANDLE_TYPE_PROCESS)
	{
		WINPR_PROCESS* process;

		process = (WINPR_PROCESS*) Object;

		if (waitpid(process->pid, &(process->status), 0) != -1)
		{
			fprintf(stderr, "WaitForSingleObject: waitpid failure [%d] %s\n", errno, strerror(errno));
			return WAIT_FAILED;
		}

		process->dwExitCode = (DWORD) process->status;
	}
	else if (Type == HANDLE_TYPE_MUTEX)
	{
		WINPR_MUTEX* mutex;

		mutex = (WINPR_MUTEX*) Object;

		if (dwMilliseconds != INFINITE)
		{
			int status;
			struct timespec timeout;

			clock_gettime(CLOCK_MONOTONIC, &timeout);
			ts_add_ms(&timeout, dwMilliseconds);

			status = pthread_mutex_timedlock(&mutex->mutex, &timeout);

			if (ETIMEDOUT == status)
				return WAIT_TIMEOUT;
		}
		else
		{
			pthread_mutex_lock(&mutex->mutex);
		}
	}
	else if (Type == HANDLE_TYPE_EVENT)
	{
		int status;
		WINPR_EVENT* event;

		event = (WINPR_EVENT*) Object;

		status = waitOnFd(event->pipe_fd[0], dwMilliseconds);

		if (status < 0)
		{
			fprintf(stderr, "WaitForSingleObject: event select() failure [%d] %s\n", errno, strerror(errno));
			return WAIT_FAILED;
		}

		if (status != 1)
			return WAIT_TIMEOUT;
	}
	else if (Type == HANDLE_TYPE_SEMAPHORE)
	{
		WINPR_SEMAPHORE* semaphore;

		semaphore = (WINPR_SEMAPHORE*) Object;

#ifdef WINPR_PIPE_SEMAPHORE
		if (semaphore->pipe_fd[0] != -1)
		{
			int status;
			int length;

			status = waitOnFd(semaphore->pipe_fd[0], dwMilliseconds);
			if (status < 0)
			{
				fprintf(stderr, "WaitForSingleObject: semaphore select() failure [%d] %s\n", errno, strerror(errno));
				return WAIT_FAILED;
			}

			if (status != 1)
				return WAIT_TIMEOUT;

			length = read(semaphore->pipe_fd[0], &length, 1);

			if (length != 1)
			{
				fprintf(stderr, "WaitForSingleObject: semaphore read failure [%d] %s\n", errno, strerror(errno));
				return WAIT_FAILED;
			}
		}
#else

#if defined __APPLE__
		semaphore_wait(*((winpr_sem_t*) semaphore->sem));
#else
		sem_wait((winpr_sem_t*) semaphore->sem);
#endif

#endif
	}
	else if (Type == HANDLE_TYPE_TIMER)
	{
		WINPR_TIMER* timer;

		timer = (WINPR_TIMER*) Object;

#ifdef HAVE_EVENTFD_H
		if (timer->fd != -1)
		{
			int status;
			UINT64 expirations;

			status = waitOnFd(timer->fd, dwMilliseconds);
			if (status < 0)
			{
				fprintf(stderr, "WaitForSingleObject: timer select() failure [%d] %s\n", errno, strerror(errno));
				return WAIT_FAILED;
			}

			if (status != 1)
				return WAIT_TIMEOUT;

			status = read(timer->fd, (void*) &expirations, sizeof(UINT64));

			if (status != 8)
			{
				if (status == -1)
				{
					if (errno == ETIMEDOUT)
						return WAIT_TIMEOUT;

					fprintf(stderr, "WaitForSingleObject: timer read() failure [%d] %s\n", errno, strerror(errno));
				}
				else
				{
					fprintf(stderr, "WaitForSingleObject: timer read() failure - incorrect number of bytes read");
				}

				return WAIT_FAILED;
			}
		}
		else
		{
			fprintf(stderr, "WaitForSingleObject: invalid timer file descriptor\n");
			return WAIT_FAILED;
		}

#else
		fprintf(stderr, "WaitForSingleObject: file descriptors not supported\n");
		return WAIT_FAILED;
#endif
	}
	else if (Type == HANDLE_TYPE_NAMED_PIPE)
	{
		int fd;
		int status;
		WINPR_NAMED_PIPE* pipe = (WINPR_NAMED_PIPE*) Object;

		fd = (pipe->ServerMode) ? pipe->serverfd : pipe->clientfd;

		if (fd == -1)
		{
			fprintf(stderr, "WaitForSingleObject: invalid pipe file descriptor\n");
			return WAIT_FAILED;
		}

		status = waitOnFd(fd, dwMilliseconds);
		if (status < 0)
		{
			fprintf(stderr, "WaitForSingleObject: named pipe select() failure [%d] %s\n", errno, strerror(errno));
			return WAIT_FAILED;
		}

		if (status != 1)
		{
			return WAIT_TIMEOUT;
		}
	}
	else
	{
		fprintf(stderr, "WaitForSingleObject: unknown handle type %d\n", (int) Type);
	}

	return WAIT_OBJECT_0;
}

DWORD WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable)
{
	fprintf(stderr, "[ERROR] %s: Function not implemented.\n", __func__);
	assert(0);
	return WAIT_OBJECT_0;
}

#define MAXIMUM_WAIT_OBJECTS 64

DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds)
{
	int fd = -1;
	int index;
	int status;
	ULONG Type;
	PVOID Object;
#ifdef HAVE_POLL_H
	struct pollfd *pollfds;
#else
	int maxfd;
	fd_set fds;
	struct timeval timeout;
#endif

	if (!nCount || (nCount > MAXIMUM_WAIT_OBJECTS))
	{
		fprintf(stderr, "%s: invalid handles count(%d)\n", __FUNCTION__, nCount);
		return WAIT_FAILED;
	}

#ifdef HAVE_POLL_H
	pollfds = alloca(nCount * sizeof(struct pollfd));
#else
	maxfd = 0;
	FD_ZERO(&fds);
	ZeroMemory(&timeout, sizeof(timeout));

#endif

	if (bWaitAll)
	{
		fprintf(stderr, "%s: bWaitAll not yet implemented\n", __FUNCTION__);
		assert(0);
	}

	for (index = 0; index < nCount; index++)
	{
		if (!winpr_Handle_GetInfo(lpHandles[index], &Type, &Object))
		{
			fprintf(stderr, "%s: invalid handle\n", __FUNCTION__);

			return WAIT_FAILED;
		}

		if (Type == HANDLE_TYPE_EVENT)
		{
			fd = ((WINPR_EVENT*) Object)->pipe_fd[0];

			if (fd == -1)
			{
				fprintf(stderr, "%s: invalid event file descriptor\n", __FUNCTION__);
				return WAIT_FAILED;
			}
		}
		else if (Type == HANDLE_TYPE_SEMAPHORE)
		{
#ifdef WINPR_PIPE_SEMAPHORE
			fd = ((WINPR_SEMAPHORE*) Object)->pipe_fd[0];
#else
			fprintf(stderr, "%s: semaphore not supported\n", __FUNCTION__);
			return WAIT_FAILED;
#endif
		}
		else if (Type == HANDLE_TYPE_TIMER)
		{
			WINPR_TIMER* timer = (WINPR_TIMER*) Object;
			fd = timer->fd;

			if (fd == -1)
			{
				fprintf(stderr, "%s: invalid timer file descriptor\n", __FUNCTION__);
				return WAIT_FAILED;
			}
		}
		else if (Type == HANDLE_TYPE_NAMED_PIPE)
		{
			WINPR_NAMED_PIPE* pipe = (WINPR_NAMED_PIPE*) Object;
			fd = (pipe->ServerMode) ? pipe->serverfd : pipe->clientfd;

			if (fd == -1)
			{
				fprintf(stderr, "%s: invalid timer file descriptor\n", __FUNCTION__);
				return WAIT_FAILED;
			}
		}
		else
		{
			fprintf(stderr, "%s: unknown handle type %d\n", __FUNCTION__, (int) Type);
			return WAIT_FAILED;
		}

		if (fd == -1)
		{
			fprintf(stderr, "%s: invalid file descriptor\n", __FUNCTION__);
			return WAIT_FAILED;
		}

#ifdef HAVE_POLL_H
		pollfds[index].fd = fd;
		pollfds[index].events = POLLIN;
		pollfds[index].revents = 0;
#else
		FD_SET(fd, &fds);

		if (fd > maxfd)
			maxfd = fd;
#endif
	}

#ifdef HAVE_POLL_H
	do
	{
		status = poll(pollfds, nCount, dwMilliseconds);
	}
	while (status < 0 && errno == EINTR);
#else
	if ((dwMilliseconds != INFINITE) && (dwMilliseconds != 0))
	{
		timeout.tv_sec = dwMilliseconds / 1000;
		timeout.tv_usec = (dwMilliseconds % 1000) * 1000;
	}

	do
	{
		status = select(maxfd + 1, &fds, 0, 0,
				(dwMilliseconds == INFINITE) ? NULL : &timeout);
	}
	while (status < 0 && errno == EINTR);
#endif

	if (status < 0)
	{
		fprintf(stderr, "%s: select() failure [%d] %s\n", __FUNCTION__, errno, strerror(errno));
		return WAIT_FAILED;
	}

	if (status == 0)
		return WAIT_TIMEOUT;

	for (index = 0; index < nCount; index++)
	{
		winpr_Handle_GetInfo(lpHandles[index], &Type, &Object);

		if (Type == HANDLE_TYPE_EVENT)
		{
			fd = ((WINPR_EVENT*) Object)->pipe_fd[0];
		}
		else if (Type == HANDLE_TYPE_SEMAPHORE)
		{
			fd = ((WINPR_SEMAPHORE*) Object)->pipe_fd[0];
		}
		else if (Type == HANDLE_TYPE_TIMER)
		{
			WINPR_TIMER* timer = (WINPR_TIMER*) Object;
			fd = timer->fd;
		}
		else if (Type == HANDLE_TYPE_NAMED_PIPE)
		{
			WINPR_NAMED_PIPE* pipe = (WINPR_NAMED_PIPE*) Object;
			fd = (pipe->ServerMode) ? pipe->serverfd : pipe->clientfd;
		}

#ifdef HAVE_POLL_H
		if (pollfds[index].revents & POLLIN)
#else
		if (FD_ISSET(fd, &fds))
#endif
		{
			if (Type == HANDLE_TYPE_SEMAPHORE)
			{
				int length;

				length = read(fd, &length, 1);

				if (length != 1)
				{
					fprintf(stderr, "%s: semaphore read() failure [%d] %s\n", __FUNCTION__, errno, strerror(errno));
					return WAIT_FAILED;
				}
			}
			else if (Type == HANDLE_TYPE_TIMER)
			{
				int length;
				UINT64 expirations;

				length = read(fd, (void*) &expirations, sizeof(UINT64));

				if (length != 8)
				{
					if (length == -1)
					{
						if (errno == ETIMEDOUT)
							return WAIT_TIMEOUT;

						fprintf(stderr, "%s: timer read() failure [%d] %s\n", __FUNCTION__, errno, strerror(errno));
					}
					else
					{
						fprintf(stderr, "%s: timer read() failure - incorrect number of bytes read", __FUNCTION__);
					}

					return WAIT_FAILED;
				}
			}

			return (WAIT_OBJECT_0 + index);
		}
	}

	fprintf(stderr, "%s: failed (unknown error)\n", __FUNCTION__);
	return WAIT_FAILED;
}

DWORD WaitForMultipleObjectsEx(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds, BOOL bAlertable)
{
	fprintf(stderr, "[ERROR] %s: Function not implemented.\n", __func__);
	assert(0);
	return 0;
}

DWORD SignalObjectAndWait(HANDLE hObjectToSignal, HANDLE hObjectToWaitOn, DWORD dwMilliseconds, BOOL bAlertable)
{
	fprintf(stderr, "[ERROR] %s: Function not implemented.\n", __func__);
	assert(0);
	return 0;
}

#endif


text:
<?php

namespace minion\Connections;

abstract class ConnectionAbstract
{
    /**
     * @var string
     */
    protected $currentDirectory;

    /**
     * Set the working directory for all commands
     *
     * @param string|null $directory
     */
    public function cwd($directory = null)
    {
        $this->currentDirectory = $directory;
    }

    /**
     * Get the current working directory
     *
     * @return string
     */
    public function pwd()
    {
        return $this->currentDirectory;
    }

	abstract public function execute($command);
}


text:
Visibility for handler methods is honored
--FILE--
<?php

class StringHandler {
    public static function pub($self) {
        echo "Public\n";
        $self->prot();
    }
    protected static function prot($self) {
        echo "Protected\n";
    }
}

register_primitive_type_handler('string', 'StringHandler');

set_exception_handler(function($e) {
    echo "\nFatal error: {$e->getMessage()} in {$e->getFile()} on line {$e->getLine()}";
});

$str = "abc";
$str->pub();
$str->prot();

?>
--EXPECTF--
Public
Protected

Fatal error: Call to protected method StringHandler::prot() from %s in %s on line %d


text:
package com.raoulvdberge.refinedstorage.container;

import com.raoulvdberge.refinedstorage.container.slot.filter.SlotFilter;
import com.raoulvdberge.refinedstorage.tile.TileStorage;
import net.minecraft.entity.player.EntityPlayer;

public class ContainerStorage extends ContainerBase {
    public ContainerStorage(TileStorage storage, EntityPlayer player) {
        super(storage, player);

        for (int i = 0; i < 9; ++i) {
            addSlotToContainer(new SlotFilter(storage.getNode().getFilters(), i, 8 + (18 * i), 20));
        }

        addPlayerInventory(8, 141);

        transferManager.addItemFilterTransfer(player.inventory, storage.getNode().getFilters());
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<qualifiedTypeNameHistroy>
<fullyQualifiedTypeName name="android.widget.Button"/>
<fullyQualifiedTypeName name="android.view.View"/>
<fullyQualifiedTypeName name="android.content.Intent"/>
<fullyQualifiedTypeName name="android.os.Bundle"/>
<fullyQualifiedTypeName name="android.widget.TextView"/>
<fullyQualifiedTypeName name="android.view.View.OnClickListener"/>
</qualifiedTypeNameHistroy>


text:
Vue.use(Vuex)

const state = {
  count: 0
}

const mutations = {
  increment (state) {
    state.count++
  },
  decrement (state) {
    state.count--
  }
}

const actions = {
  increment: ({commit}) => commit('increment'),
  decrement: ({commit}) => commit('decrement'),
  incrementIfOdd ({commit, state}) {
    if ((state.count + 1) % 2 === 0) {
      commit('increment')
    }
  },
  incrementAsync ({commit}) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('increment')
        resolve()
      }, 1000)
    })
  }
}

const getters = {
  evenOrOdd: state => state % 2 === 0 ? 'even' : 'odd'
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nicolai.Resources;
using System.Threading.Tasks;
using System.Threading;

namespace UnitTests
{
    [TestClass]
    public class SimpleUsageTests
    {
        [TestInitialize]
        public void Initialize()
        {
            MyAmbientResource.ResourceFactory = () => new MyResource();
        }

        [TestCleanup]
        public void Cleanup()
        {
            MyAmbientResource.Reset();
        }

        [TestMethod]
        public void Using_SingleScope_Success()
        {
            // Arrange
            MyResource actualResource = null;

            // Act
            using (var res = MyAmbientResource.Current)
            {
                actualResource = res.ActualResource;
            }

            // Assert
            Assert.IsNotNull(actualResource);
            Assert.AreEqual(1, actualResource.DisposeCount);
            Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
        }

        [TestMethod]
        public void Using_NestedScopeSameMethod_Success()
        {
            // Arrange
            MyResource actualResource = null;

            // Act
            using (var res = MyAmbientResource.Current)
            {
                actualResource = res.ActualResource;

                using (var res2 = MyAmbientResource.Current)
                {
                    // Dispose count should NOT increase after this scope exits
                }
            }

            // Assert
            Assert.IsNotNull(actualResource);
            Assert.AreEqual(1, actualResource.DisposeCount);
            Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
        }

        [TestMethod]
        public void Using_NestedScope_Success()
        {
            // Arrange
            MyResource actualResource = null;

            // Act
            using (var res = MyAmbientResource.Current)
            {
                actualResource = res.ActualResource;

                UseResource();
            }

            // Assert
            Assert.IsNotNull(actualResource);
            Assert.AreEqual(1, actualResource.DisposeCount);
            Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
        }

        private void UseResource()
        {
            using (var res2 = MyAmbientResource.Current)
            {
                // Dispose count should NOT increase after this scope exits (if called from active scope)
            }
        }

        [TestMethod]
        public void Using_SingleScopeAndCallToCurrent_Success()
        {
            // Arrange
            MyResource actualResource = null;

            // Act
            using (var res = MyAmbientResource.Current)
            {
                actualResource = res.ActualResource;

                var res2 = MyAmbientResource.Current;

                res2.Dispose();
            }

            // Assert
            Assert.IsNotNull(actualResource);
            Assert.AreEqual(1, actualResource.DisposeCount);
            Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
        }

        [TestMethod]
        public async Task Reference_Timeout_Success()
        {
            var timeout = MyAmbientResource.ResourceTimeoutMillis;
            try
            {
                // Arrange
                MyResource actualResource = null;
                MyAmbientResource.ResourceTimeoutMillis = 500;

                // Act
                var res = MyAmbientResource.Current;
                actualResource = res.ActualResource;
                await Task.Delay(600);

                // Assert
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(1, actualResource.DisposeCount);
                Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
            }
            finally
            {
                MyAmbientResource.ResourceTimeoutMillis = timeout;
            }
        }

        [TestMethod]
        public async Task Reference_NotTimedOutAndThenTimeout_Success()
        {
            var timeout = MyAmbientResource.ResourceTimeoutMillis;
            try
            {
                // Arrange
                MyResource actualResource = null;
                MyAmbientResource.ResourceTimeoutMillis = 500;

                // Act
                var res = MyAmbientResource.Current;
                actualResource = res.ActualResource;
                await Task.Delay(200);

                // Assert (not timed out)
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(0, actualResource.DisposeCount);
                Assert.AreEqual(1, MyAmbientResource.ActiveReferences);

                await Task.Delay(400);

                // Assert (timed out)
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(1, actualResource.DisposeCount);
                Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
            }
            finally
            {
                MyAmbientResource.ResourceTimeoutMillis = timeout;
            }
        }

        [TestMethod]
        public async Task Reference_NoAdditionalTimeoutDispose_Success()
        {
            var timeout = MyAmbientResource.ResourceTimeoutMillis;
            try
            {
                // Arrange
                MyResource actualResource = null;
                MyAmbientResource.ResourceTimeoutMillis = 500;

                // Act
                var res = MyAmbientResource.Current;
                actualResource = res.ActualResource;
                await Task.Delay(200);
                res.Dispose();

                // Assert
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(1, actualResource.DisposeCount);
                Assert.AreEqual(0, MyAmbientResource.ActiveReferences);

                await Task.Delay(400);

                // Assert (no changes)
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(1, actualResource.DisposeCount);
                Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
            }
            finally
            {
                MyAmbientResource.ResourceTimeoutMillis = timeout;
            }
        }

        [TestMethod]
        public async Task Reference_TimeoutDisabled_Success()
        {
            var timeout = MyAmbientResource.ResourceTimeoutMillis;
            try
            {
                // Arrange
                MyResource actualResource = null;
                MyAmbientResource.ResourceTimeoutMillis = 0;

                // Act
                var res = MyAmbientResource.Current;
                actualResource = res.ActualResource;
                await Task.Delay(200);

                // Assert
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(0, actualResource.DisposeCount);
                Assert.AreEqual(1, MyAmbientResource.ActiveReferences);

                // Act
                res.Dispose();

                // Assert
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(1, actualResource.DisposeCount);
                Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
            }
            finally
            {
                MyAmbientResource.ResourceTimeoutMillis = timeout;
            }
        }

        [TestMethod]
        public async Task Reference_TimeoutDisabledWhileActive_Success()
        {
            var timeout = MyAmbientResource.ResourceTimeoutMillis;
            try
            {
                // Arrange
                MyResource actualResource = null;
                MyAmbientResource.ResourceTimeoutMillis = 200;

                // Act
                var res = MyAmbientResource.Current;
                actualResource = res.ActualResource;
                await Task.Delay(100);
                MyAmbientResource.ResourceTimeoutMillis = 0;
                await Task.Delay(200);

                // Assert
                Assert.IsNotNull(actualResource);
                Assert.AreEqual(0, actualResource.DisposeCount);
                Assert.AreEqual(1, MyAmbientResource.ActiveReferences);

                // Cleanup
                res.Dispose();
            }
            finally
            {
                MyAmbientResource.ResourceTimeoutMillis = timeout;
            }
        }

        [TestMethod]
        public async Task Using_MultipleThreads_Success()
        {
            // Arrange
            MyResource actualResource1 = null;
            MyResource actualResource2 = null;
            var thread1 = Task.Run(() =>
            {
                using (var res = MyAmbientResource.Current)
                {
                    actualResource1 = res.ActualResource;
                    Thread.Sleep(500);
                }
            });
            var thread2 = Task.Run(() =>
            {
                using (var res = MyAmbientResource.Current)
                {
                    actualResource2 = res.ActualResource;
                    Thread.Sleep(500);
                }
            });

            // Act
            await Task.WhenAll(thread1, thread2);

            // Assert
            Assert.IsNotNull(actualResource1);
            Assert.IsNotNull(actualResource2);
            Assert.AreEqual(actualResource1, actualResource2);
            Assert.AreEqual(1, actualResource1.DisposeCount);
            Assert.AreEqual(0, MyAmbientResource.ActiveReferences);
        }
    }

    class MyAmbientResource : GenericAmbientResource<MyAmbientResource, MyResource>
    {
        public MyResource ActualResource => Resource;
    }

    class MyResource : IDisposable
    {
        public int DisposeCount { get; private set; }

        public virtual void Dispose()
        {
            lock (this)
            {
                DisposeCount++;
            }
        }
    }
}


text:
require_relative 'regexp'

module Babelyoda
  class LocalizationKey
    attr_reader :id
    attr_reader :context
    attr_reader :values

    def initialize(id, context)
      @id = id
      @context = context
      @values = {}
      @plural = plural_id?(id)
      @plural_key = plural? ? extract_plural_key(id) : nil
      @id = depluralize_key(@id) if plural?
    end

    def to_s
      "\"#{@id}\" [#{@values.keys.map{|k| ":#{k.to_s}"}.join(', ')}] // #{@context}"
    end

    def plural? ; @plural ; end

    def <<(localization_value)
      raise "Can't merge a plural value into a non-plural key" if !plural? && localization_value.plural?
      lang = localization_value.language.to_sym
      value = localization_value.dup
      if plural?
        value.pluralize!(@plural_key)
        if @values[lang]
          @values[lang].merge!(value, { :preserve => true })
        else
          @values[lang] = value
        end
      else
        @values[lang] = value
      end
      self
    end

    def merge!(localization_key, options = {})
      updated = false

      context_changed = false
      new_context = localization_key.context
      if @context != new_context && new_context != nil && new_context.length > 0
        @context = localization_key.context
        updated = context_changed = true
      end

      localization_key.values.each_value do |value|
        if @values.has_key?(value.language.to_sym)
          updated = true if @values[value.language.to_sym].merge!(value, options)
        else
          @values[value.language.to_sym] = value.dup
          updated = true
        end
      end

      # Mark all values as requiring translation if the context has changed.
      if context_changed
        @values.each_value do |value|
          value.status = :requires_translation
        end
      end

      return updated
    end

    def drop_empty!
      @values.delete_if do |id, value|
        value.text.empty?
      end
    end

    def empty?
      @values.empty?
    end

    def ensure_languages!(languages = [])
      languages.each do |language|
        unless self.values[language]
          self << Babelyoda::LocalizationValue.new(language, '')
        end
      end
    end

  private
    include Babelyoda::Regexp
  end
end


text:
G_BEGIN_DECLS

#define GTK_PRESERVE_WINDOW_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \
                                            GTK_TYPE_PRESERVE_WINDOW, \
                                            GtkPreserveWindowPrivate))

typedef struct _GtkPreserveWindowPrivate GtkPreserveWindowPrivate;

struct _GtkPreserveWindowPrivate {
  // If true, don't create/destroy windows on realize/unrealize.
  gboolean preserve_window;

  // Whether or not we delegate the resize of the GdkWindow
  // to someone else.
  gboolean delegate_resize;
};

G_DEFINE_TYPE(GtkPreserveWindow, gtk_preserve_window, GTK_TYPE_FIXED)

static void gtk_preserve_window_destroy(GtkObject* object);
static void gtk_preserve_window_realize(GtkWidget* widget);
static void gtk_preserve_window_unrealize(GtkWidget* widget);
static void gtk_preserve_window_size_allocate(GtkWidget* widget,
                                              GtkAllocation* allocation);

static void gtk_preserve_window_class_init(GtkPreserveWindowClass *klass) {
  GtkWidgetClass* widget_class = reinterpret_cast<GtkWidgetClass*>(klass);
  widget_class->realize = gtk_preserve_window_realize;
  widget_class->unrealize = gtk_preserve_window_unrealize;
  widget_class->size_allocate = gtk_preserve_window_size_allocate;

  GtkObjectClass* object_class = reinterpret_cast<GtkObjectClass*>(klass);
  object_class->destroy = gtk_preserve_window_destroy;

  GObjectClass* gobject_class = G_OBJECT_CLASS(klass);
  g_type_class_add_private(gobject_class, sizeof(GtkPreserveWindowPrivate));
}

static void gtk_preserve_window_init(GtkPreserveWindow* widget) {
  GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
  priv->preserve_window = FALSE;

  // These widgets always have their own window.
  gtk_widget_set_has_window(GTK_WIDGET(widget), TRUE);
}

GtkWidget* gtk_preserve_window_new() {
  return GTK_WIDGET(g_object_new(GTK_TYPE_PRESERVE_WINDOW, NULL));
}

static void gtk_preserve_window_destroy(GtkObject* object) {
  GtkWidget* widget = reinterpret_cast<GtkWidget*>(object);
  GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);

  GdkWindow* gdk_window = gtk_widget_get_window(widget);
  if (gdk_window) {
    gdk_window_set_user_data(gdk_window, NULL);
    // If the window is preserved, someone else must destroy it.
    if (!priv->preserve_window)
      gdk_window_destroy(gdk_window);
    gtk_widget_set_window(widget, NULL);
  }

  GTK_OBJECT_CLASS(gtk_preserve_window_parent_class)->destroy(object);
}

static void gtk_preserve_window_realize(GtkWidget* widget) {
  g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));

  GdkWindow* gdk_window = gtk_widget_get_window(widget);
  if (gdk_window) {
    GtkAllocation allocation;
    gtk_widget_get_allocation(widget, &allocation);

    gdk_window_reparent(gdk_window,
                        gtk_widget_get_parent_window(widget),
                        allocation.x,
                        allocation.y);
    GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
    if (!priv->delegate_resize) {
      gdk_window_resize(gdk_window,
                        allocation.width,
                        allocation.height);
    }
    gint event_mask = gtk_widget_get_events(widget);
    event_mask |= GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK;
    gdk_window_set_events(gdk_window, (GdkEventMask) event_mask);
    gdk_window_set_user_data(gdk_window, widget);

    gtk_widget_set_realized(widget, TRUE);

    gtk_widget_style_attach(widget);
    gtk_style_set_background(gtk_widget_get_style(widget),
                             gdk_window, GTK_STATE_NORMAL);
  } else {
    GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->realize(widget);
  }
}

static void gtk_preserve_window_unrealize(GtkWidget* widget) {
  g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));

  GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
  if (priv->preserve_window) {
    GtkWidgetClass* widget_class =
        GTK_WIDGET_CLASS(gtk_preserve_window_parent_class);
    GtkContainerClass* container_class =
        GTK_CONTAINER_CLASS(gtk_preserve_window_parent_class);

    if (gtk_widget_get_mapped(widget)) {
      widget_class->unmap(widget);

      gtk_widget_set_mapped(widget, FALSE);
    }

    // This is the behavior from GtkWidget, inherited by GtkFixed.
    // It is unclear why we should not call the potentially overridden
    // unrealize method (via the callback), but doing so causes errors.
    container_class->forall(
        GTK_CONTAINER(widget), FALSE,
        reinterpret_cast<GtkCallback>(gtk_widget_unrealize), NULL);

    GdkWindow* gdk_window = gtk_widget_get_window(widget);

    gtk_style_detach(widget->style);
    gdk_window_reparent(gdk_window, gdk_get_default_root_window(), 0, 0);
    gtk_selection_remove_all(widget);
    gdk_window_set_user_data(gdk_window, NULL);

    gtk_widget_set_realized(widget, FALSE);
  } else {
    GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->unrealize(widget);
  }
}

gboolean gtk_preserve_window_get_preserve(GtkPreserveWindow* window) {
  g_return_val_if_fail(GTK_IS_PRESERVE_WINDOW(window), FALSE);
  GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);

  return priv->preserve_window;
}

void gtk_preserve_window_set_preserve(GtkPreserveWindow* window,
                                      gboolean value) {
  g_return_if_fail(GTK_IS_PRESERVE_WINDOW(window));
  GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);
  priv->preserve_window = value;

  GtkWidget* widget = GTK_WIDGET(window);
  GdkWindow* gdk_window = gtk_widget_get_window(widget);
  if (value && !gdk_window) {
    GdkWindowAttr attributes;
    gint attributes_mask;

    // We may not know the width and height, so we rely on the fact
    // that a size-allocation will resize it later.
    attributes.width = 1;
    attributes.height = 1;

    attributes.window_type = GDK_WINDOW_CHILD;
    attributes.wclass = GDK_INPUT_OUTPUT;
    attributes.override_redirect = TRUE;

    attributes.visual = gtk_widget_get_visual(widget);
    attributes.colormap = gtk_widget_get_colormap(widget);

    attributes.event_mask = gtk_widget_get_events(widget);
    attributes.event_mask |= GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK;

    attributes_mask = GDK_WA_VISUAL | GDK_WA_COLORMAP | GDK_WA_NOREDIR;
    gdk_window = gdk_window_new(
        gdk_get_default_root_window(), &attributes, attributes_mask);
    gtk_widget_set_window(widget, gdk_window);
  } else if (!value && gdk_window && !gtk_widget_get_realized(widget)) {
    gdk_window_destroy(gdk_window);
    gtk_widget_set_window(widget, NULL);
  }
}

void gtk_preserve_window_size_allocate(GtkWidget* widget,
                                       GtkAllocation* allocation) {
  g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));

  gtk_widget_set_allocation(widget, allocation);

  if (gtk_widget_get_realized(widget)) {
    GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
    GdkWindow* gdk_window = gtk_widget_get_window(widget);
    if (priv->delegate_resize) {
      gdk_window_move(gdk_window, allocation->x, allocation->y);
    } else {
      gdk_window_move_resize(
          gdk_window, allocation->x, allocation->y,
          allocation->width, allocation->height);
    }
  }

  // Propagate resize to children
  guint16 border_width = GTK_CONTAINER(widget)->border_width;
  GList *children = GTK_FIXED(widget)->children;
  while (children) {
    GtkFixedChild *child = reinterpret_cast<GtkFixedChild*>(children->data);
    if (gtk_widget_get_visible(child->widget)) {
      GtkRequisition child_requisition;
      gtk_widget_get_child_requisition(child->widget, &child_requisition);

      GtkAllocation child_allocation;
      child_allocation.x = child->x + border_width;
      child_allocation.y = child->y + border_width;
      child_allocation.width = child_requisition.width;
      child_allocation.height = child_requisition.height;

      gtk_widget_size_allocate(child->widget, &child_allocation);
    }
    children = children->next;
  }
}

void gtk_preserve_window_delegate_resize(GtkPreserveWindow* widget,
                                         gboolean delegate) {
  GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
  priv->delegate_resize = delegate;
}

G_END_DECLS


text:
using namespace ofp;

PropertyRange GetAsyncReply::properties() const {
  return SafeByteRange(this, header_.length(), sizeof(GetAsyncReply));
}

bool GetAsyncReply::validateInput(Validation *context) const {
  return properties().validateInput(context);
}

GetAsyncReplyBuilder::GetAsyncReplyBuilder(UInt32 xid) {
  msg_.header_.setXid(xid);
}

GetAsyncReplyBuilder::GetAsyncReplyBuilder(const GetAsyncRequest *request) {
  msg_.header_.setXid(request->xid());
}

GetAsyncReplyBuilder::GetAsyncReplyBuilder(const GetAsyncReply *msg)
    : msg_{*msg} {}

UInt32 GetAsyncReplyBuilder::send(Writable *channel) {
  UInt32 xid = channel->nextXid();
  UInt8 version = channel->version();

  msg_.header_.setXid(xid);
  msg_.header_.setVersion(version);

  if (version >= OFP_VERSION_5) {
    size_t msgLen = sizeof(msg_) + properties_.size();
    msg_.header_.setLength(msgLen);

    channel->write(&msg_, sizeof(msg_));
    channel->write(properties_.data(), properties_.size());

  } else {
    struct {
      Big<OFPPacketInFlags> packetInMask[2];
      Big<OFPPortStatusFlags> portStatusMask[2];
      Big<OFPFlowRemovedFlags> flowRemovedMask[2];
    } asyncBody;

    PropertyRange props = properties_.toRange();
    asyncBody.packetInMask[0] =
        props.value<AsyncConfigPropertyPacketInMaster>();
    asyncBody.packetInMask[1] = props.value<AsyncConfigPropertyPacketInSlave>();
    asyncBody.portStatusMask[0] =
        props.value<AsyncConfigPropertyPortStatusMaster>();
    asyncBody.portStatusMask[1] =
        props.value<AsyncConfigPropertyPortStatusSlave>();
    asyncBody.flowRemovedMask[0] =
        props.value<AsyncConfigPropertyFlowRemovedMaster>();
    asyncBody.flowRemovedMask[1] =
        props.value<AsyncConfigPropertyFlowRemovedSlave>();

    msg_.header_.setLength(32);
    channel->write(&msg_, sizeof(msg_));
    channel->write(&asyncBody, sizeof(asyncBody));
  }

  channel->flush();

  return xid;
}


text:
'use strict';

/**
 * Requirements
 */
const LoadFilter = require(ES_SOURCE + '/nunjucks/filter/LoadFilter.js').LoadFilter;
const filterSpec = require(ES_TEST + '/nunjucks/filter/FilterShared.js').spec;
const projectFixture = require(ES_FIXTURES + '/project/index.js');
const sinon = require('sinon');

/**
 * Spec
 */
describe(LoadFilter.className, function()
{
    /**
     * Filter Test
     */
    filterSpec(LoadFilter, 'nunjucks.filter/LoadFilter', function(parameters)
    {
        return [global.fixtures.viewModelRepository];
    });

    /**
     * LoadFilter Test
     */
    beforeEach(function()
    {
        global.fixtures = projectFixture.createStatic();
    });

    describe('#filter()', function()
    {
        it('should passthrough anything that is not a string', function()
        {
            const testee = new LoadFilter(global.fixtures.viewModelRepository).filter();
            expect(testee()).to.be.not.ok;
            expect(testee({ hi: 'ho' })).to.be.deep.equal({ hi: 'ho' });
        });

        it('should load a json file though ViewModelRepository', function()
        {
            sinon.spy(global.fixtures.viewModelRepository, 'getByPath');
            const testee = new LoadFilter(global.fixtures.viewModelRepository).filter();
            const result = testee('m-teaser/default');
            expect(global.fixtures.viewModelRepository.getByPath.calledOnce).to.be.ok;
            expect(result).to.be.ok;
            expect(result.link).to.be.equal('https://www.google.com');
        });
    });
});


text:
package com.sample.packplan.util.formatter;

import com.sample.packplan.model.Item;
import com.sample.packplan.util.Constant;

/**
 * Item data formatter
 */
public final class ItemFormatter implements Formattable<Item> {

    private static final Formattable ITEM_FORMATTER = new ItemFormatter();

    /**
     * Gives the singleton instance of ItemFormatter
     *
     * @return Formattable object
     */
    public static Formattable getInstance() {
        return ITEM_FORMATTER;
    }

    private ItemFormatter() {
        // to restrict creating instances
    }

    /**
     * Format given item data
     *
     * @param data Item object
     * @return String value of formatted data
     */
    public String format(final Item data) {
        if (data == null) {
            return Constant.NEW_LINE;
        }
        StringBuilder result = new StringBuilder();
        result.append(data.getId());
        result.append(Constant.COMMA);
        result.append(data.getLength());
        result.append(Constant.COMMA);
        result.append(data.getQuantity());
        result.append(Constant.COMMA);
        result.append(data.getPieceWeight());
        result.append(Constant.NEW_LINE);
        return result.toString();
    }
}