text:
<?php

?>
<?php
class upgradeModel extends model
{
    /**
     * Errors.
     *
     * @static
     * @var array
     * @access public
     */
    static $errors = array();

    /**
     * The execute method. According to the $fromVersion call related methods.
     *
     * @param  string $fromVersion
     * @access public
     * @return void
     */
    public function execute($fromVersion)
    {
        switch($fromVersion)
        {
            case '1_0_beta':
                $this->execSQL($this->getUpgradeFile('1.0.beta'));
                $this->createCashEntry();
            case '1_1_beta':
                $this->execSQL($this->getUpgradeFile('1.1.beta'));
                $this->createTeamEntry();
            case '1_2_beta':
                $this->execSQL($this->getUpgradeFile('1.2.beta'));
                $this->transformBlock();
                $this->changeBuildinName();
                $this->computeContactInfo();
            case '1_3_beta':
                $this->execSQL($this->getUpgradeFile('1.3.beta'));
                $this->setCompanyContent();
            case '1_4_beta':
                $this->upgradeContractName();
                $this->upgradeProjectMember();
                $this->safeDropColumns(TABLE_PROJECT, 'master,member');

                /* Exec sqls must after fix data. */
                $this->execSQL($this->getUpgradeFile('1.4.beta'));
            case '1_5_beta':
                $this->execSQL($this->getUpgradeFile('1.5.beta'));
                $this->upgradeEntryLogo();
                $this->upgradeReturnRecords();
                $this->upgradeDeliveryRecords();
                $this->addSearchPriv();
            case '1_6':
                $this->execSQL($this->getUpgradeFile('1.6'));
                $this->addPrivs();
            case '1_7':
                $this->toLowerTable();
                $this->updateAppOrder();
            case '2_0':
                $this->execSQL($this->getUpgradeFile('2.0'));
                $this->fixClosedTask();
                $this->setSalesGroup();
                $this->fixOrderProduct();
            case '2_1':
                $this->execSQL($this->getUpgradeFile('2.1'));
            case '2_2':
                $this->processTradeDesc();
            case '2_3':
                $this->processCustomerEditedDate();
                $this->execSQL($this->getUpgradeFile('2.3'));
            case '2_4':
                $this->addAttendPriv();
                $this->execSQL($this->getUpgradeFile('2.4'));
            case '2_5':
                $this->execSQL($this->getUpgradeFile('2.5'));
            case '2_6':
                $this->execSQL($this->getUpgradeFile('2.6'));
            case '2_7':
                $this->processBlockType();
                $this->execSQL($this->getUpgradeFile('2.7'));
            case '3_0':
                $this->execSQL($this->getUpgradeFile('3.0'));

            default: if(!$this->isError()) $this->loadModel('setting')->updateVersion($this->config->version);
        }

        $this->deletePatch();
    }

    /**
     * Create the confirm contents.
     *
     * @param  string $fromVersion
     * @access public
     * @return string
     */
    public function getConfirm($fromVersion)
    {
        $confirmContent = '';
        switch($fromVersion)
        {
            case '1_0_beta': $confirmContent .= file_get_contents($this->getUpgradeFile('1.0.beta'));
            case '1_1_beta': $confirmContent .= file_get_contents($this->getUpgradeFile('1.1.beta'));
            case '1_2_beta': $confirmContent .= file_get_contents($this->getUpgradeFile('1.2.beta'));
            case '1_3_beta': $confirmContent .= file_get_contents($this->getUpgradeFile('1.3.beta'));
            case '1_4_beta': $confirmContent .= file_get_contents($this->getUpgradeFile('1.4.beta'));
            case '1_5_beta': $confirmContent .= file_get_contents($this->getUpgradeFile('1.5.beta'));
            case '1_6'     : $confirmContent .= file_get_contents($this->getUpgradeFile('1.6'));
            case '2_0'     : $confirmContent .= file_get_contents($this->getUpgradeFile('2.0'));
            case '2_1'     : $confirmContent .= file_get_contents($this->getUpgradeFile('2.1'));
            case '2_3'     : $confirmContent .= file_get_contents($this->getUpgradeFile('2.3'));
            case '2_4'     : $confirmContent .= file_get_contents($this->getUpgradeFile('2.4'));
            case '2_5'     : $confirmContent .= file_get_contents($this->getUpgradeFile('2.5'));
            case '2_6'     : $confirmContent .= file_get_contents($this->getUpgradeFile('2.6'));
            case '2_7'     : $confirmContent .= file_get_contents($this->getUpgradeFile('2.7'));
            case '3_0'     : $confirmContent .= file_get_contents($this->getUpgradeFile('3.0'));
        }
        return $confirmContent;
    }

    /**
     * Delete the patch record.
     *
     * @access public
     * @return void
     */
    public function deletePatch()
    {
        return true;
        $this->dao->delete()->from(TABLE_EXTENSION)->where('type')->eq('patch')->exec();
    }

    /**
     * Get the upgrade sql file.
     *
     * @param  string $version
     * @access public
     * @return string
     */
    public function getUpgradeFile($version)
    {
        return $this->app->getBasepath() . 'db' . DS . 'upgrade' . $version . '.sql';
    }

    /**
     * Execute a sql.
     *
     * @param  string  $sqlFile
     * @access public
     * @return void
     */
    public function execSQL($sqlFile)
    {
        $mysqlVersion = $this->loadModel('install')->getMysqlVersion();

        /* Read the sql file to lines, remove the comment lines, then join theme by ';'. */
        $sqls = explode("\n", file_get_contents($sqlFile));
        foreach($sqls as $key => $line)
        {
            $line       = trim($line);
            $sqls[$key] = $line;
            if(strpos($line, '--') !== false or empty($line)) unset($sqls[$key]);
        }
        $sqls = explode(';', join("\n", $sqls));

        foreach($sqls as $sql)
        {
            $sql = trim($sql);
            if(empty($sql)) continue;

            if($mysqlVersion <= 4.1)
            {
                $sql = str_replace('DEFAULT CHARSET=utf8', '', $sql);
                $sql = str_replace('CHARACTER SET utf8 COLLATE utf8_general_ci', '', $sql);
            }

            try
            {
                $this->dbh->exec($sql);
            }
            catch (PDOException $e)
            {
                self::$errors[] = $e->getMessage() . "
The sql is: $sql
";
            }
        }
    }

    /**
     * Judge any error occers.
     *
     * @access public
     * @return bool
     */
    public function isError()
    {
        return !empty(self::$errors);
    }

    /**
     * Get errors during the upgrading.
     *
     * @access public
     * @return array
     */
    public function getError()
    {
        $errors = self::$errors;
        self::$errors = array();
        return $errors;
    }

    /**
     * create cash entry.
     *
     * @access public
     * @return void
     */
    public function createCashEntry()
    {
        $entry = new stdclass();

        $entry->name     = 'cash';
        $entry->code     = 'cash';
        $entry->open     = 'iframe';
        $entry->order    = 2;
        $entry->ip       = '*';
        $entry->key      = '438d85f2c2b04372662c63ebfb1c4c2f';
        $entry->logo     = $this->config->webRoot . 'theme/default/images/ips/app-cash.png';
        $entry->login    = '../cash';
        $entry->ip       = '*';
        $entry->control  = 'simple';
        $entry->visible  = 1;
        $entry->size     = 'max';
        $entry->position = 'default';

        $block = REQUESTTYPE == 'GET' ? 'cash/index.php?m=block&f=index' : 'cash/block-index.html';
        $entry->block = $this->config->webRoot . $block;

        $this->dao->insert(TABLE_ENTRY)->data($entry)->exec();
    }

    /**
     * create team entry.
     *
     * @access public
     * @return void
     */
    public function createTeamEntry()
    {
        $entry = new stdclass();

        $entry->name     = 'team';
        $entry->code     = 'team';
        $entry->open     = 'iframe';
        $entry->order    = 4;
        $entry->ip       = '*';
        $entry->key      = '6c46d9fe76a1afa1cd61f946f1072d1e';
        $entry->logo     = $this->config->webRoot . 'theme/default/images/ips/app-team.png';
        $entry->login    = '../team';
        $entry->ip       = '*';
        $entry->control  = 'simple';
        $entry->size     = 'max';
        $entry->position = 'default';

        $block = REQUESTTYPE == 'GET' ? 'team/index.php?m=block&f=index' : 'team/block-index.html';
        $entry->block = $this->config->webRoot . $block;

        $this->dao->insert(TABLE_ENTRY)->data($entry)->exec();
    }

    /**
     * Transform block from config to block table.
     *
     * @access public
     * @return bool
     */
    public function transformBlock()
    {
        $blocks  = $this->dao->select('*')->from(TABLE_CONFIG)->where('section')->eq('block')->andWhere('module')->eq('index')->fetchAll('id');
        $entries = $this->dao->select('id,code')->from(TABLE_ENTRY)->fetchPairs('id', 'code');

        foreach($blocks as $block)
        {
            if(empty($block->owner)) continue;
            $block->value = json_decode($block->value);

            $source  = '';
            $blockID = $block->value->type;
            if($block->value->type == 'system')
            {
                if($block->app == 'sys' and isset($block->value->entryID) and !isset($entries[$block->value->entryID])) continue;
                $source  = $block->app == 'sys' ? $entries[$block->value->entryID] : $block->app;
                $blockID = $block->value->blockID;
            }

            if($blockID == 'html') $block->value->params = helper::jsonEncode(array('html' => $block->value->html));
            if(!isset($block->value->params)) $block->value->params = array();

            $data = new stdclass();
            $data->account = $block->owner;
            $data->app     = $block->app;
            $data->title   = $block->value->name;
            $data->source  = $source;
            $data->block   = $blockID;
            $data->params  = helper::jsonEncode($block->value->params);
            $data->order   = str_replace('b', '', $block->key);
            $data->grid    = 3;

            $this->dao->replace(TABLE_BLOCK)->data($data)->exec();
        }
        if(dao::isError()) return false;

        $this->dao->delete()->from(TABLE_CONFIG)->where('section')->eq('block')->andWhere('module')->eq('index')->exec();
        return true;
    }

