text:
<?php
/**
 * @package Model
 */
class Kwf_Model_Db extends Kwf_Model_Abstract
{
    protected $_rowClass = 'Kwf_Model_Db_Row';
    protected $_rowsetClass = 'Kwf_Model_Db_Rowset';
    protected $_table;
    protected $_db;
    private $_tableName;
    private $_columns;
    private $_primaryKey;

    protected $_supportedImportExportFormats = array(self::FORMAT_SQL, self::FORMAT_CSV, self::FORMAT_ARRAY);

    private $_importBuffer;
    private $_importBufferOptions;

    public function __construct($config = array())
    {
        if (isset($config['tableName'])) {
            $this->_table = new $config['tableName']();
        }
        if (isset($config['table'])) {
            $this->_table = $config['table'];
        }
        if (isset($config['db'])) {
            $this->_db = $config['db'];
        }
        parent::__construct($config);
    }

    public function __sleep()
    {
        throw new Kwf_Exception_NotYetImplemented();
    }

    public function __destruct()
    {
        if (isset($this->_importBuffer)) {
            $this->writeBuffer();
        }
    }

    protected function _init()
    {
        parent::_init();
        if (!$this->_table) {
            if (isset($this->_name)) {
                throw new Kwf_Exception("You must rename _name to _table in '".get_class($this)."'");
            }
            throw new Kwf_Exception("No table set");
        }
    }

    public function getColumnType($col)
    {
        $info = $this->getTable()->info();
        if (isset($info['metadata'][$col])) {
            $type = $this->_getTypeFromDbType($info['metadata'][$col]['DATA_TYPE']);
            if ($col == 'pos' && $type == self::TYPE_BOOLEAN) {
                throw new Kwf_Exception('Column "pos" must not be of type TINYINT in table "' . $info['name'] . '"');
            }
            return $type;
        }
        return parent::getColumnType($col);
    }

    private function _getTypeFromDbType($type)
    {
        if ($type == 'varchar') $type = self::TYPE_STRING;
        else if (substr($type, 0, 7) == 'tinyint') $type = self::TYPE_BOOLEAN;
        else if ($type == 'text') $type = self::TYPE_STRING;
        else if ($type == 'tinytext') $type = self::TYPE_STRING;
        else if (substr($type, -3) == 'int') $type = self::TYPE_INTEGER;
        else if ($type == 'datetime') $type = self::TYPE_DATETIME;
        else if ($type == 'timestamp') $type = self::TYPE_DATETIME;
        else if ($type == 'date') $type = self::TYPE_DATE;
        else if ($type == 'decimal') $type = self::TYPE_FLOAT;
        else if (substr($type, 0, 6) == 'double') $type = self::TYPE_FLOAT;
        else if ($type == 'time') $type = null;
        else $type = null;
        return $type;
    }

    protected function _getOwnColumns()
    {
        if (!$this->_columns) {
            $cache = self::_getMetadataCache();
            $cacheId = md5($this->getUniqueIdentifier()).'_columns';
            if (!$this->_columns = $cache->load($cacheId)) {
                $this->_columns = $this->getTable()->info(Zend_Db_Table_Abstract::COLS);
                $cache->save($this->_columns, $cacheId);
            }
        }
        return $this->_columns;
    }

    public function createRow(array $data=array())
    {
        $ret = new $this->_rowClass(array(
            'row' => $this->getTable()->createRow(),
            'model' => $this
        ));
        $data = array_merge($this->_default, $data);
        foreach ($data as $k=>$i) {
            $ret->$k = $i;
        }
        return $ret;
    }

    public function beforeDelete($row)
    {
        $id = $this->_getUniqueId($row->getRow());
        unset($this->_rows[$id]);
    }

    /**
     * wird aufgerufen von row
     */
    public function afterInsert($row)
    {
        $id = $this->_getUniqueId($row->getRow());
        $this->_rows[$id] = $row;
    }

    protected function _getUniqueId($proxiedRow)
    {
        $keys = $this->getPrimaryKey();
        if (!is_array($keys)) $keys = array($keys);
        $ids = array();
        foreach ($keys as $key) {
            $key = $this->transformColumnName($key);
            $ids[] = $proxiedRow->$key;
        }
        return implode('_', $ids);
    }

    public function getRowByProxiedRow($proxiedRow)
    {
        $id = $this->_getUniqueId($proxiedRow);
        if (!isset($this->_rows[$id])) {
            $proxiedRow->setReadOnly(false);
            $exprValues = array();
            foreach (array_keys($this->_exprs) as $k) {
                if (isset($proxiedRow->$k)) {
                    $exprValues[$k] = $proxiedRow->$k;
                }
            }
            $this->_rows[$id] = new $this->_rowClass(array(
                'row' => $proxiedRow,
                'model' => $this,
                'exprValues' => $exprValues
            ));
        }
        return $this->_rows[$id];
    }

    private function _formatField($field, Zend_Db_Select $select = null, $tableNameAlias = null)
    {
        if ($field instanceof Zend_Db_Expr) return $field->__toString();

        if (in_array($field, $this->getOwnColumns())) {
            $f = $this->transformColumnName($field);
            return $this->_fieldWithTableName($f, $tableNameAlias);
        }
        $ret = $this->_formatFieldInternal($field, $select, $tableNameAlias);
        if (!$ret) {
            throw new Kwf_Exception("Can't find field '$field' in model '".get_class($this)."' (Table '".$this->getTableName()."')");
        }

        return $ret;
    }

    protected function _fieldWithTableName($field, $tableNameAlias = null)
    {
        if ($tableNameAlias) {
            return $tableNameAlias.'.'.$field;
        } else {
            return $this->getTableName().'.'.$field;
        }
    }

    private function _formatFieldInternal($field, $dbSelect, $tableNameAlias)
    {
        $siblingOfModels = $this->_proxyContainerModels;
        $siblingOfModels[] = $this;
        foreach ($siblingOfModels as $siblingOf) {
            foreach ($siblingOf->getSiblingModels() as $k=>$m) {
                while ($m instanceof Kwf_Model_Proxy) {
                    $m = $m->getProxyModel();
                }
                if ($m instanceof Kwf_Model_Db) {
                    if (in_array($field, $m->getOwnColumns())) {
                        $ref = $m->getReferenceByModelClass(get_class($siblingOf), $k);
                        $siblingTableName = $m->getTableName();

                        $tablename = $tableNameAlias ? $tableNameAlias : $this->getTableName();
                        $joinCondition = $tablename.'.'.$this->getPrimaryKey()
                            .' = '.$siblingTableName.'.'.$ref['column'];
                        $alreadyJoined = false;
                        $fromPart = $dbSelect->getPart('from');
                        if ($fromPart) {
                            foreach ($fromPart as $join) {
                                if ($join['tableName'] == $siblingTableName && $join['joinCondition'] == $joinCondition) {
                                    $alreadyJoined = true;
                                    break;
                                }
                            }
                        }
                        if (!$alreadyJoined) {
                            $dbSelect->joinLeft($siblingTableName, $joinCondition, array());
                        }
                        // TODO: Eigentlich wäre _fieldWithTableName korrekt
                        // aber dann müsste auch der join über diese funktion laufen
                        return $m->getTableName().'.'.$field;
                    }
                    if (is_string($field)) {
                        $ret = $m->_formatFieldInternal($field, $dbSelect, $tableNameAlias);
                    } else {
                        $ret = $this->_createDbSelectExpression($field, $dbSelect, $m, $tableNameAlias);
                    }
                    if ($ret) return $ret;
                }
            }
        }
        return $this->_formatFieldExpr($field, $dbSelect, $tableNameAlias);
    }

    private function _formatFieldExpr($field, $dbSelect, $tableNameAlias = null)
    {
        $expr = false;

        $depOfModels = $this->_proxyContainerModels;
        $depOfModels[] = $this;
        foreach ($depOfModels as $depOf) {
            if (isset($depOf->_exprs[$field])) {
                $expr = $depOf->_exprs[$field];
                break; // setzt $depOf
            }
        }
        if (!$expr) return false;

        return $this->_createDbSelectExpression($expr, $dbSelect, $depOf, $tableNameAlias);
    }

    /**
     * Workaround
     *
     * @see http://framework.zend.com/issues/browse/ZF-1343
     * @see http://bugs.php.net/bug.php?id=44251
     */
    private function _fixStupidQuoteBug($v)
    {
        if ((strpos($v, '?') !== false || strpos($v, ':') !== false) && strpos($v, '\'') !== false) {
            $v = str_replace('\'', '', $v);
        }
        return $v;
    }

    public function createDbSelect($select, $tableNameAlias = null)
    {
        if (!$select) return null;
        $tablename = $tableNameAlias ? $tableNameAlias : $this->getTableName();
        $dbSelect = $this->getTable()->select();
        if ($tableNameAlias) {
            $dbSelect->from(array(
                $tableNameAlias => $this->getTableName()
            ));
        } else {
            $dbSelect->from($this->getTableName());
        }
        $this->_applySelect($dbSelect, $select);
        return $dbSelect;
    }

    protected function _applySelect(Zend_Db_Select $dbSelect, Kwf_Model_Select $select)
    {
        if ($dbSelect instanceof Zend_Db_Table_Select) {
            $dbSelect->setIntegrityCheck(false);
        }

        if ($whereEquals = $select->getPart(Kwf_Model_Select::WHERE_EQUALS)) {
            foreach ($whereEquals as $field=>$value) {
                if (is_array($value)) {
                    if ($value) {
                        foreach ($value as &$v) {
                            if (!is_int($v)) {
                                $v = $this->_fixStupidQuoteBug($v);
                                $v = $this->getAdapter()->quote($v);
                            }
                        }
                        $value = implode(', ', $value);
                        $dbSelect->where($this->_formatField($field, $dbSelect)." IN ($value)");
                    } else {
                        $dbSelect->where('0');
                    }
                } else {
                    $value = $this->_fixStupidQuoteBug($value);
                    $dbSelect->where($this->_formatField($field, $dbSelect)." = ?", $value);
                }
            }
        }
        if ($whereNotEquals = $select->getPart(Kwf_Model_Select::WHERE_NOT_EQUALS)) {
            foreach ($whereNotEquals as $field=>$value) {
                if (is_array($value)) {
                    foreach ($value as &$v) {
                        if (!is_int($v)) {
                            $v = $this->_fixStupidQuoteBug($v);
                            $v = $this->getAdapter()->quote($v);
                        }
                    }
                    $value = implode(', ', $value);
                    $dbSelect->where($this->_formatField($field, $dbSelect)." NOT IN ($value)");
                } else {
                    $value = $this->_fixStupidQuoteBug($value);
                    $dbSelect->where($this->_formatField($field, $dbSelect)." != ?", $value);
                }
            }
        }
        if ($this->_hasDeletedFlag && !$select->getPart(Kwf_Model_Select::IGNORE_DELETED)) {
            $dbSelect->where("deleted = 0");
        }
        if ($where = $select->getPart(Kwf_Model_Select::WHERE)) {
            foreach ($where as $w) {
                $dbSelect->where($w[0], $w[1], $w[2]);
            }
        }

        if ($whereId = $select->getPart(Kwf_Model_Select::WHERE_ID)) {
            $whereId = $this->_fixStupidQuoteBug($whereId);
            $dbSelect->where($this->_formatField($this->getPrimaryKey(), $dbSelect)." = ?", $whereId);
        }

        if ($whereNull = $select->getPart(Kwf_Model_Select::WHERE_NULL)) {
            foreach ($whereNull as $field) {
                $dbSelect->where("ISNULL(".$this->_formatField($field, $dbSelect).")");
            }
        }

        if ($other = $select->getPart(Kwf_Model_Select::OTHER)) {
            foreach ($other as $i) {
                call_user_func_array(array($dbSelect, $i['method']), $i['arguments']);
            }
        }
        if ($whereExpression = $select->getPart(Kwf_Model_Select::WHERE_EXPRESSION)) {
            foreach ($whereExpression as $expr) {
                $expr->validate();
                $dbSelect->where($this->_createDbSelectExpression($expr, $dbSelect));
            }
        }

        if ($exprs = $select->getPart(Kwf_Model_Select::EXPR)) {
            foreach ($exprs as $field) {
                if (!$col = $this->_formatField($field, $dbSelect)) {
                    throw new Kwf_Exception("Expression '$field' not found");
                }
                $dbSelect->from(null, array($field=>new Zend_Db_Expr($col)));
            }
        }
    }