    /**
     * Change buildin entry name.
     *
     * @access public
     * @return bool
     */
    public function changeBuildinName()
    {
        $this->app->loadLang('install', 'sys');

        foreach($this->lang->install->buildinEntry as $code => $name)
        {
            $this->dao->update(TABLE_ENTRY)
                ->set('name')->eq($name['name'])
                ->set('abbr')->eq($name['abbr'])
                ->set('buildin')->eq(1)
                ->set('integration')->eq(1)
                ->set('visible')->eq(1)
                ->where('code')->eq($code)
                ->exec();
        }

        if(dao::isError()) return false;
        return true;
    }

    /**
     * Compute contacteddate and contactedby fields.
     *
     * @access public
     * @return void
     */
    public function computeContactInfo()
    {
        $orders    = $this->dao->select('id')->from(TABLE_ORDER)->fetchAll();
        $customers = $this->dao->select('id')->from(TABLE_CUSTOMER)->fetchAll();
        $contracts = $this->dao->select('id')->from(TABLE_CONTRACT)->fetchAll();
        $contacts  = $this->dao->select('id')->from(TABLE_CONTACT)->fetchAll();

        foreach($orders as $order)
        {
            $lastContact = $this->dao->select('actor as contactedBy, date as contactedDate')->from(TABLE_ACTION)
                ->where('action')->eq('record')
                ->andWhere('objectType')->eq('order')
                ->andWhere('objectID')->eq($order->id)
                ->orderBY('date_desc')
                ->limit(1)
                ->fetch();
            if($lastContact) $this->dao->update(TABLE_ORDER)->data($lastContact)->where('id')->eq($order->id)->exec();
        }

        foreach($customers as $customer)
        {
            $lastContact = $this->dao->select('actor as contactedBy, date as contactedDate')->from(TABLE_ACTION)
                ->where('action')->eq('record')
                ->andWhere('customer')->eq($customer->id)
                ->orderBY('date_desc')
                ->limit(1)
                ->fetch();
            if($lastContact) $this->dao->update(TABLE_CUSTOMER)->data($lastContact)->where('id')->eq($customer->id)->exec();
        }

        foreach($contacts as $contact)
        {
            $lastContact = $this->dao->select('actor as contactedBy, date as contactedDate')->from(TABLE_ACTION)
                ->where('action')->eq('record')
                ->andWhere('contact')->eq($contact->id)
                ->orderBY('date_desc')
                ->limit(1)
                ->fetch();
            if($lastContact) $this->dao->update(TABLE_CONTACT)->data($lastContact)->where('id')->eq($contact->id)->exec();
        }

        foreach($contracts as $contract)
        {
            $lastContact = $this->dao->select('actor as contactedBy, date as contactedDate')->from(TABLE_ACTION)
                ->where('action')->eq('record')
                ->andWhere('objectType')->eq('contract')
                ->andWhere('objectID')->eq($contract->id)
                ->orderBY('date_desc')
                ->limit(1)
                ->fetch();
            if($lastContact) $this->dao->update(TABLE_CONTRACT)->data($lastContact)->where('id')->eq($contract->id)->exec();
        }

        return !dao::isError();

    }

    /**
     * Set content of company when upgrade from 1.3.beta.
     *
     * @access public
     * @return void
     */
    public function setCompanyContent()
    {
        if(empty($this->config->company->content) and $this->config->company->desc)
        {
            $this->dao->update(TABLE_CONFIG)->set('value')->eq($this->config->company->desc)->where('`key`')->eq('content')->andWhere('section')->eq('company')->exec();
            $this->dao->delete()->from(TABLE_CONFIG)->where('`key`')->eq('desc')->andWhere('section')->eq('company')->exec();
        }
        return !dao::isError();
    }

    /**
     * Set name of contract when upgrade from 1.4.beta.
     *
     * @access public
     * @return void
     */
    public function upgradeContractName()
    {
        $contracts = $this->dao->select('*')->from(TABLE_CONTRACT)->fetchAll();

        foreach($contracts as $contract)
        {
            $name = preg_replace('/^\[(\d+)\]/', '', $contract->name);
            $this->dao->update(TABLE_CONTRACT)->set('name')->eq($name)->where('id')->eq($contract->id)->exec();
        }

        return !dao::isError();
    }

    /**
     * Update project member.
     *
     * @access public
     * @return void
     */
    public function upgradeProjectMember()
    {
        $projects = $this->loadModel('project', 'oa')->getList();
        foreach($projects as $project)
        {
            $member = new stdclass();
            $member->type = 'project';
            $member->id   = $project->id;

            /* Move master to team table. */
            if(!empty($project->master))
            {
                $member->account = $project->master;
                $member->role    = 'role';
                $this->dao->replace(TABLE_TEAM)->data($member)->exec();
            }

            /* Move members to team table. */
            if(!empty($project->member))
            {
                $members = explode(',', $project->member);
                $member->role = 'member';
                foreach($members as $account)
                {
                    if($account == $project->master) continue;
                    if(!validater::checkAccount($account)) continue;

                    $member->account = $account;
                    $this->dao->replace(TABLE_TEAM)->data($member)->exec();
                }
            }

            return true;
        }
    }

    /**
     * Change system application logo path to relative path.
     *
     * @access public
     * @return void
     */
    public function upgradeEntryLogo()
    {
        $entryList = array('crm', 'cash', 'oa', 'team');
        foreach($entryList as $entry)
        {
            $entryObj = $this->dao->select('*')->from(TABLE_ENTRY)->where('code')->eq($entry)->fetch();
            $path     = substr($entryObj->logo, strpos($entryObj->logo, 'theme'));
            $this->dao->update(TABLE_ENTRY)->set('logo')->eq($path)->where('code')->eq($entry)->exec();
        }
    }

    /**
     * Update return records.
     *
     * @access public
     * @return bool
     */
    public function upgradeReturnRecords()
    {
        $contracts = $this->dao->select('*')->from(TABLE_CONTRACT)->where('`return`')->eq('done')->fetchAll();
        if(empty($contracts)) return false;

        foreach($contracts as $contract)
        {
            $data = new stdclass();
            $data->contract     = $contract->id;
            $data->amount       = $contract->amount;
            $data->returnedBy   = $contract->returnedBy;
            $data->returnedDate = $contract->returnedDate;

            $this->dao->insert(TABLE_PLAN)->data($data)->autoCheck()->exec();
        }

        return !dao::isError();
    }

    /**
     * Update delivery records.
     *
     * @access public
     * @return bool
     */
    public function upgradeDeliveryRecords()
    {
        $contracts = $this->dao->select('*')->from(TABLE_CONTRACT)->where('`delivery`')->eq('done')->fetchAll();
        if(empty($contracts)) return false;

        foreach($contracts as $contract)
        {
            $data = new stdclass();
            $data->contract      = $contract->id;
            $data->deliveredBy   = $contract->deliveredBy;
            $data->deliveredDate = $contract->deliveredDate;

            $this->dao->insert(TABLE_DELIVERY)->data($data)->autoCheck()->exec();
        }

        return !dao::isError();
    }

    /**
     * Add search priv when upgrade 1.5.beta.
     *
     * @access public
     * @return void
     */
    public function addSearchPriv()
    {
        $groups = $this->dao->select('id')->from(TABLE_GROUP)->fetchAll('id');
        foreach($groups as $group)
        {
            $priv = new stdclass();
            $priv->group  = $group->id;
            $priv->module = 'search';
            $priv->method = 'buildForm';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();

            $priv->method = 'buildQuery';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();

            $priv->method = 'saveQuery';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();

            $priv->method = 'deleteQuery';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();
        }

        return !dao::isError();
    }

    /**
     * Safe drop columns.
     *
     * @param string $table
     * @param string $columns
     * @access public
     * @return bool
     */
    public function safeDropColumns($table, $columns)
    {
        if($columns == '') return false;

        $fieldsOBJ = $this->dao->query('desc ' . TABLE_PROJECT);
        while($field = $fieldsOBJ->fetch())
        {
            $fields[$field->Field] = $field->Field;
        }

        $columns = explode(',', $columns);
        foreach($columns as $column)
        {
            if($column == '') continue;
            if(isset($fields[$column]))
            {
                $this->dao->query("ALTER TABLE $table DROP $column;");
            }
        }

        return true;
    }

    /**
     * Add app priv when upgrade from 1.6.
     *
     * @access public
     * @return void
     */
    public function addPrivs()
    {
        $groups = $this->dao->select('id')->from(TABLE_GROUP)->fetchAll('id');

        foreach($groups as $group)
        {
            if($group->id == 1)
            {
                $privs = array('balance', 'depositor', 'order', 'product', 'project', 'schema', 'setting', 'task', 'trade');

                $modules['balance']   = array('browse', 'create', 'delete', 'edit');
                $modules['depositor'] = array('activate', 'browse', 'check', 'create', 'delete', 'edit', 'forbid', 'savebalance');
                $modules['order']     = array('delete');
                $modules['product']   = array('view');
                $modules['project']   = array('activate', 'suspend');
                $modules['schema']    = array('browse', 'create', 'delete', 'edit', 'view');
                $modules['setting']   = array('lang', 'reset');
                $modules['task']      = array('kanban', 'outline', 'start');
                $modules['trade']     = array('batchCreate', 'batchEdit', 'browse', 'create', 'delete', 'detail', 'edit', 'import', 'showimport', 'transfer');

                foreach($privs as $module)
                {
                    $priv = new stdclass();
                    $priv->group  = 1;
                    $priv->module = $module;

                    foreach($modules[$module] as $method)
                    {
                        $priv->method = $method;
                        $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();
                    }
                }
            }

            if($group->id == 2)
            {
                $priv = new stdclass();
                $priv->group  = 2;
                $priv->module = 'depositor';
                $priv->method = 'delete';
                $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();

                $priv->method = 'savabalance';
                $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();
            }

            if($group->id == 3)
            {
                $priv = new stdclass();
                $priv->group  = 3;
                $priv->module = 'project';

                $methods = array('activate', 'finish', 'index', 'suspend');
                foreach($methods as $method)
                {
                    $priv->method = $method;
                    $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();
                }
            }

            $priv = new stdclass();
            $priv->group  = $group->id;
            $priv->module = 'apppriv';
            $priv->method = 'crm';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();

            $priv->method = 'cash';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();

            $priv->method = 'oa';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();

            $priv->method = 'team';
            $this->dao->replace('`sys_groupPriv`')->data($priv)->exec();
        }

        return !dao::isError();
    }

    /**
     * To lower table.
     *
     * @access public
     * @return bool
     */
    public function toLowerTable()
    {
        $results    = $this->dbh->query("show Variables like '%table_names'")->fetchAll();
        $hasLowered = false;
        foreach($results as $result)
        {
            if(strtolower($result->Variable_name) == 'lower_case_table_names' and $result->Value == 1)
            {
                $hasLowered = true;
                break;
            }
        }
        if($hasLowered) return true;

        $tables2Rename = $this->config->upgrade->lowerTables;
        if(!isset($tables2Rename)) return false;

        $tablesExists = $this->dbh->query('SHOW TABLES')->fetchAll();
        foreach($tablesExists as $key => $table) $tablesExists[$key] = current((array)$table);
        $tablesExists = array_flip($tablesExists);

        foreach($tables2Rename as $oldTable => $newTable)
        {
            if(!isset($tablesExists[$oldTable])) continue;

            $upgradebak = $newTable . '_othertablebak';
            if(isset($tablesExists[$upgradebak])) $this->dbh->query("DROP TABLE `$upgradebak`");
            if(isset($tablesExists[$newTable])) $this->dbh->query("RENAME TABLE `$newTable` TO `$upgradebak`");

            $tempTable = $oldTable . '_ranzhitmp';
            $this->dbh->query("RENAME TABLE `$oldTable` TO `$tempTable`");
            $this->dbh->query("RENAME TABLE `$tempTable` TO `$newTable`");
        }

        return true;
    }

    /**
     * Update app orders.
     *
     * @access public
     * @return void
     */
    public function updateAppOrder()
    {
        $entries = $this->loadModel('entry')->getEntries('system');
        $order   = 10;
        foreach($entries as $entry)
        {
            $this->dao->update(TABLE_ENTRY)->set('`order`')->eq($order)->where('id')->eq($entry->id)->exec();
            $order += 10;
        }
        return !dao::isError();
    }

    /**
     * Set assignedTo is closed if the task is closed when upgrade from 2.0.
     *
     * @access public
     * @return int
     */
    public function fixClosedTask()
    {
        $this->dao->update(TABLE_TASK)->set('assignedTo')->eq('closed')->where('status')->eq('closed')->exec();

        return !dao::isError();
    }

    /**
     * Set default salesGroup when upgrade from 2.0.
     *
     * @access public
     * @return int
     */
    public function setSalesGroup()
    {
        $sales = $this->dao->select('DISTINCT createdBy')->from(TABLE_CUSTOMER)->fetchPairs();

        $manageAllUsers = $this->dao->select('t1.account, t1.group, t2.group, t2.method')
            ->from(TABLE_USERGROUP)->alias('t1')
            ->leftJoin(TABLE_GROUPPRIV)->alias('t2')->on('t1.group=t2.group')
            ->where('t2.method')->eq('manageAll')
            ->fetchAll();

        if(!empty($manageAllUsers))
        {
            foreach($manageAllUsers as $manageAllUser)
            {
                if(isset($sales[$manageAllUser->account])) continue;
                $sales[$manageAllUser->account] = $manageAllUser->account;
            }
        }

        $users = ',' . implode(',', $sales) . ',';

        $group = new stdclass();
        $group->name  = '销售人员';
        $group->desc  = '';
        $group->users = $users;

        $this->dao->insert(TABLE_SALESGROUP)->data($group)->exec();

        $groupID = $this->dao->lastInsertID();

        if(!empty($manageAllUsers))
        {
            foreach($manageAllUsers as $manageAllUser)
            {
                $data['salesgroup'] = $groupID;
                $data['account']    = $manageAllUser->account;
                $data['priv']       = 'view';
                $this->dao->insert(TABLE_SALESPRIV)->data($data)->exec();

                $data['priv'] = 'edit';
                $this->dao->insert(TABLE_SALESPRIV)->data($data)->exec();
            }
        }

        $this->dao->delete()->from(TABLE_GROUPPRIV)->where('method')->eq('manageAll')->exec();

        return !dao::isError();
    }

    /**
     * Format product for order when upgrade from 2.0.
     *
     * @access public
     * @return int
     */
    public function fixOrderProduct()
    {
        $orders = $this->dao->select('*')->from(TABLE_ORDER)->fetchAll();

        foreach($orders as $order)
        {
            $this->dao->update(TABLE_ORDER)->set('product')->eq(',' . $order->product . ',')->where('id')->eq($order->id)->exec();
        }

        return !dao::isError();
    }

    /**
     * Process desc of trade when upgrade from 2.2.
     *
     * @access public
     * @return void
     */
    public function processTradeDesc()
    {
        $trades = $this->dao->select('id, `desc`')->from(TABLE_TRADE)->fetchPairs();

        foreach($trades as $id => $trade)
        {
            $desc = strip_tags(htmlspecialchars_decode($trade));
            $this->dao->update(TABLE_TRADE)->set('desc')->eq($desc)->where('id')->eq($id)->exec();
        }

        return !dao::isError();
    }

    /**
     * Process customer edited date when upgrade from 2.3.
     *
     * @access public
     * @return void
     */
    public function processCustomerEditedDate()
    {
        $customers = $this->loadModel('customer', 'crm')->getList();
        foreach($customers as $customer)
        {
            $editedDate = $customer->editedDate;

            $this->app->loadLang('order', 'crm');
            $orders = $this->loadModel('order', 'crm')->getOrderForCustomer($customer->id);
            foreach($orders as $order)
            {
                if(!empty($order) and strtotime($order->editedDate) > strtotime($editedDate))  $editedDate = $order->editedDate;
                if(!empty($order) and strtotime($order->createdDate) > strtotime($editedDate)) $editedDate = $order->createdDate;
            }

            $contracts = $this->loadModel('contract', 'crm')->getList($customer->id);
            foreach($contracts as $contract)
            {
                if(!empty($contract) and strtotime($contract->editedDate) > strtotime($editedDate))  $editedDate = $contract->editedDate;
                if(!empty($contract) and strtotime($contract->createdDate) > strtotime($editedDate)) $editedDate = $contract->createdDate;
            }

            $this->app->loadLang('contact', 'crm');
            $this->app->loadConfig('contact', 'crm');
            $contacts = $this->loadModel('contact', 'crm')->getList($customer->id);
            foreach($contacts as $contact)
            {
                if(!empty($contact) and strtotime($contact->editedDate) > strtotime($editedDate))  $editedDate = $contact->editedDate;
                if(!empty($contact) and strtotime($contact->createdDate) > strtotime($editedDate)) $editedDate = $contact->createdDate;
            }

            if($editedDate != $customer->editedDate) $this->dao->update(TABLE_CUSTOMER)->set('editedDate')->eq($editedDate)->where('id')->eq($customer->id)->exec();
        }
        return true;
    }

    /**
     * Add attend holiday leave trip privilages. when upgrade from 2.4.
     *
     * @access public
     * @return bool
     */
    public function addAttendPriv()
    {
        $groups = $this->dao->select('id')->from(TABLE_GROUP)->fetchAll('id');
        $privs = array();
        $privs['attend']['personal'] = 'personal';
        $privs['attend']['edit']     = 'edit';
        $privs['leave']['personal']  = 'personal';
        $privs['leave']['create']    = 'create';
        $privs['leave']['edit']      = 'edit';
        $privs['leave']['delete']    = 'delete';
        $privs['trip']['personal']   = 'personal';
        $privs['trip']['create']     = 'create';
        $privs['trip']['edit']       = 'edit';
        $privs['trip']['delete']     = 'delete';
        foreach($groups as $group)
        {
            $priv = new stdclass();
            $priv->group  = $group->id;
            foreach($privs as $module => $modulePriv)
            {
                $priv->module = $module;
                foreach($modulePriv as $method => $methodPriv)
                {
                    $priv->method = $method;
                    $this->dao->replace(TABLE_GROUPPRIV)->data($priv)->exec();
                }
            }
        }

        return !dao::isError();
    }

    /**
     * Process block type.
     *
     * @access public
     * @return bool
     */
    public function processBlockType()
    {
        $blocksHasType = 'order,contract,customer,task,project,thread';
        $blocks = $this->dao->select('*')->from(TABLE_BLOCK)->where('block')->in($blocksHasType)->fetchAll();
        foreach($blocks as $block)
        {
            $block->params = json_decode($block->params);
            if($block->block == 'project')
            {
                if(!isset($block->params->status))
                {
                    $block->params->status = 'doing';
                    $params = helper::jsonEncode($block->params);
                    $this->dao->update(TABLE_BLOCK)->set('params')->eq($params)->where('id')->eq($block->id)->exec();
                }
            }
            else
            {
                if(!isset($block->params->type))
                {
                    if($block->block == 'order')    $block->params->type = 'assignedTo';
                    if($block->block == 'contract') $block->params->type = 'returnedBy';
                    if($block->block == 'customer') $block->params->type = 'today';
                    if($block->block == 'task')     $block->params->type = 'assignedTo';
                    if($block->block == 'thread')   $block->params->type = 'new';

                    $params = helper::jsonEncode($block->params);
                    $this->dao->update(TABLE_BLOCK)->set('params')->eq($params)->where('id')->eq($block->id)->exec();
                }
            }
        }

        return !dao::isError();
    }

    /**
     * Remove old todo module files.
     *
     * @access public
     * @return bool
     */
    public function removeOldTodoFile()
    {
        $dir = $this->app->getBasePath() . "app/oa/todo/";
        if(!file_exists($dir)) return true;
        return $this->app->loadClass('zfile')->removeDir($dir);
    }
}