    private static function _getInnerDbModel2($model)
    {
        if ($model instanceof Kwf_Model_Db) return $model;
        if ($model instanceof Kwf_Model_Proxy) {
            $ret = self::_getInnerDbModel2($model->getProxyModel());
            if ($ret) return $ret;
        }
        if ($model instanceof Kwf_Model_MirrorCacheSimple || $model instanceof Kwf_Model_RowsSubModel_MirrorCacheSimple) {
            $ret = self::_getInnerDbModel2($model->getSourceModel());
            if ($ret) return $ret;
        }
        return null;
    }

    private static function _getInnerDbModel($model)
    {
        if (is_string($model)) $model = Kwf_Model_Abstract::getInstance($model);
        $ret = self::_getInnerDbModel2($model);
        if (!$ret) {
            throw new Kwf_Exception_NotYetImplemented();
        }
        return $ret;
    }

    private function _createDbSelectExpression($expr, $dbSelect, $depOf = null, $tableNameAlias = null)
    {
        // wenn die expr von anderen models kommt (bei ProxyModel), dann
        // brauchen wir das model, dass die expr gesetzt hat (siehe Child oder Parent)
        if (is_null($depOf)) {
            $depOf = $this;
        }
        if ($expr instanceof Kwf_Model_Select_Expr_CompareField_Abstract) {
            $quotedValue = $expr->getValue();
            if (is_array($quotedValue)) {
                foreach ($quotedValue as &$v) {
                    $v = $this->_fixStupidQuoteBug($v);
                    $v = $this->getTable()->getAdapter()->quote($v);
                }
            } else if ($quotedValue instanceof Kwf_Model_Select_Expr_Interface) {
                $quotedValue = $this->_createDbSelectExpression($quotedValue, $dbSelect, $depOf, $tableNameAlias);
            } else {
                if ($quotedValue instanceof Kwf_DateTime) {
                    $quotedValue = $quotedValue->format('Y-m-d H:i:s');
                } else if ($quotedValue instanceof Kwf_Date) {
                    $quotedValue = $quotedValue->format('Y-m-d');
                }
                $quotedValue = $this->_fixStupidQuoteBug($quotedValue);
                $quotedValue = $this->getTable()->getAdapter()->quote($quotedValue);
            }
        }
        if ($expr instanceof Kwf_Model_Select_Expr_CompareField_Abstract ||
            $expr instanceof Kwf_Model_Select_Expr_IsNull
        ) {
            $field = $expr->getField();
            if ($field instanceof Kwf_Model_Select_Expr_Interface) {
                $field = $this->_createDbSelectExpression($field, $dbSelect, $depOf, $tableNameAlias);
            } else {
                $field = $this->_formatField($field, $dbSelect, $tableNameAlias);
            }
        }
        if ($expr instanceof Kwf_Model_Select_Expr_Equal) {
            if (is_array($quotedValue)) {
                return $field." IN (".implode(',', $quotedValue).")";
            } else {
                return $field." = ".$quotedValue;
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_NotEquals) {
            if (is_array($quotedValue)) {
                return $field." NOT IN (".implode(',', $quotedValue).")";
            } else {
                return $field." != ".$quotedValue;
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_IsNull) {
            return $field." IS NULL";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Lower) {
            return $field." < ".$quotedValue;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Higher) {
            return $field." > ".$quotedValue;
        } else if ($expr instanceof Kwf_Model_Select_Expr_LowerEqual) {
            return $field." <= ".$quotedValue;
        } else if ($expr instanceof Kwf_Model_Select_Expr_HigherEqual) {
            return $field." >= ".$quotedValue;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Like) {
            $quotedValue = str_replace("_", "\\_", $quotedValue);
            if ($expr instanceof Kwf_Model_Select_Expr_Contains) {
                $v = $expr->getValue();
                $v = $this->_fixStupidQuoteBug($v);
                $quotedValueContains = $this->getTable()->getAdapter()->quote('%'.$v.'%');

                $quotedValue = str_replace("%", "\\%", $quotedValue);
                $quotedValue = str_replace(
                                substr($quotedValueContains, 2, strlen($quotedValueContains)-4),
                                substr($quotedValue, 1, strlen($quotedValue)-2),
                                $quotedValueContains);
            }
            return $field." LIKE ".$quotedValue;
        } else if ($expr instanceof Kwf_Model_Select_Expr_RegExp) {
            return $field." REGEXP ".$quotedValue;
        } else if ($expr instanceof Kwf_Model_Select_Expr_StartsWith) {
            $v = $expr->getValue();
            $v = str_replace("_", "\\_", $v);
            $v = str_replace("%", "\\%", $v);
            $v .= '%';
            $v = $this->_fixStupidQuoteBug($v);
            $v = $this->getTable()->getAdapter()->quote($v);
            return "$field LIKE $v";
        } else if ($expr instanceof Kwf_Model_Select_Expr_NOT) {
            return "NOT (".$this->_createDbSelectExpression($expr->getExpression(), $dbSelect, $depOf, $tableNameAlias).")";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Or) {
            $sqlExpressions = array();
            foreach ($expr->getExpressions() as $expression) {
                $sqlExpressions[] = "(".$this->_createDbSelectExpression($expression, $dbSelect, $depOf, $tableNameAlias).")";
            }
            return implode(" OR ", $sqlExpressions);
        } else if ($expr instanceof Kwf_Model_Select_Expr_And) {
            $sqlExpressions = array();
            foreach ($expr->getExpressions() as $expression) {
                $sqlExpressions[] = "(".$this->_createDbSelectExpression($expression, $dbSelect, $depOf, $tableNameAlias).")";
            }
            return implode(" AND ", $sqlExpressions);
        } else if ($expr instanceof Kwf_Model_Select_Expr_Add) {
            $sqlExpressions = array();
            foreach ($expr->getExpressions() as $expression) {
                $sqlExpressions[] = "(".$this->_createDbSelectExpression($expression, $dbSelect, $depOf, $tableNameAlias).")";
            }
            return implode(" + ", $sqlExpressions);
        } else if ($expr instanceof Kwf_Model_Select_Expr_Subtract) {
            $sqlExpressions = array();
            foreach ($expr->getExpressions() as $expression) {
                $sqlExpressions[] = "(".$this->_createDbSelectExpression($expression, $dbSelect, $depOf, $tableNameAlias).")";
            }
            $sql = implode(" - ", $sqlExpressions);
            if (!$expr->lowerNullAllowed) {
                $sql = "IF (($sql > 0), $sql, 0)";
            }
            return $sql;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Divide) {
            $sqlExpressions = array();
            foreach ($expr->getExpressions() as $expression) {
                $sqlExpressions[] = "(".$this->_createDbSelectExpression($expression, $dbSelect, $depOf, $tableNameAlias).")";
            }
            $sql = implode(" / ", $sqlExpressions);
            return $sql;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Multiply) {
            $sqlExpressions = array();
            foreach ($expr->getExpressions() as $expression) {
                $sqlExpressions[] = "(".$this->_createDbSelectExpression($expression, $dbSelect, $depOf, $tableNameAlias).")";
            }
            $sql = implode(" * ", $sqlExpressions);
            return $sql;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Concat) {
            $sqlExpressions = array();
            foreach ($expr->getExpressions() as $expression) {
                            if ($expression instanceof Kwf_Model_Select_Expr_Interface) {
                    $sqlExpressions[] = $this->_createDbSelectExpression($expression, $dbSelect, $depOf, $tableNameAlias);
                } else {
                    $sqlExpressions[] = $this->_formatField($expression, $dbSelect, $tableNameAlias);
                }
            }
            return 'CONCAT('.implode(", ", $sqlExpressions).')';
        } else if ($expr instanceof Kwf_Model_Select_Expr_StrPad) {
            $field = $expr->getField();
            if ($field instanceof Kwf_Model_Select_Expr_Interface) {
                $field = $this->_createDbSelectExpression($field, $dbSelect, $depOf, $tableNameAlias);
            } else {
                $field = $this->_formatField($field, $dbSelect, $tableNameAlias);
            }
            if ($expr->getPadType() == Kwf_Model_Select_Expr_StrPad::RIGHT) {
                $pad = 'RPAD';
            } else if ($expr->getPadType() == Kwf_Model_Select_Expr_StrPad::LEFT) {
                $pad = 'LPAD';
            } else {
                throw new Kwf_Exception_NotYetImplemented();
            }
            return $pad."($field, {$expr->getPadLength()}, {$expr->getPadStr()})";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Date_Year) {
            $field = $expr->getField();
            $format = $expr->getFormat();
            if ($field instanceof Kwf_Model_Select_Expr_Interface) {
                $field = $this->_createDbSelectExpression($field, $dbSelect, $depOf, $tableNameAlias);
            } else {
                $field = $this->_formatField($field, $dbSelect, $tableNameAlias);
            }
            return "DATE_FORMAT($field, '%$format')";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Date_Format) {
            $field = $expr->getField();
            $format = $expr->getFormat();
            if ($field instanceof Kwf_Model_Select_Expr_Interface) {
                $field = $this->_createDbSelectExpression($field, $dbSelect, $depOf, $tableNameAlias);
            } else {
                $field = $this->_formatField($field, $dbSelect, $tableNameAlias);
            }
            $format = str_replace(array('Y', 'm', 'd'), array('%Y', '%m', '%d'), $format);
            return "DATE_FORMAT($field, '$format')";
        } else if ($expr instanceof Kwf_Model_Select_Expr_String) {
            $quotedString = $this->_fixStupidQuoteBug($expr->getString());
            $quotedString = $this->getTable()->getAdapter()->quote($quotedString);
            return $quotedString;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Boolean) {
            return $expr->getValue() ? new Zend_Db_Expr('TRUE') : new Zend_Db_Expr('FALSE');
        } else if ($expr instanceof Kwf_Model_Select_Expr_Count) {
            $field = $expr->getField();
            if ($field != '*') {
                $field = $this->_formatField($field, $dbSelect, $tableNameAlias);
            }
            if ($expr->getDistinct()) $field = "DISTINCT $field";
            return "COUNT($field)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Sum) {
            $field = $this->_formatField($expr->getField(), $dbSelect, $tableNameAlias);
            return "SUM($field)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Max) {
            $field = $this->_formatField($expr->getField(), $dbSelect, $tableNameAlias);
            return "MAX($field)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Min) {
            $field = $this->_formatField($expr->getField(), $dbSelect, $tableNameAlias);
            return "MIN($field)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Area) {
            $lat1 = $this->_formatField('latitude', $dbSelect, $tableNameAlias);
            // calculate radian-values because mysql sin and cos does only work with radians
            $lat2 = deg2rad($expr->getLatitude());
            $long1 = $this->_formatField('longitude', $dbSelect, $tableNameAlias);
            // calculate radian-values because mysql sin and cos does only work with radians
            $long2 = deg2rad($expr->getLongitude());
            $radius = $expr->getRadius();
            // calculate radian-values also directly with mysql because we don't have the
            // values for lat1 and long1 but their field-name/expression
            return "
                (ACOS(
                    SIN(RADIANS($lat1)) * SIN($lat2) +
                    COS(RADIANS($lat1)) * COS($lat2) *
                    COS($long2 - RADIANS($long1))
                ) * 6378.137) <= $radius
            ";
        } else if ($expr instanceof Kwf_Model_Select_Expr_GroupConcat) {
            $field = $this->_formatField($expr->getField(), $dbSelect, $tableNameAlias);
            return "GROUP_CONCAT($field SEPARATOR ".$this->getAdapter()->quote($expr->getSeparator()).")";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Child) {
            $d = $depOf->getDependentModelWithDependentOf($expr->getChild());
            $depM = $d['model'];
            $ref = $d['model']->getReferenceByModelClass(get_class($d['dependentOf']), isset($d['rule']) ? $d['rule'] : null);

            $dbDepM = self::_getInnerDbModel($depM);
            $dbDepOf = self::_getInnerDbModel($depOf);

            $depTableName = $dbDepM->getTableName();
            $depSelect = $expr->getSelect();
            if (!$depSelect) $depSelect = $dbDepM->select();
            $depDbSelect = $dbDepM->_getDbSelect($depSelect);
            $depDbSelect->where($dbDepM->_formatField($ref['column'])."=".$dbDepOf->_formatField($dbDepOf->getPrimaryKey(), $depDbSelect, $tableNameAlias));
            $exprStr = new Zend_Db_Expr($dbDepM->_createDbSelectExpression($expr->getExpr(), $depDbSelect));
            $depDbSelect->reset(Zend_Db_Select::COLUMNS);
            $depDbSelect->from(null, $exprStr);
            return "($depDbSelect)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Child_Contains) {
            $i = $depOf->getDependentModelWithDependentOf($expr->getChild());
            $depM = $i['model'];
            $depOf = $i['dependentOf'];
            $depM = Kwf_Model_Abstract::getInstance($depM);
            $dbDepM = $depM;
            while ($dbDepM instanceof Kwf_Model_Proxy) {
                $dbDepM = $dbDepM->getProxyModel();
            }
            if (!$dbDepM instanceof Kwf_Model_Db) {
                throw new Kwf_Exception_NotYetImplemented();
            }
            $dbDepOf = $depOf;
            while ($dbDepOf instanceof Kwf_Model_Proxy) {
                $dbDepOf = $dbDepOf->getProxyModel();
            }
            if (!$dbDepOf instanceof Kwf_Model_Db) {
                throw new Kwf_Exception_NotYetImplemented();
            }
            $d = $depOf->getDependentModelWithDependentOf($expr->getChild());
            $ref = $d['model']->getReferenceByModelClass(get_class($d['dependentOf']), isset($d['rule']) ? $d['rule'] : null);
            $depSelect = $expr->getSelect();
            if (!$depSelect) $depSelect = $dbDepM->select();
            $col1 = $dbDepM->_formatField($ref['column'], null /* select fehlt - welches ist das korrekte?*/);
            $col2 = $dbDepOf->transformColumnName($dbDepOf->getPrimaryKey());
            $depDbSelect = $dbDepM->_getDbSelect($depSelect);
            $depDbSelect->reset(Zend_Db_Select::COLUMNS);
            $depDbSelect->from(null, $col1);
            return $this->_fieldWithTableName($this->getPrimaryKey(), $tableNameAlias)." IN ($depDbSelect)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Child_First) {
            $depM = $depOf->getDependentModel($expr->getChild());
            $dbDepM = self::_getInnerDbModel($depM);
            $dbDepOf = self::_getInnerDbModel($depOf);

            $depTableName = $dbDepM->getTableName();
            $ref = $depM->getReferenceByModelClass(get_class($depOf), null/*todo*/);
            $depSelect = $expr->getSelect();
            if (!$depSelect) {
                $depSelect = $dbDepM->select();
            } else {
                //wir führen unten ein where aus, das darf nicht im original select bleiben
                $depSelect = clone $depSelect;
            }
            $col1 = $dbDepM->transformColumnName($ref['column']);
            $col2 = $dbDepOf->transformColumnName($dbDepOf->getPrimaryKey());
            $depSelect->where("$depTableName.$col1={$dbDepOf->getTableName()}.$col2");
            $depDbSelect = $dbDepM->_getDbSelect($depSelect);
            $exprStr = $dbDepM->_formatField($expr->getField(), $depDbSelect);
            $depDbSelect->reset(Zend_Db_Select::COLUMNS);
            $depDbSelect->from(null, $exprStr);
            $depDbSelect->limit(1);
            return "($depDbSelect)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Parent) {
            $refM = $depOf->getReferencedModel($expr->getParent());
            $dbRefM = self::_getInnerDbModel($refM);
            $dbDepOf = self::_getInnerDbModel($depOf);
            $ref = $depOf->getReference($expr->getParent());
            $refSelect = $dbRefM->select();
            if ($ref === Kwf_Model_RowsSubModel_Interface::SUBMODEL_PARENT) {
                $ref = $dbDepOf->getReferenceByModelClass($depOf->getParentModel(), null);
            }

            $col1 = $dbDepOf->_formatField($ref['column'], $dbSelect, $tableNameAlias);
            static $parentNum = 0;
            $refTableNameAlias = $dbRefM->getTableName().'_parent'.($parentNum++);
            $col2 = $dbRefM->_formatField($dbRefM->getPrimaryKey(), $dbSelect, $refTableNameAlias);

            $refSelect->where("$col2=$col1");
            $refDbSelect = $dbRefM->createDbSelect($refSelect, $refTableNameAlias);
            $f = $expr->getField();
            if (is_string($f)) {
                $exprStr = new Zend_Db_Expr($dbRefM->_formatField($f, $refDbSelect, $refTableNameAlias));
            } else {
                $exprStr = new Zend_Db_Expr($dbRefM->_createDbSelectExpression($f, $refDbSelect, $refM, $refTableNameAlias));
            }
            $refDbSelect->reset(Zend_Db_Select::COLUMNS);
            $refDbSelect->from(null, $exprStr);
            return "($refDbSelect)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Field) {
            $field = $this->_formatField($expr->getField(), $dbSelect, $tableNameAlias);
            return $field;
        } else if ($expr instanceof Kwf_Model_Select_Expr_PrimaryKey) {
            $field = $this->_formatField($this->getPrimaryKey(), $dbSelect, $tableNameAlias);
            return $field;
        } else if ($expr instanceof Kwf_Model_Select_Expr_SumFields) {
            $sqlExpressions = array();
            foreach ($expr->getFields() as $expression) {
                if (is_int($expression)) {
                    $sqlExpressions[] = $expression;
                } else if (is_string($expression)) {
                    $sqlExpressions[] = $this->_formatField($expression, $dbSelect, $tableNameAlias);
                } else if ($expression instanceof Kwf_Model_Select_Expr_Interface) {
                    $sqlExpressions[] = $this->_createDbSelectExpression($expression, $dbSelect, $tableNameAlias);
                } else {
                    throw new Kwf_Exception_NotYetImplemented();
                }
            }
            return '('.implode('+ ', $sqlExpressions).')';
        } else if ($expr instanceof Kwf_Model_Select_Expr_Sql) {
            foreach ($expr->getUsedColumns() as $f) {
                //mit dem rückgabewert nichts machen, das ist nur zum joinen von sibling models
                $this->_formatFieldInternal($f, $dbSelect, $tableNameAlias);
            }
            $sql = $expr->getSql();
            if (preg_match_all('#expr\{([a-zA-Z0-9_]+)\}#', $sql, $exprs)) {
                foreach ($exprs[1] as $k => $e) {
                    $sql = str_replace($exprs[0][$k], $this->_formatField($e, $dbSelect, $tableNameAlias), $sql);
                }
            }
            return '('.$sql.')';
        } else if ($expr instanceof Kwf_Model_Select_Expr_If) {
            $if = $this->_createDbSelectExpression($expr->getIf(), $dbSelect, $depOf, $tableNameAlias);
            $then = $this->_createDbSelectExpression($expr->getThen(), $dbSelect, $depOf, $tableNameAlias);
            $else = $this->_createDbSelectExpression($expr->getElse(), $dbSelect, $depOf, $tableNameAlias);
            return "IF($if, $then, $else)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_Position) {
            $field = $this->_formatField($expr->getField(), $dbSelect, $tableNameAlias);
            static $positionNum = 0;
            $alias = ($tableNameAlias ? $tableNameAlias : $this->getTableName()) . '_expr_position'.($positionNum++);
            $aliasIdField = $this->_formatField($this->getPrimaryKey(), null, $alias);
            $aliasField = $this->_formatField($expr->getField(), null, $alias);
            if ($expr->getDirection() == Kwf_Model_Select_Expr_Position::DIRECTION_ASC) {
                $direction = '<';
            } else {
                $direction = '>';
            }
            $ret = "SELECT COUNT($aliasIdField)+1 FROM ".$this->getTableName()." $alias
                WHERE $aliasField $direction $field";
            foreach ($expr->getGroupBy() as $g) {
                $field = $this->_formatField($g, $dbSelect, $tableNameAlias);
                $aliasField = $this->_formatField($g, null, $alias);
                $ret .= " AND $field=$aliasField";
            }
            return "($ret)";
        } elseif ($expr instanceof Kwf_Model_Select_Expr_Date_Age) {
            $birthDate = $this->_formatField($expr->getField(), $dbSelect, $tableNameAlias);
            $referenceYear = $expr->getDate()->format('Y');
            $referenceDate = $expr->getDate()->format();
            return "IF($birthDate,($referenceYear-YEAR($birthDate)) - (RIGHT('$referenceDate',5)<RIGHT($birthDate,5)), NULL)";
        } else if ($expr instanceof Kwf_Model_Select_Expr_SearchLike) {
            $e = $expr->getQueryExpr($this);
            if (!$e) return 'TRUE';
            return $this->_createDbSelectExpression($e, $dbSelect, $depOf, $tableNameAlias);
        } else {
            throw new Kwf_Exception_NotYetImplemented("Expression not yet implemented: ".get_class($expr));
        }
    }

    public function getExprValue($row, $name)
    {
        if ($name instanceof Kwf_Model_Select_Expr_Interface) {
            $expr = $name;
        } else {
            $expr = $this->_exprs[$name];
        }
        if ($expr instanceof Kwf_Model_Select_Expr_Sql) {
            $select = $this->select();
            $select->whereEquals($this->getPrimaryKey(), $row->{$this->getPrimaryKey()});
            $select->limit(1);
            $options = array(
                'columns' => array($name)
            );
            $dbSelect = $this->_createDbSelectWithColumns($select, $options);
            return $dbSelect->query()->fetchColumn();
        }

        return parent::getExprValue($row, $name);
    }

    //Nur zum Debuggen verwenden!
    public function getSqlForSelect($select)
    {
        $dbSelect = $this->_getDbSelect($select);
        return $dbSelect->__toString();
    }

    public function find($id)
    {
        return new $this->_rowsetClass(array(
            'rowset' => $this->getTable()->find($id),
            'rowClass' => $this->_rowClass,
            'model' => $this
        ));
    }

    public function getRow($select)
    {
        if (is_string($select) || is_int($select)) {
            //primary key given, skip query and use already existing row
            if (!is_array($this->getPrimaryKey())) {
                $select = $this->transformColumnName($select);
                if (isset($this->_rows[$select])) {
                    return $this->_rows[$select];
                }
            }
        }
        return parent::getRow($select);
    }

    public function getIds($select = array(), $order=null, $limit=null, $start=null)
    {
        if (!is_object($select)) {
            $select = $this->select($select, $order, $limit, $start);
        }
        $rows = $this->export(
            Kwf_Model_Abstract::FORMAT_ARRAY,
            $select,
            array('columns'=>array($this->getPrimaryKey()))
        );
        $ret = array();
        foreach ($rows as $i) {
            $ret[] = $i[$this->getPrimaryKey()];
        }
        return $ret;
    }

    public function getRows($where = array(), $order=null, $limit=null, $start=null)
    {
        $dbSelect = $this->_getDbSelect($where, $order, $limit, $start);
        return new $this->_rowsetClass(array(
            'rowset' => $this->getTable()->fetchAll($dbSelect),
            'rowClass' => $this->_rowClass,
            'model' => $this
        ));
    }

    private function _getTableUpdateWhere($where)
    {
        if (!is_object($where)) {
            if (is_string($where)) $where = array($where);
            $select = $this->select($where);
        } else {
            $select = $where;
        }
        if ($select->getPart(Kwf_Model_Select::OTHER) ||
            $select->getPart(Kwf_Model_Select::LIMIT_COUNT) ||
            $select->getPart(Kwf_Model_Select::LIMIT_OFFSET))
            throw new Kwf_Exception('Select for update must only contain where* parts');
        $dbSelect = new Zend_Db_Select($this->getAdapter());
        $this->_applySelect($dbSelect, $select);
        $where = array();
        foreach ($dbSelect->getPart('where') as $part) {
            if (substr($part, 0, 4) == 'AND ') $part = substr($part, 4);
            $where[] = $part;
        }
        return $where;
    }

    public function deleteRows($where)
    {
        if ($this->hasDeletedFlag()) {
            $ret = $this->updateRows(array('deleted' => true), $where);
        } else {
            $ret = $this->getTable()->delete($this->_getTableUpdateWhere($where));
        }
        $this->_afterDeleteRows($where);
        return $ret;
    }

    public function updateRows($data, $where)
    {
        return $this->getTable()->update($data, $this->_getTableUpdateWhere($where));
    }

    private function _getDbSelect($where, $order=null, $limit=null, $start=null)
    {
        if (!is_object($where)) {
            if (is_string($where)) $where = array($where);
            $select = $this->select($where, $order, $limit, $start);
        } else {
            $select = $where;
        }
        $dbSelect = $this->createDbSelect($select);
        if ($order = $select->getPart(Kwf_Model_Select::ORDER)) {
            foreach ($order as $o) {
                if ($o['field'] instanceof Zend_Db_Expr) {
                    $dbSelect->order($o['field']);
                } else if ($o['field'] instanceof Kwf_Model_Select_Expr_Interface) {
                    $dbSelect->order($this->_createDbSelectExpression($o['field'], $dbSelect).' '.$o['direction']);
                } else if ($o['field'] == Kwf_Model_Select::ORDER_RAND) {
                    $dbSelect->order('RAND()');
                } else {
                    if (strpos($o['field'], '.') === false &&
                        strpos($o['field'], '(') === false
                    ) {
                        $o['field'] = $this->_formatField($o['field'], $dbSelect);
                    }
                    $dbSelect->order($o['field'].' '.$o['direction']);
                }
            }
        }
        $limitCount = $select->getPart(Kwf_Model_Select::LIMIT_COUNT);
        $limitOffset = $select->getPart(Kwf_Model_Select::LIMIT_OFFSET);
        if ($limitCount || $limitOffset) {
            $dbSelect->limit($limitCount, $limitOffset);
        }

        if ($select->hasPart(Kwf_Model_Select::UNION)) {
            $unions = array($dbSelect);
            foreach ($select->getPart(Kwf_Model_Select::UNION) as $unionSel) {
                $unions[] = $this->_getDbSelect($unionSel);
            }
            $dbSelect = $this->getTable()->select()->union($unions);
        }

        return $dbSelect;
    }

    public function countRows($select = array())
    {
        if (!is_object($select)) {
            $select = $this->select($select);
        }
        if ($select->hasPart(Kwf_Model_Select::UNION)) {
            throw new Kwf_Exception_NotYetImplemented();
        }

        $dbSelect = $this->createDbSelect($select);
        $dbSelect->reset(Zend_Db_Select::COLUMNS);
        $dbSelect->setIntegrityCheck(false);
        if ($dbSelect->getPart('group')) {
            $group = current($dbSelect->getPart('group'));
            $dbSelect->reset(Zend_Db_Select::GROUP);
            $dbSelect->from(null, "COUNT(DISTINCT $group) c");
        } else {
            $dbSelect->from(null, 'COUNT(*) c');
        }
        return $this->getTable()->getAdapter()->query($dbSelect)->fetchColumn();
    }

    public function evaluateExpr(Kwf_Model_Select_Expr_Interface $expr, Kwf_Model_Select $select = null)
    {
        if (is_null($select)) $select = $this->select();
        $dbSelect = $this->createDbSelect($select);
        $dbSelect->reset(Zend_Db_Select::COLUMNS);
        $dbSelect->setIntegrityCheck(false);
        $dbSelect->from(null, $this->_createDbSelectExpression($expr, $dbSelect));
        return $this->getTable()->getAdapter()->query($dbSelect)->fetchColumn();
    }

    public function getPrimaryKey()
    {
        if (!$this->_primaryKey) {
            $cache = self::_getMetadataCache();
            $cacheId = md5($this->getUniqueIdentifier()).'_primaryKey';
            if (!$this->_primaryKey = $cache->load($cacheId)) {
                $this->_primaryKey = $this->getTable()->info('primary');
                if (sizeof($this->_primaryKey) == 1) {
                    $this->_primaryKey = array_values($this->_primaryKey);
                    $this->_primaryKey = $this->_primaryKey[0];
                }
                $cache->save($this->_primaryKey, $cacheId);
            }
        }
        return $this->_primaryKey;
    }

    public function getTable()
    {
        if (is_string($this->_table)) {
            $this->_tableName = $this->_table;
            $this->_table = new Kwf_Db_Table(array(
                'name' => $this->_table,
                'db' => $this->_db
            ));
        }
        return $this->_table;
    }

    public function getAdapter()
    {
        return $this->getTable()->getAdapter();
    }

    public function getTableName()
    {
        if (!$this->_tableName) {
            if (is_string($this->_table)) return $this->_table;
            return $this->_table->info(Zend_Db_Table_Abstract::NAME);
        }
        return $this->_tableName;
    }

    public function isEqual(Kwf_Model_Interface $other) {
        if ($other instanceof Kwf_Model_Db &&
            $this->getTableName() == $other->getTableName()) {
            return true;
        }
        return false;
    }

    public function select($where = array(), $order = null, $limit = null, $start = null)
    {
        if (!is_array($where)) {
            $ret = new Kwf_Model_Select();
            if ($where) {
                $ret->whereEquals($this->getPrimaryKey(), $where);
            }
        } else {
            $ret = new Kwf_Model_Select($where);
        }
        if ($order) $ret->order($order);
        if ($limit || $start) $ret->limit($limit, $start);
        return $ret;
    }

    public function getUniqueIdentifier()
    {
        return ($this->_db ? $this->_db.'.' : '') . $this->getTableName();
    }

    private function _createDbSelectWithColumns($select, $options)
    {
        $select = clone $select;
        if (isset($options['columns'])) {
            foreach ($options['columns'] as $c) {
                $select->expr($c);
            }
        }
        $dbSelect = $this->_getDbSelect($select);
        if (isset($options['columns'])) {
            $columns = $dbSelect->getPart(Zend_Db_Select::COLUMNS);
            unset($columns[0]); //unset *
            $dbSelect->reset(Zend_Db_Select::COLUMNS);
            $dbSelect->setPart(Zend_Db_Select::COLUMNS, $columns);
        }

        return $dbSelect;
    }

    public function export($format, $select = array(), $options = array())
    {
        if ($format == self::FORMAT_SQL) {
            $wherePart = '';
            if ($select) {
                if (!is_object($select)) {
                    if (is_string($select)) $select = array($select);
                    $select = $this->select($select);
                }
                $dbSelect = $this->_getDbSelect($select);
                $whereParts = $dbSelect->getPart(Zend_Db_Select::WHERE);
                $wherePart = implode(' ', $whereParts);

                // check if a row is exported and quit, if none
                $dbSelect->limit(1);
                $hasRows = $dbSelect->query()->fetchAll();
                if (!count($hasRows)) {
                    return '';
                }
            }
            if ($wherePart) {
                $wherePart = '--where="'.$wherePart.'" ';
            }

            $systemData = $this->_getSystemData();
            $filename = tempnam('/tmp', 'modelimport');

            $cmd = "{$systemData['mysqlDir']}mysqldump --add-drop-table=false ";
            $cmd .= "--skip-add-locks --complete-insert ";
            $cmd .= "--no-create-info=true ".$wherePart
                ."$systemData[mysqlOptions] $systemData[tableName] | gzip -c > $filename";
            exec($cmd, $output, $ret);
            if ($ret != 0) throw new Kwf_Exception("SQL export failed");
            $ret = file_get_contents($filename);
            unlink($filename);
            return $ret;
        } else if ($format == self::FORMAT_CSV) {
            if (!is_object($select)) {
                if (is_string($select)) $select = array($select);
                $select = $this->select($select);
            }

            $tmpExportFolder = realpath('temp').'/modelcsvex'.uniqid();
            $filename = $tmpExportFolder.'/csvexport';

            $dbSelect = $this->_createDbSelectWithColumns($select, $options);
            $sqlString = $dbSelect->assembleIntoOutfile($filename);

            $dbSelect->limit(1);
            $fieldResult = $dbSelect->query()->fetchAll();
            $columnsCsv = '';
            if (count($fieldResult)) {
                mkdir($tmpExportFolder, 0777);
                $columns = array_keys($fieldResult[0]);
                $columnsCsv = '"'.implode('","', $columns).'"';
                $this->executeSql($sqlString);
                $cmd = "{ echo '$columnsCsv'; cat $filename; } | gzip -c > $filename.gz";
                exec($cmd, $output, $ret);
                if ($ret != 0) throw new Kwf_Exception("CSV-SQL export failed");

                if (!file_exists($filename.'.gz')) {
                    throw new Kwf_Exception("Error exporting csv from model - target file has not been created");
                }
                unlink($filename);

                $ret = file_get_contents($filename.'.gz');
                unlink($filename.'.gz');
                rmdir($tmpExportFolder);
                return $ret;
            } else {
                return '';
            }
        } else if ($format == self::FORMAT_ARRAY) {
            if (!is_object($select)) {
                if (is_string($select)) $select = array($select);
                $select = $this->select($select);
            }
            if ($select->hasPart(Kwf_Model_Select::UNION)) {
                $select = clone $select;
                $unions = $select->getPart(Kwf_Model_Select::UNION);
                $select->unsetPart(Kwf_Model_Select::UNION);
                $selects = array($select);
                $selects = array_merge($selects, $unions);
                $ret = array();
                while ($selects) {
                    //split up into blocks of 150, mysql doesn't take more
                    $curSelects = array_splice($selects, 0, min(150, count($selects)));
                    $unions = array();
                    foreach ($curSelects as $s) {
                        $unions[] = $this->_createDbSelectWithColumns($s, $options);
                    }
                    $ret = array_merge($ret, $this->getAdapter()->query(implode(" UNION ", $unions))->fetchAll());
                }
                return $ret;
            } else {
                $dbSelect = $this->_createDbSelectWithColumns($select, $options);
                if (!$dbSelect) return array();
                return $this->getAdapter()->query($dbSelect)->fetchAll();
            }

        } else {
            return parent::export($format, $select);
        }
    }

    private function _updateModelObserver($options)
    {
        if (isset($options['skipModelObserver']) && $options['skipModelObserver']) return;

        if (Kwf_Component_Data_Root::getComponentClass()) {
            if ($this->_proxyContainerModels) {
                foreach ($this->_proxyContainerModels as $m) {
                    Kwf_Component_ModelObserver::getInstance()->add('update', $m);
                }
            } else {
                Kwf_Component_ModelObserver::getInstance()->add('update', $this);
            }
        }
    }

    public function import($format, $data, $options = array())
    {
        if ($format == self::FORMAT_SQL) {
            // if no data is recieved, quit
            if (!$data) return;

            $filename = tempnam('/tmp', 'modelimport');
            file_put_contents($filename, $data);

            $systemData = $this->_getSystemData();
            $cmd = "gunzip -c $filename ";
            if (isset($options['replace']) && $options['replace']) {
                $cmd .= "| sed -e \"s|INSERT INTO|REPLACE INTO|\"";
            }
            if (isset($options['ignorePrimaryKey']) && $options['ignorePrimaryKey']) {
                $primaryKey = $this->getPrimaryKey();
                $cmd .= " | sed -e \"s|(\`".$primaryKey."\`,|(|\" -e \"s|([0-9]*,|(|g\"";
            }

            $cmd .= "| {$systemData['mysqlDir']}mysql $systemData[mysqlOptions] 2>&1";
            exec($cmd, $output, $ret);
            unlink($filename);
            $this->_updateModelObserver($options);
            if ($ret != 0) throw new Kwf_Exception("SQL import failed: ".implode("\n", $output));
            $this->_afterImport($format, $data, $options);
        } else if ($format == self::FORMAT_CSV) {
            // if no data is recieved, quit
            if (!$data) return;

            $tmpImportFolder = tempnam('temp/', 'modelcsvim');
            unlink($tmpImportFolder);
            mkdir($tmpImportFolder, 0777);
            $filename = $tmpImportFolder.'/csvimport';
            file_put_contents($filename.'.gz', $data);

            $cmd = "gunzip -c $filename.gz > $filename"
                ." && head --lines=1 $filename | sed -e 's|\"|`|g'";
            exec($cmd, $output, $ret);
            if ($ret != 0) throw new Kwf_Exception("CSV-SQL export failed");

            $fieldNames = trim($output[0]);
            if ($fieldNames) {
                // set the character_set_database MySQL system variable to utf8
                $this->executeSql("SET character_set_database = 'utf8'");

                $sqlString = "LOAD DATA INFILE '$filename'";
                if (isset($options['replace']) && $options['replace']) {
                    $sqlString .= " REPLACE";
                }
                $sqlString .= " INTO TABLE `".($this->getTableName())."`";
                $sqlString .= " FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n'";
                $sqlString .= " IGNORE 1 LINES";
                $sqlString .= " ($fieldNames)";

                $this->executeSql($sqlString);
            }

            unlink($filename.'.gz');
            unlink($filename);
            rmdir($tmpImportFolder);
            $this->_updateModelObserver($options);
            $this->_afterImport($format, $data, $options);
        } else if ($format == self::FORMAT_ARRAY) {
            if (isset($options['buffer']) && $options['buffer']) {
                if (isset($this->_importBuffer)) {
                    if ($options != $this->_importBufferOptions) {
                        throw new Kwf_Exception_NotYetImplemented("You can't buffer imports with different options (not yet implemented)");
                    }
                    $this->_importBuffer = array_merge($this->_importBuffer, $data);
                    // handling for not sending too much data to mysql in one query
                    // is in _importArray() function
                } else {
                    $this->_importBufferOptions = $options;
                    $this->_importBuffer = $data;
                }
                if ($options['buffer'] !== true && count($this->_importBuffer) > $options['buffer']) {
                    $this->writeBuffer();
                }
            } else {
                $this->_importArray($data, $options);
            }
            $this->_updateModelObserver($options);
            $this->_afterImport($format, $data, $options);
        } else {
            parent::import($format, $data);
        }
    }

    private function _getSystemData()
    {
        $ret = array();

        $dbConfig = Zend_Registry::get('db')->getConfig();
        $ret['mysqlOptions'] = "--host={$dbConfig['host']} --user={$dbConfig['username']} --password={$dbConfig['password']} {$dbConfig['dbname']} ";
        $config = Zend_Registry::get('config');

        $ret['mysqlDir'] = '';
        if (trim(`hostname`) == "vivid-sun") {
            $ret['mysqlDir'] = '/usr/local/mysql/bin/';
        }
        $ret['tableName'] = $this->getTableName();

        return $ret;
    }

    public function writeBuffer()
    {
        parent::writeBuffer();
        if (isset($this->_importBuffer)) {
            $this->_importArray($this->_importBuffer, $this->_importBufferOptions);
            unset($this->_importBuffer);
            unset($this->_importBufferOptions);
        }
    }

    private function _importArray($data, $options)
    {
        if (empty($data)) return;
        if ($this->getSiblingModels()) {
            if ($options) {
                throw new Kwf_Exception_NotYetImplemented("import options together with siblingModels are not yet implemented");
            }
            foreach ($data as $r) {
                $this->createRow($r)->save();
            }
            return;
        }
        $data = array_values($data);
        $fields = array_keys($data[0]);
        if (isset($options['replace']) && $options['replace']) {
            $sqlTableAndColumns = 'REPLACE';
        } else {
            $sqlTableAndColumns = 'INSERT';
        }
        foreach ($fields as &$f) {
            $f = $this->transformColumnName($f);
        }
        if (isset($options['ignore']) && $options['ignore'])
            $sqlTableAndColumns .= ' IGNORE';
        $sqlTableAndColumns .= ' INTO '.$this->getTableName().' (`'.implode('`, `', $fields).'`) VALUES ';
        $sqlValues = '';
        foreach ($data as $d) {
            if (array_keys($d) != array_keys($data[0])) {
                throw new Kwf_Exception_NotYetImplemented("You must have always the same keys when importing");
            }
            $sqlValues .= '(';
            foreach ($d as $i) {
                if (is_null($i)) {
                    $sqlValues .= 'NULL';
                } else {
                    $sqlValues .= $this->getTable()->getAdapter()->quote($i);
                }
                $sqlValues .= ',';
            }
            $sqlValues = substr($sqlValues, 0, -1);
            $sqlValues .= '),';

            // write buffer when mysql string will get over 700K
            // normally mysql supports string up to 1M
            if (strlen($sqlValues) > 700000) {
                $this->executeSql($sqlTableAndColumns.substr($sqlValues, 0, -1));
                $sqlValues = '';
            }
        }
        if ($sqlValues) {
            $this->executeSql($sqlTableAndColumns.substr($sqlValues, 0, -1));
        }
    }

    public function executeSql($sql)
    {
        // Performance, bei Pdo wird der Adapter umgangen
        if ($this->getTable()->getAdapter() instanceof Zend_Db_Adapter_Pdo_Mysql) {
            $q = $this->getTable()->getAdapter()->getProfiler()->queryStart($sql, Zend_Db_Profiler::INSERT);
            $this->getTable()->getAdapter()->getConnection()->exec($sql);
            $this->getTable()->getAdapter()->getProfiler()->queryEnd($q);
        } else {
            $this->getTable()->getAdapter()->query($sql);
        }
    }

    public function getSupportedImportExportFormats()
    {
        if ($this->getSiblingModels()) {
            return array(self::FORMAT_ARRAY);
        } else {
            $ret = $this->_supportedImportExportFormats;
            foreach ($ret as $k => $v) {
                if ($v === self::FORMAT_CSV) {
                    // check if csv is possible with current database rights
                    if (!Kwf_Util_Mysql::getFileRight()) {
                        unset($ret[$k]);
                    }
                } else if ($v === self::FORMAT_SQL) {
                    // check if mysql is available (mainly because of POI Servers,
                    // where mysql is on another server)
                    exec("whereis mysql", $output, $execRet);

                    if ($output && is_array($output) && trim($output[0]) != 'mysql:') {
                        // hier bleibts drin
                    } else {
                        unset($ret[$k]);
                    }
                }
            }
            $ret = array_values($ret);
            return $ret;
        }
    }

    private static function _getMetadataCache()
    {
        static $ret;
        if (!isset($ret)) {
            $frontendOptions = array(
                'automatic_serialization' => true,
                'write_control' => false,
            );
            if (extension_loaded('apc') && php_sapi_name() != 'cli') {
                $backendOptions = array();
                $backend = 'Apc';
            } else {
                $backendOptions = array(
                    'cache_dir' => 'cache/model',
                    'file_name_prefix' => 'servicemeta'
                );
                $backend = 'File';
            }
            $ret = Kwf_Cache::factory('Core', $backend, $frontendOptions, $backendOptions);
        }
        return $ret;
    }

    public function fetchColumnByPrimaryId($column, $id)
    {
        if (in_array($column, $this->_getOwnColumns())) {
            $sql = "SELECT $column FROM ".$this->getTableName()." WHERE ".$this->getPrimaryKey()."=?";
            return Kwf_Registry::get('db')->query($sql, $id)->fetchColumn();
        } else {
            return parent::fetchColumnByPrimaryId($column, $id);
        }
    }

    public function fetchColumnsByPrimaryId(array $columns, $id)
    {
        $sql = "SELECT ".implode(',', $columns)." FROM ".$this->getTableName()." WHERE ".$this->getPrimaryKey()."=?";
        return Kwf_Registry::get('db')->query($sql, $id)->fetch();
    }

    /**
     * @internal
     */
    public function convertValueType($column, $value)
    {
        $type = $this->getColumnType($column);
        return self::convertValueToType($value, $type);
    }
}


text:
using Glass.Mapper.Configuration;
using Sitecore.Data;

namespace Glass.Mapper.Sc.Configuration
{
    /// <summary>
    /// Class SitecoreFieldConfiguration
    /// </summary>
    public class SitecoreFieldConfiguration : FieldConfiguration
    {
        /// <summary>
        /// The name of the field  to use if it is different to the property name
        /// </summary>
        /// <value>The name of the field.</value>
        public string FieldName { get; set; }

        /// <summary>
        /// The ID of the field when used in a code first scenario
        /// </summary>
        /// <value>The field id.</value>
        public ID FieldId { get; set; }

        /// <summary>
        /// Options to override the behaviour of certain fields.
        /// </summary>
        /// <value>The setting.</value>
        public SitecoreFieldSettings Setting { get; set; }

        /// <summary>
        /// Use with Glass.Mapper.Sc.Fields.Link type
        /// </summary>
        public SitecoreInfoUrlOptions UrlOptions { get; set; }

        public SitecoreMediaUrlOptions MediaUrlOptions { get; set; }

        protected override AbstractPropertyConfiguration CreateCopy()
        {
            return new SitecoreFieldConfiguration();
        }

        protected override void Copy(AbstractPropertyConfiguration copy)
        {
            var config = copy as SitecoreFieldConfiguration;
            config.FieldId = FieldId;
            config.FieldName = FieldName;
            config.Setting = Setting;
            config.MediaUrlOptions = MediaUrlOptions;
            config.UrlOptions = UrlOptions;
            base.Copy(copy);
        }

        public virtual void GetPropertyOptions(GetOptions propertyOptions)
        {
            propertyOptions.InferType = (Setting & SitecoreFieldSettings.InferType) == SitecoreFieldSettings.InferType;
            base.GetPropertyOptions(propertyOptions);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace otc {
template<typename, typename> class RootedTree;

typedef std::string namestring_t;

template<typename T>
class RootedTreeNode {
    public:
        using node_type = RootedTreeNode<T>;
        using data_type = T;

        bool isTip() const { return (lChild == nullptr); }

        bool isInternal() const { return not isTip(); }

        const node_type * getParent() const { return parent; }
              node_type * getParent()       { return parent; }

        const node_type * getFirstChild() const { return lChild; }
              node_type * getFirstChild()       { return lChild; }

        const node_type * getLastChild() const { return rChild; }
              node_type * getLastChild()       { return rChild; }

        const node_type * getPrevSib() const { return lSib; }
              node_type * getPrevSib()       { return lSib; }

        const node_type * getNextSib() const { return rSib; }
              node_type * getNextSib()       { return rSib; }

        const node_type * getFirstSib() const { assert(parent); return parent->getFirstChild(); }
              node_type * getFirstSib()       { assert(parent); return parent->getFirstChild(); }

        const node_type * getLastSib() const { assert(parent); return parent->getLastChild(); }
              node_type * getLastSib()       { assert(parent); return parent->getLastChild(); }

        unsigned getOutDegree() const {
            unsigned n = 0;
            auto currNode = getFirstChild();
            while(currNode) {
                n += 1;
                currNode = currNode->getNextSib();
            }
            return n;
        }
        bool hasOttId() const {
            return ottId != LONG_MAX;
        }
        long getOttId() const {
            assert(hasOttId());
            return ottId;
        }
        void setOttId(long i) {
            ottId = i;
            assert(hasOttId());
        }
        void delOttId() {
            ottId = LONG_MAX;
        }
        // non-empty only for internals that are labelled with names that are NOT taxLabels
        const namestring_t & getName() const {
            return name;
        }
        void setName(const namestring_t &n) {
            name = n;
        }
        const T & getData() const {
            return data;
        }
        T & getData() {
            return data;
        }
        RootedTreeNode<T>(RootedTreeNode<T> *par)
            :parent(par) {
        }
        void addSibOnLeft(node_type *n) {
            assert(n);

            // Connect left (from n)
            n->lSib = lSib;
            if (n->lSib)
                n->lSib->rSib = n;
            else
            {
                assert(parent->lChild == this);
                parent->lChild = n;
            }

            // Connect right (from n)
            n->rSib = this;
            lSib = n;

            // Connect up (from n)
            n->parent = parent;
        }
        void addSibOnRight(node_type *n) {
            assert(n);

            // Connect right (from n)
            n->rSib = rSib;
            if (n->rSib)
                n->rSib->lSib = n;
            else
            {
                assert(parent->rChild == this);
                parent->rChild = n;
            }

            // Connect left (from n)
            n->lSib = this;
            rSib = n;

            // Connect up (from n)
            n->parent = parent;
        }
        void addSibAtEnd(node_type *n) {
            getLastSib()->addSibOnRight(n);
        }
        void addSib(node_type *n) {
            addSibAtEnd(n);
        }
        void addChild(node_type *n) {
            if (rChild) {
                rChild->addSib(n);
            } else {
                lChild = n;
                rChild = n;
                n->lSib = nullptr;
                n->rSib = nullptr;
                n->parent = this;
            }
        }
        bool hasChildren() const {
            assert(bool(lChild) == bool(rChild));
            return lChild;
        }
        void removeChild(node_type *n) {
            assert(n);
            assert(hasChildren());
            assert(n->parent == this);
            n->detachThisNode();
        }
        bool isOutDegreeOneNode() const {
            return lChild and not lChild->rSib;
        }
        bool isOutDegreeTwoNode() const {
            return lChild and lChild->rSib and not lChild->rSib->rSib;
        }
        bool isPolytomy() const {
            return lChild and lChild->rSib and lChild->rSib->rSib;
        }
        bool includesOnlyOneLeaf() const {
            if (isTip()) {
                return true;
            }
            return isOutDegreeOneNode() && lChild->includesOnlyOneLeaf();
        }
        // takes this node out of the child array of its parent, but does not fix any other pointer.
        void detachThisNode() {
            assert(parent);
            assert(parent->hasChildren());

            if (lSib)
                lSib->rSib = rSib;
            else
                parent->lChild = rSib;

            if (rSib)
                rSib->lSib = lSib;
            else
                parent->rChild = lSib;

            parent = nullptr;
            rSib = nullptr;
            lSib = nullptr;
        }
    public:
        void writeAsNewick(std::ostream &out,
                           bool useLeafNames,
                           const std::map<node_type *, namestring_t> *nd2name=nullptr) const {
            auto child = getFirstChild();
            if (child) {
                out << "(";
                child->writeAsNewick(out,useLeafNames,nd2name);
                child = child->getNextSib();
                for(;child;child = child->getNextSib()) {
                    out << ",";
                    child->writeAsNewick(out,useLeafNames,nd2name);
                }
                out << ")";
            }
            out << getName();
        }
        void addSelfAndDesToPreorder(std::vector<const node_type *> &p) const;
    private:
        node_type * lChild = nullptr;
        node_type * rChild = nullptr;
        node_type * lSib = nullptr;
        node_type * rSib = nullptr;
        node_type * parent = nullptr;
        namestring_t name;     // non-empty only for internals that are labelled with names that are NOT taxLabels
        long ottId = LONG_MAX; // present for every leaf. UINT_MAX for internals labeled with taxlabels
        T data;
    private:
        RootedTreeNode<T>(const RootedTreeNode<T> &) = delete;
        RootedTreeNode<T> & operator=(const RootedTreeNode<T> &) = delete;
        template<typename Y, typename Z>
        friend class RootedTree;
};

template<typename NodeType>
const NodeType* findRoot(const NodeType* nd)
{
    while(nd->getParent())
        nd = nd->getParent();
    return nd;
}

template<typename T, typename U>
class RootedTree {
    public:
        using node_data_type = T;
        using node_type = RootedTreeNode<T>;
        using data_type = U;

        RootedTree<T, U>()
            :root(nullptr) {
        }
        ~RootedTree<T, U>() {
            clear();
        }
        std::vector<const node_type *> getPreorderTraversal() const;
        void writeAsNewick(std::ostream &out,
                           bool useLeafNames,
                           const std::map<node_type *, namestring_t> *nd2name=nullptr) const {
            if (root) {
                root->writeAsNewick(out, useLeafNames, nd2name);
            }
        }
        const node_type * getRoot() const {
            return root;
        }
        node_type * getRoot() {
            return root;
        }
        void _setRoot(node_type * r) {
            root = r;
        }
        node_type * createRoot() {
            if (root != nullptr) {
                clear();
            }
            this->root = this->allocNewNode(nullptr);
            return this->root;
        }
        node_type * createChild(node_type *par) {
            auto c = this->allocNewNode(par);
            par->addChild(c);
            return c;
        }
        node_type * createNode(node_type *par) {
            auto c = this->allocNewNode(par);
            if (par != nullptr) {
                par->addChild(c);
            }
            return c;
        }
        node_type * createSib(node_type *leftSib) {
            assert(leftSib->parent != nullptr);
            auto s = this->allocNewNode(leftSib->parent);
            leftSib->addSib(s);
            return s;
        }
        U & getData() {
            return this->data;
        }
        const U & getData() const {
            return this->data;
        }
        void pruneAndDangle(node_type * nd) {
            assert(findRoot(nd) == root);
            auto p = nd->getParent();
            if (p == nullptr) {
                root = nullptr;
                return;
            }
            p->removeChild(nd);
        }
        void pruneAndDelete(node_type * nd) {
            auto nodes = getSubtreeNodes(nd);
            pruneAndDangle(nd);
            for(auto nd: nodes)
                delete nd;
        }
        bool isDetached(node_type * nd) {
            return contains(detached, nd);
        }
    protected:
        node_type * root;
        U data;
        std::string name;
        std::set<node_type *> detached;

    public:
        void setName(const std::string &n) {
            name.assign(n);
        }
        const std::string & getName() const {
            return name;
        }
        node_type * allocNewNode(node_type *p) {
            node_type * nd = new node_type(p);
            return nd;
        }
        void clear() {
            for(auto nd: getAllAttachedNodes())
                delete nd;

            root = NULL;
        }
        std::vector<const node_type *> getAllAttachedNodes() const {
            return getSubtreeNodes(root);
        }

        std::vector<const node_type *> getSubtreeNodes(node_type* p) const {
            std::vector<const node_type*> nodes;
            if (p) {
                nodes.push_back(p);
            }
            for(std::size_t i = 0; i < nodes.size(); i++) {
                for(auto n = nodes[i]->lChild; n; n = n->rSib) {
                    nodes.push_back(n);
                }
            }
            return nodes;
        }
        std::set<const node_type *> getSetOfAllAttachedNodes() const {
            std::set<const node_type*> nodes;
            for(auto nd: getAllAttachedNodes())
                nodes.insert(nd);
            return nodes;
        }
        void markAsDetached(node_type * nd) {
            detached.insert(nd);
        }
        void markAsAttached(node_type * nd) {
          detached.erase(nd);
        }
    private:
        RootedTree<T, U>(const RootedTree<T, U> &) = delete;
        RootedTree<T, U> & operator=(const RootedTree<T, U> &) = delete;
};

class RTNodeNoData{};
class RTreeNoData{};

template<typename Tree>
void addSubtree(typename Tree::node_type* par, Tree& T2)
{
    auto c = T2.getRoot();
    T2.pruneAndDangle(c);
    par->addChild(c);
}

template<typename Tree>
void replaceWithSubtree(typename Tree::node_type* n, Tree& T2)
{
    // Get the parent of the tip we are replacing
    auto p = n->getParent();
    // Remove the data from T2 and attach it to this parent
    auto c = T2.getRoot();
    T2.pruneAndDangle(c);
    p->addChild(c);
    // Remove the old child from under p
    p->removeChild(n);
    // Make the old child the root of T2, which will handle deleting it
    T2._setRoot(n);
}

} // namespace otc
#endif


text:
if (( ! $+commands[pacman] )); then
  return 1
fi

#
# Frontend
#

# Get the Pacman frontend.
zstyle -s ':prezto:module:pacman' frontend '_pacman_frontend'

if (( $+commands[$_pacman_frontend] )); then
  alias pacman="$_pacman_frontend"
else
  _pacman_frontend='pacman --color auto'
  _pacman_sudo='sudo '
fi

#
# Aliases
#

# Pacman.
alias pac="${_pacman_frontend}"

# Installs packages from repositories.
alias paci="${_pacman_sudo}${_pacman_frontend} --sync"

# Installs packages from files.
alias pacI="${_pacman_sudo}${_pacman_frontend} --upgrade"

# Removes packages and unneeded dependencies.
alias pacx="${_pacman_sudo}${_pacman_frontend} --remove"

# Removes packages, their configuration, and unneeded dependencies.
alias pacX="${_pacman_sudo}${_pacman_frontend} --remove --nosave --recursive"

# Displays information about a package from the repositories.
alias pacq="${_pacman_frontend} --sync --info"

# Displays information about a package from the local database.
alias pacQ="${_pacman_frontend} --query --info"

# Searches for packages in the repositories.
alias pacs="${_pacman_frontend} --sync --search"

# Searches for packages in the local database.
alias pacS="${_pacman_frontend} --query --search"

# Lists orphan packages.
alias pacman-list-orphans="${_pacman_sudo}${_pacman_frontend} --query --deps --unrequired"

# Removes orphan packages.
alias pacman-remove-orphans="${_pacman_sudo}${_pacman_frontend} --remove --recursive \$(${_pacman_frontend} --quiet --query --deps --unrequired)"

# Synchronizes the local package and Arch Build System databases against the
# repositories using the asp tool.
if (( $+commands[asp] )); then
  alias pacu="${_pacman_sudo}${_pacman_frontend} --sync --refresh && sudo asp update"
else
  alias pacu="${_pacman_sudo}${_pacman_frontend} --sync --refresh"
fi

# Synchronizes the local package database against the repositories then
# upgrades outdated packages.
alias pacU="${_pacman_sudo}${_pacman_frontend} --sync --refresh --sysupgrade"

function aurget {
  local target_dir="$1"
  if [[ -n "$2" ]]; then
    target_dir="$2"
  fi
  git clone "https://aur.archlinux.org/$1" "$target_dir"
}

unset _pacman_{frontend,sudo}


text:
class RenameBeaconsId < ActiveRecord::Migration
  def change
    remove_column :artworks, :beacons_id
    remove_column :locations, :beacons_id

    add_reference :artworks, :beacon, index: true
    add_reference :locations, :beacon, index: true
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    /// <summary>
    /// GA by keyword
    /// </summary>
    public class GAKeyword : GAAccount
    {
        /// <summary>
        /// Keyword
        /// </summary>
        public string Keyword { get; set; }
    }
}


text:
package com.sun.corba.se.PortableActivationIDL;

/**
* com/sun/corba/se/PortableActivationIDL/RepositoryHelper.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl
* Monday, December 12, 2016 4:37:46 PM PST
*/

abstract public class RepositoryHelper
{
  private static String  _id = "IDL:PortableActivationIDL/Repository:1.0";

  public static void insert (org.omg.CORBA.Any a, Repository that)
  {
    org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
    a.type (type ());
    write (out, that);
    a.read_value (out.create_input_stream (), type ());
  }

  public static Repository extract (org.omg.CORBA.Any a)
  {
    return read (a.create_input_stream ());
  }

  private static org.omg.CORBA.TypeCode __typeCode = null;
  synchronized public static org.omg.CORBA.TypeCode type ()
  {
    if (__typeCode == null)
    {
      __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (RepositoryHelper.id (), "Repository");
    }
    return __typeCode;
  }

  public static String id ()
  {
    return _id;
  }

  public static Repository read (org.omg.CORBA.portable.InputStream istream)
  {
    return narrow (istream.read_Object (_RepositoryStub.class));
  }

  public static void write (org.omg.CORBA.portable.OutputStream ostream, Repository value)
  {
    ostream.write_Object ((org.omg.CORBA.Object) value);
  }

  public static Repository narrow (org.omg.CORBA.Object obj)
  {
    if (obj == null)
      return null;
    else if (obj instanceof Repository)
      return (Repository)obj;
    else if (!obj._is_a (id ()))
      throw new org.omg.CORBA.BAD_PARAM ();
    else
    {
      org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();
      _RepositoryStub stub = new _RepositoryStub ();
      stub._set_delegate(delegate);
      return stub;
    }
  }

  public static Repository unchecked_narrow (org.omg.CORBA.Object obj)
  {
    if (obj == null)
      return null;
    else if (obj instanceof Repository)
      return (Repository)obj;
    else
    {
      org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();
      _RepositoryStub stub = new _RepositoryStub ();
      stub._set_delegate(delegate);
      return stub;
    }
  }

}


text:
require "appsignal"

module Appsignal
  module Integrations
    # @api private
    module PadrinoPlugin
      def self.init
        Appsignal.logger.debug("Loading Padrino (#{Padrino::VERSION}) integration")

        root = Padrino.mounted_root
        Appsignal.config = Appsignal::Config.new(root, Padrino.env)

        Appsignal.start_logger
        Appsignal.start
      end
    end
  end
end

module Appsignal::Integrations::PadrinoIntegration
  def route!(base = settings, pass_block = nil)
    return super if !Appsignal.active? || env["sinatra.static_file"]

    transaction = Appsignal::Transaction.create(
      SecureRandom.uuid,
      Appsignal::Transaction::HTTP_REQUEST,
      request
    )
    begin
      Appsignal.instrument("process_action.padrino") do
        super
      end
    rescue Exception => error # rubocop:disable Lint/RescueException
      transaction.set_error(error)
      raise error
    ensure
      transaction.set_action_if_nil(get_payload_action(request))
      transaction.set_metadata("path", request.path)
      transaction.set_metadata("method", request.request_method)
      transaction.set_http_or_background_queue_start
      Appsignal::Transaction.complete_current!
    end
  end

  private

  def get_payload_action(request)
    # Short-circut is there's no request object to obtain information from
    return settings.name.to_s unless request

    # Newer versions expose the action / controller on the request class.
    # Newer versions also still expose a route_obj so we must prioritize the
    # action/fullpath methods.
    # The `request.action` and `request.controller` values are `nil` when a
    # endpoint is not found, `""` if not specified by the user.
    controller_name = request.controller if request.respond_to?(:controller)
    action_name = request.action if request.respond_to?(:action)
    action_name ||= ""

    unless action_name.empty?
      return "#{settings.name}:#{controller_name}##{action_name}"
    end

    # Older versions of Padrino work with a route object
    if request.respond_to?(:route_obj) && request.route_obj
      return "#{settings.name}:#{request.route_obj.original_path}"
    end

    # Fall back to the application name if we haven't found an action name in
    # any previous methods.
    "#{settings.name}#unknown"
  end
end

Padrino::Application.send(:prepend, Appsignal::Integrations::PadrinoIntegration)

Padrino.after_load do
  Appsignal::Integrations::PadrinoPlugin.init
end


text:
<resources>

    <string name="app_name">Tutorial16 - Bindless Resources</string>

</resources>


text:
namespace {

// Gets the version number to use for variations seed simulation. Must be called
// on a thread where IO is allowed.
base::Version GetVersionForSimulation() {
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
  const base::Version installed_version =
      UpgradeDetectorImpl::GetCurrentlyInstalledVersion();
  if (installed_version.IsValid())
    return installed_version;
#endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)

  // TODO(asvitkine): Get the version that will be used on restart instead of
  // the current version on Android, iOS and ChromeOS.
  return base::Version(version_info::GetVersionNumber());
}

}  // namespace

ChromeVariationsServiceClient::ChromeVariationsServiceClient() {}

ChromeVariationsServiceClient::~ChromeVariationsServiceClient() {}

std::string ChromeVariationsServiceClient::GetApplicationLocale() {
  return g_browser_process->GetApplicationLocale();
}

base::SequencedWorkerPool* ChromeVariationsServiceClient::GetBlockingPool() {
  return content::BrowserThread::GetBlockingPool();
}

base::Callback<base::Version(void)>
ChromeVariationsServiceClient::GetVersionForSimulationCallback() {
  return base::Bind(&GetVersionForSimulation);
}

net::URLRequestContextGetter*
ChromeVariationsServiceClient::GetURLRequestContext() {
  return g_browser_process->system_request_context();
}

network_time::NetworkTimeTracker*
ChromeVariationsServiceClient::GetNetworkTimeTracker() {
  return g_browser_process->network_time_tracker();
}

version_info::Channel ChromeVariationsServiceClient::GetChannel() {
  return chrome::GetChannel();
}

bool ChromeVariationsServiceClient::OverridesRestrictParameter(
    std::string* parameter) {
#if defined(OS_CHROMEOS)
  chromeos::CrosSettings::Get()->GetString(
      chromeos::kVariationsRestrictParameter, parameter);
  return true;
#else
  return false;
#endif
}

void ChromeVariationsServiceClient::OnInitialStartup() {
#if defined(OS_WIN)
  StartGoogleUpdateRegistrySync();
#endif
}

#if defined(OS_WIN)
void ChromeVariationsServiceClient::StartGoogleUpdateRegistrySync() {
  registry_syncer_.RequestRegistrySync();
}
#endif


text:
package com.alibaba.nacos.config.server.remote;

import com.alibaba.nacos.common.utils.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * config change listen context.
 *
 * @author liuzunfei
 * @version $Id: ConfigChangeListenContext.java, v 0.1 2020年07月20日 1:37 PM liuzunfei Exp $
 */
@Component
public class ConfigChangeListenContext {

    /**
     * groupKey-> connection set.
     */
    private ConcurrentHashMap<String, HashSet<String>> groupKeyContext = new ConcurrentHashMap<>();

    /**
     * connectionId-> group key set.
     */
    private ConcurrentHashMap<String, HashMap<String, String>> connectionIdContext = new ConcurrentHashMap<>();

    /**
     * add listen.
     *
     * @param groupKey     groupKey.
     * @param connectionId connectionId.
     */
    public synchronized void addListen(String groupKey, String md5, String connectionId) {
        // 1.add groupKeyContext
        Set<String> listenClients = groupKeyContext.get(groupKey);
        if (listenClients == null) {
            groupKeyContext.putIfAbsent(groupKey, new HashSet<>());
            listenClients = groupKeyContext.get(groupKey);
        }
        listenClients.add(connectionId);

        // 2.add connectionIdContext
        HashMap<String, String> groupKeys = connectionIdContext.get(connectionId);
        if (groupKeys == null) {
            connectionIdContext.putIfAbsent(connectionId, new HashMap<>(16));
            groupKeys = connectionIdContext.get(connectionId);
        }
        groupKeys.put(groupKey, md5);

    }

    /**
     * remove listen context for connection id .
     *
     * @param groupKey     groupKey.
     * @param connectionId connection id.
     */
    public synchronized void removeListen(String groupKey, String connectionId) {

        //1. remove groupKeyContext
        Set<String> connectionIds = groupKeyContext.get(groupKey);
        if (connectionIds != null) {
            connectionIds.remove(connectionId);
            if (connectionIds.isEmpty()) {
                groupKeyContext.remove(groupKey);
            }
        }

        //2.remove connectionIdContext
        HashMap<String, String> groupKeys = connectionIdContext.get(connectionId);
        if (groupKeys != null) {
            groupKeys.remove(groupKey);
        }
    }

    /**
     * get listeners of the group key.
     *
     * @param groupKey groupKey.
     * @return the copy of listeners, may be return null.
     */
    public synchronized Set<String> getListeners(String groupKey) {

        HashSet<String> strings = groupKeyContext.get(groupKey);
        if (CollectionUtils.isNotEmpty(strings)) {
            Set<String> listenConnections = new HashSet<>();
            safeCopy(strings, listenConnections);
            return listenConnections;
        }
        return null;
    }

    /**
     * copy collections.
     *
     * @param src  may be modified concurrently
     * @param dest dest collection
     */
    private void safeCopy(Collection src, Collection dest) {
        Iterator iterator = src.iterator();
        while (iterator.hasNext()) {
            dest.add(iterator.next());
        }
    }

    /**
     * remove the context related to the connection id.
     *
     * @param connectionId connectionId.
     */
    public synchronized void clearContextForConnectionId(final String connectionId) {

        Map<String, String> listenKeys = getListenKeys(connectionId);

        if (listenKeys == null) {
            connectionIdContext.remove(connectionId);
            return;
        }
        for (Map.Entry<String, String> groupKey : listenKeys.entrySet()) {

            Set<String> connectionIds = groupKeyContext.get(groupKey.getKey());
            if (CollectionUtils.isNotEmpty(connectionIds)) {
                connectionIds.remove(connectionId);
            } else {
                groupKeyContext.remove(groupKey.getKey());
            }

        }
        connectionIdContext.remove(connectionId);
    }

    /**
     * get listen keys.
     *
     * @param connectionId connection id.
     * @return listen group keys of the connection id, key:group key,value:md5
     */
    public synchronized Map<String, String> getListenKeys(String connectionId) {
        HashMap<String, String> stringStringHashMap = connectionIdContext.get(connectionId);
        return stringStringHashMap == null ? null : new HashMap<>(stringStringHashMap);
    }

    /**
     * get md5.
     *
     * @param connectionId connection id.
     * @return md5 of the listen group key.
     */
    public String getListenKeyMd5(String connectionId, String groupKey) {
        Map<String, String> groupKeyContexts = connectionIdContext.get(connectionId);
        return groupKeyContexts == null ? null : groupKeyContexts.get(groupKey);
    }

    /**
     * get connection count.
     *
     * @return count of long connections.
     */
    public int getConnectionCount() {
        return connectionIdContext.size();
    }

}


text:
package bt.net;

import bt.metainfo.TorrentId;
import com.google.common.base.MoreObjects;

import java.util.Objects;

public class ConnectionKey {
    private final Peer peer;
    private final int remotePort;
    private final TorrentId torrentId;

    public ConnectionKey(Peer peer, int remotePort, TorrentId torrentId) {
        Objects.requireNonNull(peer);
        Objects.requireNonNull(torrentId);
        this.peer = peer;
        this.remotePort = remotePort;
        this.torrentId = torrentId;
    }

    public Peer getPeer() {
        return peer;
    }

    public int getRemotePort() {
        return remotePort;
    }

    public TorrentId getTorrentId() {
        return torrentId;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        ConnectionKey that = (ConnectionKey) obj;
        // must not use peer's port, because it can be updated
        return peer.getInetAddress().equals(that.peer.getInetAddress())
                && remotePort == that.remotePort
                && torrentId.equals(that.torrentId);

    }

    @Override
    public int hashCode() {
        int result = peer.getInetAddress().hashCode();
        result = 31 * result + remotePort;
        result = 31 * result + torrentId.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("peer", peer)
                .add("remotePort", remotePort)
                .add("torrentId", torrentId)
                .toString();
    }
}


text:
using System;
using System.Net;

namespace CS_threescale_Test
{
    /// <summary>
    /// A custom implementation of IWebRequestCreate for Web Requests.
    /// </summary>
    /// <summary>A web request creator for unit testing.</summary>
    public class MockWebRequestCreate : IWebRequestCreate
    {
        /// <summary>
        /// The web request.
        /// </summary>
        private static WebRequest nextRequest;

        /// <summary>
        /// Internally held lock object for multi-threading support.
        /// </summary>
        private static object lockObject = new object();

        /// <summary>
        /// Gets or sets the next request object.
        /// </summary>
        public static WebRequest NextRequest
        {
            get
            {
                return nextRequest;
            }

            set
            {
                lock (lockObject)
                {
                    nextRequest = value;
                }
            }
        }

        /// <summary>
        /// Creates the new instance of the CustomWebRequest.
        /// </summary>
        /// <param name="uri">The given Uri</param>
        /// <returns>An instantiated web request object requesting from the given Uri.</returns>
        public WebRequest Create(Uri uri)
        {
            return nextRequest;
        }

        /// <summary>
        /// Creates a Mock Web request
        /// </summary>
        /// <returns>The mocked HttpRequest object</returns>
        public static MockWebRequest CreateMockWebRequest()
        {
            var request = new MockWebRequest();
            NextRequest = request;
            return request;
        }
    }
}


text:
package at.ac.tuwien.kr.alpha.core.depgraph;

import at.ac.tuwien.kr.alpha.api.programs.analysis.ComponentGraph;
import at.ac.tuwien.kr.alpha.api.programs.analysis.DependencyGraph;
import org.apache.commons.lang3.StringUtils;

import at.ac.tuwien.kr.alpha.core.programs.InternalProgram;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Representation of an {@link InternalProgram}'s component graph, i.e. the directed acyclic graph resulting from condensing the program's
 * {@link DependencyGraphImpl} into its strongly connected components. Needed in order to calculate stratifications from which an evaluation order for the
 * {@link at.ac.tuwien.kr.alpha.core.programs.transformation.StratifiedEvaluation} transformation can be derived.
 *
 * Copyright (c) 2019-2020, the Alpha Team.
 */
public final class ComponentGraphImpl implements ComponentGraph {

	private final ArrayList<SCComponent> components;
	private final List<SCComponent> entryPoints;

	private ComponentGraphImpl(ArrayList<SCComponent> components, List<SCComponent> entryPoints) {
		this.components = components;
		this.entryPoints = entryPoints;
	}

	/**
	 * Creates a new {@link ComponentGraphImpl} based on a dependency graph and an {@link StronglyConnectedComponentsAlgorithm.SccResult} representing the
	 * result of calculating the dependency graph's strongly connected components (SCCs).
	 *
	 * @param dg        the dependency graph backing this component graph.
	 * @param sccResult the SCC calculation result for the dependency graph in question.
	 * @return a new {@link ComponentGraphImpl} representing the strongly connected components of the given dependency graph.
	 */
	public static ComponentGraphImpl buildComponentGraph(DependencyGraph dg, StronglyConnectedComponentsAlgorithm.SccResult sccResult) {
		return new ComponentGraphImpl.Builder(dg, sccResult).build();
	}

	@Override
	public List<SCComponent> getComponents() {
		return Collections.unmodifiableList(components);
	}

	@Override
	public List<SCComponent> getEntryPoints() {
		return Collections.unmodifiableList(entryPoints);
	}

	public static class SCComponentImpl implements ComponentGraph.SCComponent {

		private final int                        id;
		private final List<DependencyGraph.Node> nodes;
		private final Map<Integer, Boolean>      dependencyIds;
		private final Set<Integer>               dependentIds;
		private final boolean                    hasNegativeCycle;

		private SCComponentImpl(int id, List<DependencyGraph.Node> nodes, Map<Integer, Boolean> dependencyIds, Set<Integer> dependentIds, boolean hasNegativeCycle) {
			this.id = id;
			this.nodes = nodes;
			this.dependencyIds = dependencyIds;
			this.dependentIds = dependentIds;
			this.hasNegativeCycle = hasNegativeCycle;
		}

		@Override
		public Map<Integer, Boolean> getDependencyIds() {
			return Collections.unmodifiableMap(dependencyIds);
		}

		@Override
		public Set<Integer> getDependentIds() {
			return Collections.unmodifiableSet(dependentIds);
		}

		@Override
		public String toString() {
			return "SCComponent{" + StringUtils.join(nodes, ",") + "}";
		}

		@Override
		public boolean hasNegativeCycle() {
			return hasNegativeCycle;
		}

		@Override
		public List<DependencyGraph.Node> getNodes() {
			return nodes;
		}

		@Override
		public int getId() {
			return id;
		}

		private static class Builder {

			private int                        id;
			private List<DependencyGraph.Node> nodes;
			private Map<Integer, Boolean>      dependencyIds = new HashMap<>();
			private Set<Integer>               dependentIds = new HashSet<>();
			private boolean                    hasNegativeCycle;

			private Builder(int id, List<DependencyGraph.Node> nodes) {
				this.nodes = nodes;
				this.id = id;
			}

			private SCComponentImpl build() {
				return new SCComponentImpl(id, nodes, dependencyIds, dependentIds, hasNegativeCycle);
			}

		}

	}

	private static class Builder {

		private DependencyGraph                    depGraph;
		private List<List<DependencyGraph.Node>>   componentMap;
		private Map<DependencyGraph.Node, Integer> nodesByComponentId;
		private ArrayList<SCComponentImpl.Builder>     componentBuilders = new ArrayList<>();
		private ArrayList<SCComponent>             components = new ArrayList<>();

		private Builder(DependencyGraph dg, StronglyConnectedComponentsAlgorithm.SccResult sccResult) {
			this.depGraph = dg;
			this.componentMap = sccResult.stronglyConnectedComponents;
			this.nodesByComponentId = sccResult.nodesByComponentId;
		}

		private ComponentGraphImpl build() {
			// Create a ComponentBuilder for each component.
			for (int i = 0; i < componentMap.size(); i++) {
				componentBuilders.add(new SCComponentImpl.Builder(i, componentMap.get(i)));
			}
			// Iterate and register each edge of every component.
			for (int i = 0; i < componentBuilders.size(); i++) {
				SCComponentImpl.Builder builder = componentBuilders.get(i);
				for (DependencyGraph.Node node : builder.nodes) {
					for (DependencyGraph.Edge edge : depGraph.getAdjancencyMap().get(node)) {
						registerEdge(i, edge);
					}
				}
			}
			// Build each component and identify starting components.
			List<SCComponent> startingPoints = new ArrayList<>();
			for (SCComponentImpl.Builder builder : componentBuilders) {
				SCComponent tmpComponent = builder.build();
				components.add(tmpComponent);
				// Component is starting if it has no dependencies.
				if (tmpComponent.getDependencyIds().isEmpty()) {
					startingPoints.add(tmpComponent);
				}
			}
			return new ComponentGraphImpl(components, startingPoints);
		}

		private void registerEdge(int srcComponentId, DependencyGraph.Edge edge) {
			int destComponentId = nodesByComponentId.get(edge.getTarget());
			if (srcComponentId == destComponentId) {
				// Record negative self-loop.
				if (!edge.getSign()) {
					componentBuilders.get(srcComponentId).hasNegativeCycle = true;
				}
			} else {
				SCComponentImpl.Builder srcComponentBld = componentBuilders.get(srcComponentId);
				srcComponentBld.dependentIds.add(destComponentId);
				SCComponentImpl.Builder destComponentBld = componentBuilders.get(destComponentId);
				boolean isPositiveDep = true;
				if (destComponentBld.dependencyIds.containsKey(srcComponentId)) {
					isPositiveDep = destComponentBld.dependencyIds.get(srcComponentId);
				}
				// If the dependency to srcComponent already is negative, it stays that way, otherwise it is determined by the edge's sign.
				destComponentBld.dependencyIds.put(srcComponentId, isPositiveDep & edge.getSign());
			}
		}

	}

}