text:
<project default="all" name="xpath-lang">

  <property file="build.properties"/>

  <dirname file="${ant.file}" property="project.dir" />
  <property name="src.dir" value="${project.dir}/src" />

  <property name="build.dir" value="${basedir}/build" />
  <property name="build.classes.dir" value="${build.dir}/classes" />

  <taskdef name="javac2" classname="com.intellij.ant.Javac2">
    <classpath refid="classpath.uidesigner" />
  </taskdef>
  <taskdef name="jflex" classname="JFlex.anttask.JFlexTask">
    <classpath location="${idea.home}/tools/jflex/lib/JFlex.jar"/>
  </taskdef>

  <path id="idea.classpath">
    <fileset dir="${idea.home}">
      <include name="lib/*.jar"/>
      <include name="redist/*.jar"/>
    </fileset>
  </path>

  <path id="classpath.uidesigner">
    <fileset dir="${idea.home}">
      <include name="lib/*.jar"/>
      <include name="redist/*.jar"/>
    </fileset>
  </path>

  <target name="init">
  </target>

  <target name="jflex" depends="init">
    <jflex skeleton="${idea.home}/tools/jflex/idea-flex.skeleton" nobak="true"
           file="${src.dir}/org/intellij/lang/xpath/xpath-lexer.flex" destdir="${src.dir}" charat="true"/>
  </target>

  <target name="compile" depends="init, jflex">
    <mkdir dir="${build.classes.dir}"/>
    <mkdir dir="${build.dir}/xslt-rt/classes"/>

    <javac2 srcdir="${src.dir}" destdir="${build.classes.dir}" source="1.5" target="1.5" debug="${compile.debug}" optimize="${compile.optimize}">
      <classpath refid="idea.classpath"/>
      <exclude name="com/**/*" />
    </javac2>

    <javac2 srcdir="../xslt-rt/src" destdir="${build.dir}/xslt-rt/classes" source="1.4" target="1.4" debug="${compile.debug}" optimize="${compile.optimize}">
      <exclude name="com/**/*" />
    </javac2>
  </target>

  <target name="build" depends="compile" description="Build project"/>

  <target name="jar" depends="build">
    <jar file="${build.dir}/xpath-lang.jar" compress="false">
      <zipfileset dir="${build.classes.dir}">
        <include name="**/*"/>
        <exclude name="**/run/rt/*"/>
      </zipfileset>
      <zipfileset dir="${src.dir}">
        <include name="icons/**/*"/>
        <include name="intentionDescriptions/**/*.*"/>
        <include name="inspectionDescriptions/**/*.*"/>
        <include name="**/*.xml"/>
        <include name="**/*.xsd"/>
        <include name="**/*.xsl"/>
        <include name="**/*.xhtml"/>
      </zipfileset>
      <zipfileset dir="${project.dir}">
        <include name="LICENSE"/>
        <include name="W3C Document License.htm"/>
        <include name="META-INF/*.*" unless="xpath-lang.embedded"/>
      </zipfileset>
    </jar>

    <jar file="${build.dir}/xslt-rt/xslt-rt.jar" compress="false">
      <zipfileset dir="${build.dir}/xslt-rt/classes">
        <include name="**/run/rt/**/*"/>
      </zipfileset>
    </jar>
  </target>

  <target name="all" depends="compile, jar"/>

  <target name="clean">
    <delete dir="${build.dir}"/>
  </target>
</project>

redpajama_set_name: RedPajamaGithub


text:
Deface::Override.new(:virtual_path  => "spree/shared/_search",
                     :insert_top => "input[type=submit]",
                     :text          => "<i class='icon-search'></i>",
                     :name          => "add_icon_to_search")
Deface::Override.new(:virtual_path  => "spree/shared/_search",
                     :add_to_attributes => "select, input[type=search]",
                     :attributes    => {:class => "top-search"},
                     :name          => "add_top-search_class")
Deface::Override.new(:virtual_path  => "spree/shared/_search",
                     :remove        => "select#taxon",
                     :name          => "remove_taxon_select")
Deface::Override.new(:virtual_path  => "spree/shared/_search",
                     :insert_after        => "select#taxon",
                     :text          => "TESTINGS!!",
                     :name => "test")


text:
package com.bricks.core.intercept;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import com.bricks.lang.log.LogAble;

/**
 * @author bricks <long1795@gmail.com>
 */
@Aspect
public class MethodLoggerInterceptor implements LogAble {
	@Around("execution (* com.bricks..*(..))")
	public Object invoke(ProceedingJoinPoint pjp) throws Throwable {
		long start = System.currentTimeMillis();
		Object result = pjp.proceed();
		log().info(">>>>>>>>>>>>>>>>>>#{}({}): {} in {}", MethodSignature.class.cast(pjp.getSignature()).getMethod().getName(),
				pjp.getArgs(), result,
				System.currentTimeMillis() - start);
		return result;
	}
}


text:
<?php

namespace Attendee\Bundle\ApiBundle\Controller;

use Attendee\Bundle\ApiBundle\Entity\User;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations as Rest;

/**
 * Class UsersController
 *
 * @Route("/users")
 *
 * @package Attendee\Bundle\ApiBundle\Controller
 */
class UsersController extends AbstractController
{
    /**
     * @param \Symfony\Component\HttpFoundation\Request $request
     *
     * @return array
     *
     * @Rest\View()
     * @Rest\Get("", name="api_users_index")
     *
     * @ApiDoc(
     *  description="Lists all users.",
     *  section="Users",
     *  parameters={
     *      {"name"="ids[]", "dataType"="integer", "required"=false}
     *  }
     * )
     *
     */
    public function indexAction(Request $request)
    {
        $ids = $request->get('ids');

        $users = $this->getUserService()->find($ids);

        return array(
            'users' => $users
        );
    }

    /**
     * @param \Symfony\Component\HttpFoundation\Request $request
     *
     * @Rest\View
     * @Rest\Post("", name="api_users_create")
     *
     * @ApiDoc(
     *  section="User",
     *  description="Create user."
     * )
     *
     * @return array
     */
    public function createAction(Request $request)
    {
        $data = $request->request->get('user');
        $form = $this->createForm('user', new User());
        $form->submit($data);

        $user = $form->getData();
        $this->getUserService()->save($user);

        return $this->showAction($user);
    }

    /**
     * @param User $user
     *
     * @Rest\View()
     * @Rest\Get("/{id}", name="api_users_show")
     *
     * @ApiDoc(
     *  resource=true,
     *  description="User detail.",
     *  section="User"
     * )
     *
     * @return array
     */
    public function showAction(User $user)
    {
        return array(
            'user' => $user
        );
    }
}


text:
package eclipseLib;

/**
 * Created in IntelliJ IDEA.
 * By: Alexander.Chernikov
 * When: 19.02.2009, 20:55:48
 * Русский текст.
 */
public class SourceThree {
	public static final String ELIB_CONST = "value 3";

	public void elibMethod() {
	}
}


text:
<?php
abstract class td_smart_list {

    private $counting_order_asc = false;    //how to count the items in the list
    private $counting_start = 1;            //start from 1 or 0 ? - As of 31 July 2015 IT'S NOT USED :(

    protected $use_pagination = false;      // if true: tells our render function to only output the current item

    private $list_items; // we keep the items on render here

    abstract protected function render_list_item($item_array, $current_item_id, $current_item_number, $total_items_number); //child classes must implement this :)

    /**
     * renders a smart list form content. This should be the ONLY public thing for now
     * @param $smart_list_settings array of settings for the smart list
     * @return string
     */
    function render_from_post_content($smart_list_settings) {

        $this->counting_order_asc = $smart_list_settings['counting_order_asc'];

        // make a new tokenizer
        $td_tokenizer = new td_tokenizer();
        $td_tokenizer->token_title_start = $smart_list_settings['td_smart_list_h'];
        $td_tokenizer->token_title_end = $smart_list_settings['td_smart_list_h'];

        // get the list items
        $list_items = $td_tokenizer->split_to_list_items(array(
	            'content' => $smart_list_settings['post_content'],
		        'extract_first_image' => $smart_list_settings['extract_first_image']
	        )
        );

	    //print_r($list_items);

        // no items found, we return the content as is
        if (empty($list_items['list_items'])) {
            return $smart_list_settings['post_content'];
        }

        // we need to number all the items before pagination because item 2 can have number 4 if the counting method is desc
        $list_items = $this->add_numbers_to_list_items($list_items);

        if ($this->use_pagination === true) {
            $current_page = $this->get_current_page($list_items);
            return $this->render($list_items, $current_page);
        } else {
            return $this->render($list_items);
        }

    }

    /**
     * Calculate the total item number and the current item number
     *  current item number can be asc, desc and start from 0 or 1 etc.
     * @param $list_items
     * @return array - $list_items with added 'current_item_number' and 'total_items_number' keys
     */
    private function add_numbers_to_list_items($list_items) {

        $total_items_number = count($list_items['list_items']) - 1 + $this->counting_start; // fix for 0 base counting (0 of 3 - to -  3 of 3)

        //render each item using the render_list_item method from the child class
        foreach ($list_items['list_items'] as $list_item_key => &$list_item) {

            //how to count (asc or desc)
            if ($this->counting_order_asc === true) {
                $current_item_index = $list_item_key + $this->counting_start;
            } else {
                $current_item_index = $total_items_number - ($list_item_key);
            }

            $list_item['current_item_number'] = $current_item_index;
            $list_item['total_items_number'] = $total_items_number;
        }

        return $list_items;
    }

    /**
     * This is the rendering function. It gets a list of items and it outputs HTML
     * @param $list_items - the smart list list of items
     * @return string - the smart list's HTML
     */
    private function render($list_items, $current_page = false) {
        /*
        $total_pages = count($this->list_items['list_items']);
        if ($current_page > $total_pages) {
            status_header(404);
            nocache_headers();
            include( get_404_template() );
            exit;
        }
        */

        // we make the list items available to other functions (like pagination)
        $this->list_items = $list_items;

        $buffy = '';

        /*  ----------------------------------------------------------------------------
            add the before_list content
         */
        if (!empty($list_items['before_list'])) {
            $buffy .= implode('', $list_items['before_list']);
        }

        /*  ----------------------------------------------------------------------------
            add the list
         */
        $buffy .= $this->render_before_list_wrap();  //from child class

        if ($current_page === false) {
            //render each item using the render_list_item method from the child class
            foreach ($list_items['list_items'] as $list_item_key => $list_item) {
                $buffy .= $this->render_list_item($list_item, $list_item_key + 1, $list_item['current_item_number'], $list_item['total_items_number']);
            }
        } else {

            $array_id_from_paged = $current_page - 1;
            $buffy .= $this->render_list_item(
                $list_items['list_items'][$array_id_from_paged],
                $array_id_from_paged,
                $list_items['list_items'][$array_id_from_paged]['current_item_number'],
                $list_items['list_items'][$array_id_from_paged]['total_items_number']
            );
        }

        $buffy .= $this->render_after_list_wrap(); //from child class - render the list wrap end

        /*  ----------------------------------------------------------------------------
            add the after_list content
         */
        if (!empty($list_items['after_list'])) {
            $buffy .= implode('', $list_items['after_list']);
        }

        return $buffy;
    }

    /**
     * callback function, it's used by smart lists child to render the pagination
     * @uses td_smart_list::list_items
     * @return string
     */
    protected function callback_render_pagination() {

        $buffy = '';

        $current_page = $this->get_current_page($this->list_items);
        $total_pages = count($this->list_items['list_items']);

        // no pagination if we have one page!
        if ($total_pages == 1) {
            return '';
        }

        //        echo $paged;
        //        echo $total_pages;

        if ($current_page == 1) {
            // first page
            $buffy .= '
';
                $buffy .= '' .__td('Back', TD_THEME_NAME). '';
                $buffy .= '_wp_link_page($current_page + 1) . '">' .__td('Next', TD_THEME_NAME). '';
            $buffy .= '
';
        }
        elseif ($current_page == $total_pages) {
            // last page
            $buffy .= '
';
                $buffy .= '_wp_link_page($current_page - 1) . '">' .__td('Back', TD_THEME_NAME). '';
                $buffy .= '' .__td('Next', TD_THEME_NAME). '';
            $buffy .= '
';
        }
        else {
            // middle page
            $buffy .= '
';
                $buffy .= '_wp_link_page($current_page - 1) . '">' .__td('Back', TD_THEME_NAME). '';
                $buffy .=  '_wp_link_page($current_page + 1) . '">' .__td('Next', TD_THEME_NAME). '';
            $buffy .= '
';
        }

        return $buffy;
    }

    protected function callback_render_drop_down_pagination() {
        $buffy = '';

        $current_page = $this->get_current_page($this->list_items);
        $total_pages = count($this->list_items['list_items']);

        // no pagination if we have one page!
        if ($total_pages == 1) {
            return '';
        }

        $buffy .= '
';

        // render back page button
        if ($current_page == 1) {
            // is first page
            $buffy .= '' .__td('Back', TD_THEME_NAME). '';
        } else {
            $buffy .= '_wp_link_page($current_page - 1) . '">' .__td('Back', TD_THEME_NAME). '';
        }

        // render the drop down
        $buffy .= '
<select class="td-smart-list-dropdown">';
        foreach ($this->list_items['list_items'] as $index => $list_item) {
            $list_item_page_nr = $index + 1;
            $selected = '';

            if ($current_page == $list_item_page_nr) {
                $selected = 'selected';
            }

            $buffy .= '<option ' . $selected . ' value="' . esc_attr($this->_wp_link_page($list_item_page_nr)) . '">' . $list_item['current_item_number'] . ' - ' . $list_item['title'] . '</option>';
        }
        $buffy .= '<select>
';

        // render next page button
        if ($current_page == $total_pages) {
            // is last page
            $buffy .= '' .__td('Next', TD_THEME_NAME). '';
        } else {
            $buffy .=  '_wp_link_page($current_page + 1) . '">' .__td('Next', TD_THEME_NAME). '';
        }

        $buffy .= '
';

        return $buffy;
    }

    /**
     * Hax to intercept the current page of the post
     * @return int|mixed
     */
    private function get_current_page($list_items) {
        $td_page = (get_query_var('page')) ? get_query_var('page') : 1; //rewrite the global var
        $td_paged = (get_query_var('paged')) ? get_query_var('paged') : 1; //rewrite the global var
        //paged works on single pages, page - works on homepage
        if ($td_paged > $td_page) {
            $current_page = $td_paged;
        } else {
            $current_page = $td_page;
        }
        // if no pages, we are on the first page
        if (empty($current_page)) {
            return 1;
        }

        // if the requested page is bigger than our number of items, return the last page
        // this is how the default wordpress post pagination works!
        $total_pages = count($list_items['list_items']);
        if ($current_page > $total_pages) {
            $current_page = $total_pages;
        }

        return $current_page;
    }

    /**
     * This function returns the pagination link for the current post
     * TAGDIV: - taken from wordpress wp-includes/post-template.php
     *         - we removed the wrapping
     *         - original name: _wp_link_page
     *
     * Helper function for wp_link_pages().
     *
     * @since 3.1.0
     * @access private
     *
     * @param int $i Page number.
     * @return string Link.
     */
    private function _wp_link_page( $i ) {
        global $wp_rewrite;
        $post = get_post();

        if ( 1 == $i ) {
            $url = get_permalink();
        } else {
            if ( '' == get_option('permalink_structure') || in_array($post->post_status, array('draft', 'pending')) )
                $url = add_query_arg( 'page', $i, get_permalink() );
            elseif ( 'page' == get_option('show_on_front') && get_option('page_on_front') == $post->ID )
                $url = trailingslashit(get_permalink()) . user_trailingslashit("$wp_rewrite->pagination_base/" . $i, 'single_paged');
            else
                $url = trailingslashit(get_permalink()) . user_trailingslashit($i, 'single_paged');
        }

        if ( is_preview() ) {
            $url = add_query_arg( array(
                'preview' => 'true'
            ), $url );

            if ( ( 'draft' !== $post->post_status ) && isset( $_GET['preview_id'], $_GET['preview_nonce'] ) ) {
                $url = add_query_arg( array(
                    'preview_id'    => wp_unslash( $_GET['preview_id'] ),
                    'preview_nonce' => wp_unslash( $_GET['preview_nonce'] )
                ), $url );
            }
        }

        return esc_url( $url );
    }

    /**
     * what to render at the start of the smart list (usually it's overwritten by child classes)
     */
    protected function render_before_list_wrap() {
        return '';
    }

    /**
     * what to render at the end of the list (usually it's overwritten by child classes)
     */
    protected function render_after_list_wrap() {
        return '';
    }

}

/**
 * Class td_tokenizer - the magic tokenizer
 */
class td_tokenizer {

    private $log = false; //enable or disable the log
    private $last_log_function = '';
    private $last_log_token = '';
    private $last_token_id = 0;

    var $token_title_start = 'h3';
    var $token_title_end = 'h3';
    private $token_title_is_open = false; //are we in the title tag?
    private $token_td_smart_list_end = false; //did we reach the end of the list

    private $current_list_item = array(); //here we keep the current list item

    private $buffy = array();

    function __construct() {
        $this->current_list_item = $this->get_empty_list_item();

    }

    function split_to_list_items ($params) {

	    $content = $params['content'];
	    $extract_first_image = $params['extract_first_image'];

        //(<figure.*<\/figure>) - html5 image + caption
        //(
.*<a.*<img.*<\/a>.*<\/p>) - p a img
        //(<a.*) - a img
        //(
.*.*<\/p>) - p img
        //() - img
        //(
.*[.*td_smart_list_end.*].*<\/p>) -
 [td_smartlist_end]

        //([.*td_smart_list_end.*]) - [td_smartlist_end] without p

	    // add the image regex ONLY if we want to also extract the image
	    $img_regex = '';
	    if ($extract_first_image === true) {
		    $img_regex = "(<figure.*
)|" .
		                 "(
.*<a.*<img.*.*
)|" .  //two step - checks for image + description
		                 "(<a.*<img.*)|" .
		                 "(
.*.*
)|" .
		                 "()|";
	    }

        $td_magic_regex = $this->fix_regex(
            "(<$this->token_title_start.*?>)|" .
            "(</$this->token_title_end>)|" .
            $img_regex .
            "(
.*[.*td_smart_list_end.*].*
)|" .
            "([.*td_smart_list_end.*])");
        //echo $td_magic_regex;

        $tokens_list = preg_split('/' . $td_magic_regex . '/', $content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        $tokens_list = array_map('trim', $tokens_list); //trim elements
        $tokens_list = array_filter( $tokens_list, 'strlen'); //filter empty, null etc except 0 (may be a bug 0)

        //print_r($tokens_list);

        foreach($tokens_list as $token) {

            if ($this->is_title_open($token)) {
            }

            elseif($this->is_content_after_smart_list($token)) {
            }

            elseif ($this->is_content_before_smart_list($token)) {

            }

            elseif ($this->is_title_close($token)) {
            }

            elseif ($this->is_title_text($token)) {
            }

            elseif ($this->is_first_image($token) and $extract_first_image === true) {
            }

            elseif($this->is_smart_list_end($token)) {
            }

            elseif ($this->is_description($token)) {
            }

            else {
                //normal content?
                $this->log_step('no match', $token);
            }

            $this->log_loop_complete();
        }

        //add the remaining element (last one)
        if (!empty($this->current_list_item['title'])) {
            $this->buffy['list_items'][] = $this->current_list_item;
        }

        return $this->buffy;
    }

    private function get_empty_list_item () {
        return array(
            'title' => '',
            'first_img_id' => '',
            'description' => '',
            'read_more_link' => ''
        );
    }

    private function is_title_open($token) {
        $this->log_step(__FUNCTION__, $token);
        $matches = array();
        preg_match('/<' . $this->token_title_start . '.*?>/', $token, $matches); //match

        if (!empty($matches)) {
            $this->token_title_is_open = true;
            return true;
        } else {
            return false;
        }

    }

    private function is_title_close($token) {
        $this->log_step(__FUNCTION__, $token);
        if ($token == '</' . $this->token_title_end . '>') {
            $this->token_title_is_open = false; //make sure we change the h3 state
            return true;
        } else {
            return false;
        }
    }

    /**
     * this function also pushes the working buffer ($this->current_list_item) to $this->buffy
     * @param $token
     * @return bool
     */
    private function is_title_text($token) {
        $this->log_step(__FUNCTION__, $token);
        if ($this->token_title_is_open === true) {

            //if the last list item is not empty, we add it to the list_items buffer
            if (!empty($this->current_list_item['title'])) {
                $this->buffy['list_items'][] = $this->current_list_item;
            }

            //empty the list - RESET

            $this->current_list_item = $this->get_empty_list_item();
            $this->current_list_item['title'] = $token; //put the new title

            $this->token_title_is_open = false; //make sure we change the h3 state - this is a fix for cases when we don't have h3

            return true;
        } else {
            return false;
        }
    }

    private function is_smart_list_end($token) {
        $this->log_step(__FUNCTION__, $token);

        $matches = array();
        preg_match('/\[.*td_smart_list_end.*\]/', $token, $matches);

        if (!empty($matches[0])) {
            $this->token_td_smart_list_end = true;
            return true;
        } else {
            return false;
        }
    }

    /**
     * returns true if the content is before the smart list
     */
    private function is_content_before_smart_list($token) {
        $this->log_step(__FUNCTION__, $token);
        if (($this->token_title_is_open === true or !empty($this->current_list_item['title']) ) and $this->token_td_smart_list_end === false) {
            return false;

        } else {
            $this->buffy['before_list'][] = $token;
            return true;

        }
    }

    /**
     * returns true if the content is after the smart list
     */
    private function is_content_after_smart_list($token) {
        $this->log_step(__FUNCTION__, $token);
        if ($this->token_td_smart_list_end === true) {
            $this->buffy['after_list'][] = $token;
            return true;

        } else {
            return false;
        }
    }

    /**
     * returns true only if it's the first image
     * @param $token
     * @return bool
     */
    private function is_first_image($token) {
        $this->log_step(__FUNCTION__, $token);
        if (!empty($this->current_list_item['first_img_id'])) { //we already have the first image for this item
            return false;
        }

        $matches = array();
        preg_match('/wp-image-([0-9]+)/', $token, $matches);

        //do we have an image?
        if (!empty($matches[1])) {

            //do we have also some description in the same paragraph with the image?
            $tmp_description = $this->extract_description_from_first_image($token);

            /*
            echo '

            -----x-----------

            ';

            echo $token;

            echo '
            ---->
            ';

            echo $tmp_description;

            echo '
            --
            ';

            */
            if ($tmp_description != '') {
                $this->current_list_item['description'] .= $tmp_description;
            }

            $this->current_list_item['first_img_id'] = $this->get_image_id_from_token($token);
            return true;
        } else {
            return false;
        }
    }

    /**
     * It takes a paragraph
 and:
     * 1. it extracts all the links and searches each one for images. If an image is found, it is removed from the text because it's already used as a first_image
     * 2. if no links with images are found, it searches for raw images without any link. It also removes the first one.
     * @param $token
     * @return mixed
     */
    private function extract_description_from_first_image($token) {
        $matches = '';
        $buffy = '';

        //0. check if we have a figure in the token. Figures are USUALLY alone (not in paragraph)
        if (strpos($token,'<figure') !== false) {
            return '';
        }

        //1. search for all the links in this toke / block of text - if this steps retuns something, the second step doesn't run
        preg_match_all('//U', $token, $matches); //extract all links
        if (!empty($matches[0]) and is_array($matches[0])) {
            foreach ($matches[0] as $match) {
                if (strpos($match, 'fix_regex($match) . '/', '', $token, 1); //remove the first image because that will be used as first_image
                    break;
                }
            }
        }

        //2. no match found
        if ($buffy == '') {
            //search for the FIRST img if we didn't find any links in the block of text
            $matches = '';
            preg_match('//U', $token, $matches); //extract first image
            if (!empty($matches[0])) {
                // we need the extra str_replace because the $matches[0] is user entered in tinymce
                $input_regex = str_replace('(', '\(', $matches[0]);
                $input_regex = str_replace(')', '\)', $input_regex);
                $buffy = preg_replace('/' . $this->fix_regex($input_regex) . '/', '', $token, 1); //remove the first image because that will be used as first_image
            }
        }

        $buffy = trim($buffy);

        return $buffy;
    }

    /**
     * returns true only if the current item has a title
     * @param $token
     * @return bool
     */
    private function is_description($token) {
        $this->log_step(__FUNCTION__, $token);
        if (!empty($this->current_list_item['title']) and $this->token_td_smart_list_end === false) {  //if we have a item with title and the list did not ended, it's a description if not it's random text
            $this->current_list_item['description'] .= $token;
            return true;
        } else {
            return false;
        }
    }

    private function get_image_id_from_token($token) {
        $matches = array();
        preg_match('/wp-image-([0-9]+)/', $token, $matches);
        if (!empty($matches[1])) {
            return $matches[1];
        } else {
            return '';
        }
    }

    private function log_step($function_name, $token = '') {
        if ($this->log === true) {
            $this->last_log_function = $function_name;
            $this->last_log_token = $token;

        }
    }

    private function log_loop_complete() {
        if ($this->log === true) {
            //echo "\n -- Step complete -- \n\n";
            echo $this->last_token_id . ' ' . $this->last_log_function . ' -- token: ' . $this->last_log_token . "\n";

            $this->last_log_token = '';
            $this->last_log_function = '';

            $this->last_token_id++;
        }
    }

    /**
     * fix the regex string
     * @param $input_regex
     * @return mixed
     */
    private function fix_regex($input_regex) {
        $input_regex = str_replace('/', '\/', $input_regex);
        $input_regex = str_replace(']', '\]', $input_regex);
        $input_regex = str_replace('[', '\[', $input_regex);
        return $input_regex;
    }

}


text:
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is. Is it related to core functionality or plugin to some framework.

**To Reproduce**
Steps and link to sandbox. You can use [jsfiddle](https://jsfiddle.net/), [StackBlitz](https://stackblitz.com/), [CodePen](https://codepen.io/), [CodeSandbox](https://codesandbox.io/) and any other.

**Expected behavior**
A clear and concise description of what you expected to happen.

**Environment:**
 - OS: [e.g. iOS]
 - Browser [e.g. chrome, safari]
 - Version [e.g. 22]
 - IMask version
 - Framework/plugin version if used

**Additional context**
Add any other context about the problem here.


text:
package com.yrkj.controller;

import com.yrkj.model.Integral.CourierInput;
import com.yrkj.model.Integral.IntegralSearch;
import com.yrkj.model.core.*;
import com.yrkj.model.product.Product;
import com.yrkj.model.product.ProductSearch;
import com.yrkj.service.OrderService;
import com.yrkj.service.ProductService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by xuenianxiang on 2017/6/18.
 */

@RestController
@RequestMapping("/api/product")
@EnableSwagger2
@Api(description = "商品管理接口")
public class ProductController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService _orderService;
    @ApiOperation(value = "创建产品",notes = "创建产品")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ActionResult add(@RequestBody Product product) {
        Claims claims = (Claims)request.getAttribute("claims");
        product.setCreate_by(claims.getSubject());
        product.setCreate_time(new Date());
        return productService.add(product);
    }

    @ApiOperation(value = "更新产品",notes = "更新产品")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ActionResult update(@RequestBody Product product) {
        Claims claims = (Claims)request.getAttribute("claims");
        product.setUpdate_by(claims.getSubject());
        product.setUpdate_time(new Date());
        return productService.update(product);
    }

    @ApiOperation(value = "批量删除产品",notes = "批量删除产品")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ActionResult delete(@RequestBody IdsInput input) {
        Claims claims = (Claims)request.getAttribute("claims");
        IdsModel model = new IdsModel();
        model.setList(input.getList());
        model.setUpdate_by(claims.getSubject());
        model.setUpdate_time(new Date());
        return productService.deleteProducts(model);
    }

    @ApiOperation(value = "批量更改状态",notes = "批量更改状态")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public ActionResult updateStatus(@RequestBody ChangeStatusInput input) {
        Claims claims = (Claims)request.getAttribute("claims");
        ChangeStatusModel model = new ChangeStatusModel();
        model.setStatus(input.getStatus());
        model.setList(input.getList());
        model.setUpdate_by(claims.getSubject());
        model.setUpdate_time(new Date());

        return productService.updateStatus(model);
    }

    @ApiOperation(value = "获取产品详情",notes = "获取产品详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public ActionResult get(@RequestParam Long id) throws ServletException {
        return productService.getById(id);
    }

    @ApiOperation(value = "获取产品列表",notes = "获取产品列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public PageModel list(@RequestBody ProductSearch model) {
        return productService.getAll(model);
    }

    @ApiOperation(value = "获取单一产品列表",notes = "获取单一产品列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/singleList", method = RequestMethod.POST)
    public PageModel singleList(@RequestBody ProductSearch model) {
        return productService.getAllSingle(model);
    }

    @ApiOperation(value = "获取勋章商品列表",notes = "获取勋章商品列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/badgeList", method = RequestMethod.POST)
    public PageModel badgeList(@RequestBody ProductSearch model) {
        return productService.getBadgeList(model);
    }

    @ApiOperation(value = "获取订单列表",notes = "获取订单列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/orders", method = RequestMethod.POST)
    public PageModel OrderList(@RequestBody IntegralSearch model) {
        return _orderService.GetOrdersList(model);
    }
    @ApiOperation(value = "修改快递信息",notes = "修改快递信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/updateCourier", method = RequestMethod.POST)
    public ActionResult UpdateCourier(@RequestBody CourierInput model) {
        return _orderService.UpdateCourier(model);
    }
    @ApiOperation(value = "获取订单详情",notes = "获取订单详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "authorization", value = "Bearer {token}", required = true, dataType = "String",paramType = "header")})
    @RequestMapping(value = "/order", method = RequestMethod.GET)
    public ActionResult Order(@RequestParam String orderNum) {
        return _orderService.GetOrderDetail(orderNum);
    }
}


text:
title: Free Code Camp Hotkeys
localeTitle: Free Code Camp Hotkeys
---
freeCodeCamp tiene varias teclas de acceso rápido, por lo que los usuarios avanzados pueden moverse rápidamente.

## Cómo utilizar las teclas de acceso rápido

Para usar estas teclas de acceso rápido, debe presionar las teclas en el orden en que aparecen. Es importante tener en cuenta que no debe presionarlos al mismo tiempo.

### Redireccionar teclas de acceso rápido

g n n Redirige al siguiente reto.
g n a Redirige a la página acerca de
g n m Redirecciona al mapa.
g n s Redirecciona a la tienda.
g n o Redirige a la configuración
g n r Redirige al repositorio de Free Code Camp GitHub
g n w Redirecciona al foro

### Teclas de acceso directo del editor

Estas teclas de acceso rápido deben presionarse al mismo tiempo, no en orden.

Ctrl + Enter Ejecuta las pruebas. Si la vez anterior las pruebas fueron exitosas, esto envía el desafío y pasa a la siguiente
Ctrl + / Comentarios o descomenta la línea actual o el código seleccionado

### Otras teclas de acceso rápido

g m Alternar el cajón del mapa
g t n Conmutar modo nocturno
g c Alternar el chat principal (Gitter)

Esc Si presiona esto mientras la entrada de búsqueda está enfocada, vacía la entrada


text:
package edu.teco.dnd.module.permissions;

import java.security.Permission;
import java.util.ArrayList;
import java.util.List;

/**
 * Combines multiple PolicyRules, returning the first result that is not null.
 */
public class PolicyRuleCombiner implements PolicyRule {
	private final List<PolicyRule> rules = new ArrayList<PolicyRule>();

	public void addRule(final PolicyRule rule) {
		rules.add(rule);
	}

	@Override
	public Boolean getPolicy(final Permission permission, final StackTraceElement[] stackTrace) {
		for (final PolicyRule rule : rules) {
			final Boolean policy = rule.getPolicy(permission, stackTrace);
			if (policy != null) {
				return policy;
			}
		}
		return null;
	}
}


text:
from django.forms import ModelForm

from .models import PakistaniPlace

class PakistaniPlaceForm(ModelForm):
    """ Form for storing a Pakistani place. """
    class Meta:
        model = PakistaniPlace
        fields = ('state', 'state_required', 'state_default', 'postcode', 'postcode_required', 'postcode_default',
                  'phone', 'name')


text: My profile/resume


text:
rm -rf ./Mixpanel_h
rm Mixpanel.h
cat ../Mixpanel/MixpanelPeople.h ../Mixpanel/Mixpanel.h >> Mixpanel.h
headerdoc2html -q -o . Mixpanel.h
rm Mixpanel.h
open Mixpanel_h/index.html


text:
import numpy as np
from PIL import Image
from rl.core import Processor

class SeleniumObservationProcessor(Processor):
    def __init__(self, window_height, window_width):
        self.window_height = window_height
        self.window_width = window_width

    def process_observation(self, observation):
        #  TODO Add a text observation of the url or html?
        vision_observation = observation[0][0].get('vision', None)
        assert vision_observation.ndim == 3  # (height, width, channel)
        vision_observation = vision_observation[0:self.window_height, 0:self.window_width]
        img = Image.fromarray(vision_observation)
        img = img.convert('L')  # convert to grayscale
        processed_observation = np.array(img)
        return processed_observation.astype('uint8')  # saves storage in experience memory

    def process_state_batch(self, batch):
        processed_batch = batch.astype('float32') / 255.
        return processed_batch

    def process_reward(self, reward):
        return np.clip(reward, -1., 1.)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ly_main_tab_bottom"
    android:layout_width="fill_parent"
    android:layout_height="55dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/bottom_bar" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="55dp" >

        <LinearLayout
            android:id="@+id/id_tab_bottom_weixin"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:descendantFocusability="beforeDescendants"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/btn_tab_bottom_weixin"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#0000"
                android:clickable="false"
                android:src="@drawable/tab_weixin_pressed" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="微信" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/id_tab_bottom_friend"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:descendantFocusability="beforeDescendants"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/btn_tab_bottom_friend"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#0000"
                android:clickable="false"
                android:src="@drawable/tab_find_frd_normal" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="朋友" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/id_tab_bottom_contact"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:descendantFocusability="beforeDescendants"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/btn_tab_bottom_contact"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#0000"
                android:clickable="false"
                android:src="@drawable/tab_address_normal" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="通讯录" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/id_tab_bottom_setting"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:descendantFocusability="beforeDescendants"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/btn_tab_bottom_setting"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#0000"
                android:clickable="false"
                android:src="@drawable/tab_settings_normal" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="设置" />
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>


text:
package service

import (
	"net/http"
	"sysware.com/ivideo/common"
	"sysware.com/ivideo/model"
	"testing"
)

func Test_ServerConfigSaveHandleCMSImplSave(t *testing.T) {
	saveInfo := &serverConfigSaveHandleCMSImpl{}
	req, err := http.NewRequest("GET", "http://192.168.128.154/server/saveconfig?servername=中心管理服务器1&servertype=0&dbAddress=jdbc:oracle:thin:@192.168.5.99:1521:orcl&dbUserName=ivideo&dbPassword=sysware&dbDefaultSchema=ivideo&activemqAddress=tcp://192.168.5.154:61616", nil)
	if nil != err {
		t.Error(err)
	}
	req.Header.Set("Content-Type", "application/json; charset=UTF-8")
	err = req.ParseForm()
	if nil != err {
		t.Error(err)
	}
	serverInfo := &model.ServerInfo{ServerName: "中心管理服务器1", Address: "/home/pc01/source/java/apache-tomcat-7.0.53/webapps/cms", Type: common.SERVER_TYPE_CMS}
	err = saveInfo.Save(req, serverInfo)
	if nil != err {
		t.Error(err)
	}
}


text:
package ru.job4j;

import java.util.Date;

/**
 * class Teacher extends Profession.
 *
 * @author Ruzhev Alexander
 * @since 29.03.2017
 */
public class Teacher extends Profession {
    /**
     * Constructor extends Profession.
     *
     * @param name       - name
     * @param age        - age
     * @param employed   - date employed
     * @param profession - profession teacher
     */
    public Teacher(String name, int age, Date employed, String profession) {
        super(name, age, employed, profession);
    }

    /**
     * teach the student.
     *
     * @param student - object Engineer
     */
    public void teach(Engineer student) {
        System.out.printf("Teacher %s teaches engineer %s", this.getName(), student.getName());
    }

    /**
     * teach the student.
     *
     * @param student - object MedicalDoctor
     */
    public void teach(MedicalDoctor student) {
        System.out.printf("Teacher %s teaches medical doctor %s", this.getName(), student.getName());
    }

    /**
     * test job.
     */
    public void testJob() {
        System.out.printf("Teacher %s checks the work of the group", this.getName());
    }

    /**
     * give homework.
     */
    public void toGiveHomework() {
        System.out.printf("Teacher %s gives homework group", this.getName());
    }
}


text:
package codetoanalyze.java.incremental.child_changed;

class Parent {

  Object foo() {
    Child c = new Child();
    Object o = c.bar();
    return o;
  }

  void dontReanalyze() {
    Object o1 = new Object();
  }

}


text:
<?php

namespace Nim\Bundle\WorkerBundle\Model;

use Nim\Component\Resource\Model\SoftDeletableTrait;
use Nim\Component\Resource\Model\TimestampableTrait;

class Phone implements PhoneInterface
{
    use \Nim\Component\Resource\Model\SoftDeletableTrait,
        \Nim\Component\Resource\Model\TimestampableTrait;

    protected $id;
    protected $type;
    protected $number;

    /**
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * {@inheritdoc}
     */
    public function setNumber($number)
    {
        $this->number = $number;
    }

    /**
     * {@inheritdoc}
     */
    public function getNumber()
    {
        return $this->number;
    }
}


text:
package com.uppidy.android.demo.app;

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.DuplicateConnectionException;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.GrantType;
import org.springframework.social.oauth2.OAuth2Parameters;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.uppidy.android.sdk.R;
import com.uppidy.android.sdk.api.Uppidy;
import com.uppidy.android.sdk.connect.UppidyConnectionFactory;

/**
 * @author arudnev@uppidy.com
 */
public class UppidyWebOAuthActivity extends AbstractWebViewActivity {

	private static final String TAG = UppidyWebOAuthActivity.class.getSimpleName();

	private ConnectionRepository connectionRepository;

	private UppidyConnectionFactory connectionFactory;

	// ***************************************
	// Activity methods
	// ***************************************
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Uppidy uses javascript to redirect to the success page
		getWebView().getSettings().setJavaScriptEnabled(true);

		// Using a custom web view client to capture the access token
		getWebView().setWebViewClient(new UppidyOAuthWebViewClient());

		this.connectionRepository = getApplicationContext().getConnectionRepository();
		this.connectionFactory = getApplicationContext().getUppidyConnectionFactory();
	}

	@Override
	public void onStart() {
		super.onStart();

		// display the Uppidy authorization page
		getWebView().loadUrl(getAuthorizeUrl());
	}

	// ***************************************
	// Private methods
	// ***************************************
	private String getAuthorizeUrl() {
		String redirectUri = getString(R.string.uppidy_oauth_callback_url);
		String scope = getString(R.string.uppidy_scope);

		/*
		 * Generate the Uppidy authorization url to be used in the browser or web view the display=touch parameter
		 * requests the mobile formatted version of the Uppidy authorization page
		 */
		OAuth2Parameters params = new OAuth2Parameters();
		params.setRedirectUri(redirectUri);
		params.setScope(scope);
		params.add("display", "touch");
		return this.connectionFactory.getOAuthOperations().buildAuthorizeUrl(GrantType.IMPLICIT_GRANT, params);
	}

	private void displayUppidyOptions() {
		Intent intent = new Intent();
		intent.setClass(this, UppidyActivity.class);
		startActivity(intent);
		finish();
	}

	// ***************************************
	// Private classes
	// ***************************************
	private class UppidyOAuthWebViewClient extends WebViewClient {

		/*
		 * The WebViewClient has another method called shouldOverridUrlLoading which does not capture the javascript
		 * redirect to the success page. So we're using onPageStarted to capture the url.
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// parse the captured url
			Uri uri = Uri.parse(url);

			Log.d(TAG, url);

			/*
			 * The access token is returned in the URI fragment of the URL.
			 * See details of authentication / authorization support via the following link:
			 *
			 * http://develop.uppidy.com/docs/auth/
			 *
			 * The fragment will be formatted like this:
			 *
			 * #access_token=A&expires_in=0
			 */
			String uriFragment = uri.getFragment();

			// confirm we have the fragment, and it has an access_token parameter
			if (uriFragment != null && uriFragment.startsWith("access_token=")) {
				// split to get the two different parameters
				new ConnectTask().execute(uriFragment.split("&"));
			}

			/*
			 * if there was an error with the oauth process, return the error description
			 *
			 * The error query string will look like this:
			 *
			 * ?error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request
			 */
			if (uri.getQueryParameter("error") != null) {
				CharSequence errorReason = uri.getQueryParameter("error_description").replace("+", " ");
				Toast.makeText(getApplicationContext(), errorReason, Toast.LENGTH_LONG).show();
				displayUppidyOptions();
			}
		}
	}

	// ***************************************
	// Private classes
	// ***************************************
	private class ConnectTask extends AsyncTask<String, Void, Connection<Uppidy>> {

		@Override
		protected void onPreExecute() {
			// before the network request begins, show a progress indicator
			showProgressDialog("Establishing connection to Uppidy...");
		}

		@Override
		protected Connection<Uppidy> doInBackground(String... params) {
			Connection<Uppidy> connection = null;
			try {
				/*
				 * The fragment also contains an "expires_in" parameter. In this
				 * example we requested the offline_access permission, which
				 * basically means the access will not expire, so we're ignoring
				 * it here
				 */
				try {
					// split to get the access token parameter and value
					String[] accessTokenParam = params[0].split("=");

					// get the access token value
					String accessToken = accessTokenParam[1];

					// create the connection and persist it to the repository
					AccessGrant accessGrant = new AccessGrant(accessToken);
					connection = connectionFactory.createConnection(accessGrant);

					try {
						connectionRepository.addConnection(connection);
					} catch (DuplicateConnectionException e) {
						// connection already exists in repository!
						Log.w(TAG, "Connection already exists in repository", e);
					}
				} catch (Exception e) {
					// don't do anything if the parameters are not what is expected
					Log.w(TAG, "Could not create connection", e);
				}

				getApplicationContext().init();

			} catch (Exception e) {
				Log.e(TAG, e.getLocalizedMessage(), e);
			}
			return connection;
		}

		@Override
		protected void onPostExecute(Connection<Uppidy> result) {
			// after the network request completes, hide the progress indicator
			dismissProgressDialog();
			displayUppidyOptions();
		}

	}

}


text:
package com.codepath.apps.restclienttemplate.activities;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.codepath.apps.restclienttemplate.R;
import com.codepath.apps.restclienttemplate.databinding.ActivityProfileBinding;
import com.codepath.apps.restclienttemplate.fragments.TweetsListFragment;
import com.codepath.apps.restclienttemplate.fragments.UserTimelineFragment;
import com.codepath.apps.restclienttemplate.helper.TwitterApp;
import com.codepath.apps.restclienttemplate.helper.TwitterClient;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.codepath.apps.restclienttemplate.models.User;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;

import cz.msebera.android.httpclient.Header;

public class ProfileActivity extends AppCompatActivity implements TweetsListFragment.TweetSelectedListener {

    private ActivityProfileBinding binding;
    TwitterClient client;
    User mUser = null;
    UserTimelineFragment userTimelineFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);

        mUser = Parcels.unwrap(getIntent().getParcelableExtra("user"));
        //String screenName = getIntent().getStringExtra("screenName");

        if (mUser != null) {
            populateUserHeadline(mUser);
        } else {
            client = TwitterApp.getRestClient();

            client.getUserInfo(new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

                    try {
                        mUser = User.fromJSON(response);
                        User.currentUser = mUser;
                        //set the title of actionBar
                        getSupportActionBar().setTitle(mUser.screenName);
                        //populate user headline
                        populateUserHeadline(mUser);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }

    public void populateUserHeadline(User user) {

        // Display user timeline fragment inside container(dynamically)
        userTimelineFragment = UserTimelineFragment.newInstance(mUser.getScreenName());
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.flContainer, userTimelineFragment);
        ft.commit();

        TextView tvName = binding.tvName;
        TextView tvTagline = binding.tvTagline;
        TextView tvFollowers = binding.tvFollowers;
        TextView tvFollowing = binding.tvFollowing;

        ImageView ivProfileImage = binding.ivHeaderProfileImage;
        tvName.setText(user.name);

        tvTagline.setText(user.tagLine);
        tvFollowers.setText(user.followersCount + " Followers");
        tvFollowing.setText(user.followingCount + " Following");

        Glide.with(this).load(user.getProfileImageUrl()).into(ivProfileImage);

    }

    @Override
    public void onTweetSelected(Tweet tweet) {
        //Toast.makeText(this, tweet.user.screenName, Toast.LENGTH_SHORT).show();
        Intent i = new Intent(ProfileActivity.this, ProfileActivity.class);
        //i.putExtra("screenName", tweet.user.screenName);
        i.putExtra("user", Parcels.wrap(tweet.user));
        startActivity(i);
    }

}


text:
import os
import unittest

from svtplay_dl.fetcher.dash import _dashparse
from svtplay_dl.fetcher.dash import parse_duration
from svtplay_dl.utils.parser import setup_defaults

def parse(playlist):
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "dash-manifests", playlist)) as fd:
        manifest = fd.read()

    return _dashparse(setup_defaults(), manifest, "http://localhost", None)

class dashtest(unittest.TestCase):
    def test_parse_cmore(self):
        data = parse("cmore.mpd")
        assert len(data[3261.367].files) == 410
        assert len(data[3261.367].audio) == 615
        assert data[3261.367].segments

    def test_parse_fff(self):
        data = parse("fff.mpd")
        assert len(data[3187.187].files) == 578
        assert len(data[3187.187].audio) == 577
        assert data[3187.187].segments

    def test_parse_nya(self):
        data = parse("svtvod.mpd")
        assert len(data[2793.0].files) == 350
        assert len(data[2793.0].audio) == 350
        assert data[2793.0].segments

    def test_parse_live(self):
        data = parse("svtplay-live.mpd")
        assert len(data[2795.9959999999996].files) == 6
        assert len(data[2795.9959999999996].audio) == 6
        assert data[2795.9959999999996].segments

    def test_parse_live2(self):
        data = parse("svtplay-live2.mpd")
        assert len(data[2892.0].files) == 11
        assert len(data[2892.0].audio) == 11
        assert data[2892.0].segments

    def test_parse_duration(self):
        assert parse_duration("PT3459.520S") == 3459.52
        assert parse_duration("PT2.00S") == 2.0
        assert parse_duration("PT1H0M30.000S") == 3630.0
        assert parse_duration("P1Y1M1DT1H0M30.000S") == 34218030.0
        assert parse_duration("PWroNG") == 0


text:
package edu.washington.escience.myria.operator.apply;

import static org.junit.Assert.assertEquals;

import java.nio.ByteBuffer;

import org.junit.Test;

import com.google.common.collect.ImmutableList;

import edu.washington.escience.myria.DbException;
import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.Type;
import edu.washington.escience.myria.expression.Expression;
import edu.washington.escience.myria.expression.ExpressionOperator;
import edu.washington.escience.myria.expression.BitsetExpression;
import edu.washington.escience.myria.expression.VariableExpression;
import edu.washington.escience.myria.operator.Apply;
import edu.washington.escience.myria.operator.BatchTupleSource;
import edu.washington.escience.myria.storage.TupleBatch;
import edu.washington.escience.myria.storage.TupleBatchBuffer;
import edu.washington.escience.myria.util.TestEnvVars;

public class ApplyBitsetTest {

  @Test
  public void testApply() throws DbException {
    final Schema schema = Schema.ofFields("bytes", Type.BLOB_TYPE);
    final Schema expectedResultSchema = Schema.ofFields("bits", Type.BOOLEAN_TYPE);
    final TupleBatchBuffer input = new TupleBatchBuffer(schema);

    byte[] bytes = new byte[8];
    for (int i = 0; i < 8; ++i) {
      bytes[i] = (byte) (1 << i);
    }
    input.putBlob(0, ByteBuffer.wrap(bytes));

    ImmutableList.Builder<Expression> expressions = ImmutableList.builder();
    ExpressionOperator colIdx = new VariableExpression(0);
    ExpressionOperator bits = new BitsetExpression(colIdx);
    Expression expr = new Expression("bits", bits);
    expressions.add(expr);

    Apply apply = new Apply(new BatchTupleSource(input), expressions.build());
    apply.open(TestEnvVars.get());
    int rowIdx = 0;
    while (!apply.eos()) {
      TupleBatch result = apply.nextReady();
      if (result != null) {
        assertEquals(expectedResultSchema, result.getSchema());

        for (int batchIdx = 0; batchIdx < result.numTuples(); ++batchIdx, ++rowIdx) {
          int srcByteIdx = rowIdx / 8;
          int srcBitIdx = rowIdx % 8;
          boolean trueExpected = (srcByteIdx == srcBitIdx);
          assertEquals(trueExpected, result.getBoolean(0, batchIdx));
        }
      }
    }
    assertEquals(8 * 8, rowIdx);
    apply.close();
  }
}


text:
const React = window.React;

const TextInputFixtures = React.createClass({
  getInitialState() {
    return {
      color: '#ffaaee',
    };
  },

  renderControlled(type) {
    let id = `controlled_${type}`;

    let onChange = e => {
      let value = e.target.value;
      if (type === 'number') {
        value = value === '' ? '' : parseFloat(value, 10) || 0;
      }
      this.setState({
        [type] : value,
      });
    };

    let state = this.state[type] || '';

    return (

        {type}
        <input id={id} type={type} value={state} onChange={onChange} />
          → {JSON.stringify(state)}

    );
  },

  renderUncontrolled(type) {
    let id = `uncontrolled_${type}`;
    return (

        {type}
        <input id={id} type={type} />

    );
  },

  render() {
    // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
    let types = [
      'text', 'email', 'number', 'url', 'tel',
      'color', 'date', 'datetime-local',
      'time', 'month', 'week', 'range', 'password',
    ];
    return (
      <form onSubmit={event => event.preventDefault()}>
        <fieldset>
          <legend>Controlled</legend>
          {types.map(this.renderControlled)}
        </fieldset>
        <fieldset>
          <legend>Uncontrolled</legend>
          {types.map(this.renderUncontrolled)}
        </fieldset>
      </form>
    );
  },
});

module.exports = TextInputFixtures;