问:
Explode error in TYPO3 7.6 with compatibility6
I've got errors after update from TYPO3 6.2 to typo3 7.6 with compatibility6 mode enabled.

In the backend, when I need to edit page or article, the content is not charged in the textareas and I've got this warning

```<code>PHP Warning
Core: Error handler (BE): PHP Warning: explode() expects parameter 2 to be string, array given in /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Utility/GeneralUtility.php line 1556
</code>```

To try to debug it, i put a test in the trimExplode function of typo3 like this:

```<code>if(is_array($string)){
    $e = new \Exception();
    $error_string = $e->getTraceAsString();
    $f = fopen('/var/www/html/custom.log', 'a+');
    fputs($f, PHP_EOL . "new line" . PHP_EOL);
    fputs($f, PHP_EOL . $error_string . PHP_EOL);
    fputs($f, PHP_EOL . print_r($string) . PHP_EOL);
    fclose($f);
}
</code>```

But the stacktrace that i get is not enough clear for me to understand what's wrong. The array is empty and so, i think the problem is not the array, but is in compatibility6. Does anybody know what's the problem with compatibility6? Here's the stacktrace

```<code>new line
#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'field_auto_head...')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'tx_templavoila_...', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1

new line

#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'field_feature_b...')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'tx_templavoila_...', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1

new line

#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'recursive')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'pi_flexform', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1

new line

#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'template')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'pi_flexform', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1
</code>```

Thank you for any response or help.

EDIT:

Here's the php function that create the warning

```<code>public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0)
{

if(is_array($string)){
    $e = new \Exception();
    $error_string = $e->getTraceAsString();
    $f = fopen('/var/www/html/custom.log', 'a+');
    fputs($f, PHP_EOL . "new line" . PHP_EOL);
    fputs($f, PHP_EOL . $error_string . PHP_EOL);
    fputs($f, PHP_EOL . print_r($string) . PHP_EOL);
    fclose($f);
}

    $result = explode($delim, $string);
    if ($removeEmptyValues) {
        $temp = [];
        foreach ($result as $value) {
            if (trim($value) !== '') {
                $temp[] = $value;
            }
        }
        $result = $temp;
    }
    if ($limit > 0 && count($result) > $limit) {
        $lastElements = array_splice($result, $limit - 1);
        $result[] = implode($delim, $lastElements);
    } elseif ($limit < 0) {
        $result = array_slice($result, 0, $limit);
    }
    $result = array_map('trim', $result);
    return $result;
}
</code>```

答: You have to upgrade TYPO3 6.2 to typo3 7.6.x. In TYPO3 7.6 major changes in typo3 defult tables and tables fileds. So, if you don't follow all INSTALL TOOLS Upgrade Wizard steps and compare database specification. Then first follow all this steps.

Body:
I've got errors after update from TYPO3 6.2 to typo3 7.6 with compatibility6 mode enabled.

In the backend, when I need to edit page or article, the content is not charged in the textareas and I've got this warning

PHP Warning
Core: Error handler (BE): PHP Warning: explode() expects parameter 2 to be string, array given in /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Utility/GeneralUtility.php line 1556

To try to debug it, i put a test in the trimExplode function of typo3 like this:

if(is_array($string)){
    $e = new \Exception();
    $error_string = $e->getTraceAsString();
    $f = fopen('/var/www/html/custom.log', 'a+');
    fputs($f, PHP_EOL . "new line" . PHP_EOL);
    fputs($f, PHP_EOL . $error_string . PHP_EOL);
    fputs($f, PHP_EOL . print_r($string) . PHP_EOL);
    fclose($f);
}

But the stacktrace that i get is not enough clear for me to understand what's wrong. The array is empty and so, i think the problem is not the array, but is in compatibility6. Does anybody know what's the problem with compatibility6? Here's the stacktrace

new line
#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'field_auto_head...')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'tx_templavoila_...', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1

new line

#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'field_feature_b...')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'tx_templavoila_...', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1

new line

#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'recursive')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'pi_flexform', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1

new line

#0 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/AbstractItemProvider.php(1142): TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', Array, true)
#1 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataProvider/TcaSelectItems.php(75): TYPO3\CMS\Backend\Form\FormDataProvider\AbstractItemProvider->processDatabaseFieldValue(Array, 'template')
#2 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/FlexFormSegment.php(51): TYPO3\CMS\Backend\Form\FormDataProvider\TcaSelectItems->addData(Array)
#3 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\FlexFormSegment->compile(Array)
#4 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(549): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#5 /var/www/html/typo3conf/ext/compatibility6/Classes/Form/FormDataProvider/TcaFlexProcess.php(54): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->modifyDataStructureAndDataValuesByFlexFormSegmentGroup(Array, 'pi_flexform', Array)
#6 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataGroup/TcaDatabaseRecord.php(51): TYPO3\CMS\Compatibility6\Form\FormDataProvider\TcaFlexProcess->addData(Array)
#7 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Form/FormDataCompiler.php(99): TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord->compile(Array)
#8 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1118): TYPO3\CMS\Backend\Form\FormDataCompiler->compile(Array)
#9 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(1009): TYPO3\CMS\Backend\Controller\EditDocumentController->makeEditForm()
#10 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Controller/EditDocumentController.php(2043): TYPO3\CMS\Backend\Controller\EditDocumentController->main()
#11 [internal function]: TYPO3\CMS\Backend\Controller\EditDocumentController->mainAction(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#12 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RouteDispatcher.php(54): call_user_func_array(Array, Array)
#13 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(168): TYPO3\CMS\Backend\Http\RouteDispatcher->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest), Object(TYPO3\CMS\Core\Http\Response))
#14 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/RequestHandler.php(95): TYPO3\CMS\Backend\Http\RequestHandler->dispatch(Object(TYPO3\CMS\Core\Http\ServerRequest))
#15 /home/typo3/typo3_src-7.6.16/typo3/sysext/core/Classes/Core/Bootstrap.php(302): TYPO3\CMS\Backend\Http\RequestHandler->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#16 /home/typo3/typo3_src-7.6.16/typo3/sysext/backend/Classes/Http/Application.php(94): TYPO3\CMS\Core\Core\Bootstrap->handleRequest(Object(TYPO3\CMS\Core\Http\ServerRequest))
#17 /home/typo3/typo3_src-7.6.16/typo3/index.php(20): TYPO3\CMS\Backend\Http\Application->run()
#18 [internal function]: {closure}()
#19 /home/typo3/typo3_src-7.6.16/typo3/index.php(21): call_user_func(Object(Closure))
#20 {main}

1

Thank you for any response or help.

EDIT:

Here's the php function that create the warning

public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0)
{

if(is_array($string)){
    $e = new \Exception();
    $error_string = $e->getTraceAsString();
    $f = fopen('/var/www/html/custom.log', 'a+');
    fputs($f, PHP_EOL . "new line" . PHP_EOL);
    fputs($f, PHP_EOL . $error_string . PHP_EOL);
    fputs($f, PHP_EOL . print_r($string) . PHP_EOL);
    fclose($f);
}

    $result = explode($delim, $string);
    if ($removeEmptyValues) {
        $temp = [];
        foreach ($result as $value) {
            if (trim($value) !== '') {
                $temp[] = $value;
            }
        }
        $result = $temp;
    }
    if ($limit > 0 && count($result) > $limit) {
        $lastElements = array_splice($result, $limit - 1);
        $result[] = implode($delim, $lastElements);
    } elseif ($limit < 0) {
        $result = array_slice($result, 0, $limit);
    }
    $result = array_map('trim', $result);
    return $result;
}


来源: stackexchange

问:
Selenium WebDriver typing very slow in text field on IE browser
I'm running one of my scripts on IE 11 browser with Selenium 2.43.1
when the script types in text field using following:

```<code>element.sendKeys("string");
</code>```

In IE browser, I can see that one character of string is typed in text field and it waits for 1-2 seconds before typing next character. Means for typing one character it's taking 1-2 seconds.

Why is typing so slow with IE?

Is there any alternate way to speed up typing?

答:
Disable NATIVE_EVENT resolved my issue</p>

```<code> DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
 capabilities.setCapability(InternetExplorerDriver.NATIVE_EVENTS, false);
 driver = new InternetExplorerDriver(capabilities);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm running one of my scripts on IE 11 browser with Selenium 2.43.1
when the script types in text field using following:

element.sendKeys("string");

In IE browser, I can see that one character of string is typed in text field and it waits for 1-2 seconds before typing next character. Means for typing one character it's taking 1-2 seconds.

Why is typing so slow with IE?

Is there any alternate way to speed up typing?

Body:
Disable NATIVE_EVENT resolved my issue

 DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
 capabilities.setCapability(InternetExplorerDriver.NATIVE_EVENTS, false);
 driver = new InternetExplorerDriver(capabilities);


问:
Can't work : $_SESSION['qty'] = '$qty';
I'm making a shopping website and I faced a problem. When I filled in some numbers in quantity column, it will show the number as the end of the column. Is there domething wrong?

```<code><tr align="center">
    <td><input type="checkbox" name="remove[]" value="<?php echo $pro_id;?>" /></td>
    <td><?php echo $product_title; ?><br><img src="admin_area/product_images/<?php echo $product_image; ?>" width='60' height="60"/></td>
    <td><input type="text" size="4" name="qty" value="<?php echo $_SESSION['qty'];?>"/></td>
    <?php
    if(isset($_POST['update_cart'])){
        $qty = $_POST['qty'];
        $update_qty="Update cart set qty='$qty'";
        $run_qty = mysqli_query($con, $update_qty);
        $_SESSION['qty'] = $qty;
    }
    ?>
    <td><?php echo "$".$single_price; ?></td>
</tr>
</code>```

答:
You must start session before accessing any content
Add </p>

```<code>session_start();
</code>```

<p>In the top of your file, under </p>

```<code><?php
</code>```

Title: Can't work : $_SESSION['qty'] = '$qty';

Body:
I'm making a shopping website and I faced a problem. When I filled in some numbers in quantity column, it will show the number as the end of the column. Is there domething wrong?

    <input type="checkbox" name="remove[]" value="<?php echo $pro_id;?>" />
    <?php echo $product_title; ?>
<img src="admin_area/product_images/<?php echo $product_image; ?>" width='60' height="60"/>
    <input type="text" size="4" name="qty" value="<?php echo $_SESSION['qty'];?>"/>
    <?php
    if(isset($_POST['update_cart'])){
        $qty = $_POST['qty'];
        $update_qty="Update cart set qty='$qty'";
        $run_qty = mysqli_query($con, $update_qty);
        $_SESSION['qty'] = $qty;
    }
    ?>
    <?php echo "$".$single_price; ?>

Body:
You must start session before accessing any content
Add

session_start();

In the top of your file, under

<?php


问:
Small native cross-platform GUI framework for C++
I wrote a small program with Boost in c++. It works fine and so I want to give it a graphical interface so that it is easier to use.

In order to do so, I am looking for small cross-platform framework which provides native look and feel. Windows and Linux support would be enough, currently i do not need os x...

I used wxWidgets for some other project, but it was a pain to set everything up and ship this big library with the software.

But I was really amazed by the use of real native controls.
In order to keep the program small I also tried fltk, but it has an awful look.

I just need an simple framework without network support or other gimmicks.

So my question: Is there any framework out there which fits all the requirements? Or if not, which frameworks fits at least some of these needs?

Thanks in advance!

答: If you want it to be small, just write the GUI twice -- once in MFC and then in X.  Your GUI sounds simple enough.  Build up your own small abstraction that is just what you need.</p>

ContentLicense: CC BY-SA 2.5


问:
How to mount azure blob to windows server
I want to mount azure blob storage to my windows server 2012R2 as drive, i have already used cloudberry but we cant afford that one, if another way to mount it.</p>

答:
For now, it is not possible to mount Azure Blob directly, please refer to this feedback.

we want more space, azure files give 500 GB only after mounting

On Azure, Max size of a file share is 5TB not 500Gb. More information about Azure Storage limit please refer to this link.


问:
Platform suggestions for android app without javascript
Is there any cross platform tool apart from xamarin for developing an app,which is not functioning on javascript,</p>

答:
Hope this links  will helps you...

http://thinkapps.com/blog/development/develop-for-ios-v-android-cross-platform-tools/

https://www.business.com/articles/top-5-cross-platform-app-development-tools-in-2016/


问:
Insert into same table avoiding duplicate
```<code>Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------
</code>```

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

```<code>INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

答:
Remove id and set classId and userId as primary.
Then just do a normal insert, if they exist it will not be inserted again.</p>

Body:
Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')


问:
Does retain cycle for a block applies for methods the block call?
Ok, we know that we may have a retain cycle if we do this

```<code>[someObject messageWithBlock:^{ [self doSomething]; }];
</code>```

and that the solution is something like this

```<code>__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];
</code>```

But what about if we do this last code but doSomething has a lot of references to self? Like:

```<code>- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}
</code>```

Will this create a retain cycle?

and what about this:

```<code>__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];
</code>```

Where MY_TABLE is a #define?

答:
No retain cycle in this code:

```<code>__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}
</code>```

Explanation

In the above code

```<code>[weakSelf doSomething];
</code>```

means the receiver object (self) has now become weakSelf ie. any call to self inside doSomething will refer to weakSelf.
Thus reference to self inside doSomething would not create a retain cycle.

Talking about the code below:

```<code>__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];
</code>```

as the receiver object  inside the block is self, and not weakSelf this would create a retain cycle.

Body:
Ok, we know that we may have a retain cycle if we do this

[someObject messageWithBlock:^{ [self doSomething]; }];

and that the solution is something like this

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];

But what about if we do this last code but doSomething has a lot of references to self? Like:

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}

Will this create a retain cycle?

and what about this:

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];

Where MY_TABLE is a #define?

Body:
No retain cycle in this code:

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}

Explanation

In the above code

[weakSelf doSomething];

means the receiver object (self) has now become weakSelf ie. any call to self inside doSomething will refer to weakSelf.
Thus reference to self inside doSomething would not create a retain cycle.

Talking about the code below:

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];

as the receiver object  inside the block is self, and not weakSelf this would create a retain cycle.


问:
Google speech service - not returning transcription
I am using the sample code provided here and have implemented with the following:

```<code># [START import_libraries]
import argparse
import base64
import json
import time
from oauth2client.service_account import ServiceAccountCredentials
import googleapiclient.discovery
import googleapiclient as gac
# [END import_libraries]

# [START authenticating]

# Application default credentials provided by env variable
# GOOGLE_APPLICATION_CREDENTIALS
def get_speech_service(credentials):
    return googleapiclient.discovery.build('speech', 'v1beta1',credentials = credentials)

def main(speech_file):
    """Transcribe the given audio file asynchronously.
    Args:
        speech_file: the name of the audio file.
    """
    # [START construct_request]
    with open(speech_file, 'rb') as speech:
        # Base64 encode the binary audio file for inclusion in the request.
        speech_content = base64.b64encode(speech.read())

#    print speech_content

    scopes = ['https://www.googleapis.com/auth/cloud-platform']

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        '/Users/user/Documents/google_cloud/myjson.json', scopes)

    service = get_speech_service(credentials)
    service_request = service.speech().asyncrecognize(
        body={
            'config': {
                # There are a bunch of config options you can specify. See
                # https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig for the full list.
                'encoding': 'LINEAR16',  # raw 16-bit signed LE samples
                'sampleRate': 16000,  # 16 khz
                # See http://g.co/cloud/speech/docs/languages for a list of
                # supported languages.
                'languageCode': 'en-US',  # a BCP-47 language tag
            },
            'audio': {
                'content': speech_content.decode('UTF-8')
                }
            })
    # [END construct_request]
    # [START send_request]
    response = service_request.execute()
    print(json.dumps(response))
    # [END send_request]

    name = response['name']
    # Construct a GetOperation request.
    service_request = service.operations().get(name=name)

    while True:
        # Give the server a few seconds to process.
        print('Waiting for server processing...')
        time.sleep(1)
        # Get the long running operation with response.
        response = service_request.execute()

        if 'done' in response and response['done']:
            break

    # First print the raw json response
    print(json.dumps(response['response'], indent=2))

    # Now print the actual transcriptions
    out = []
    for result in response['response'].get('results', []):
        print 'poo'
        print('Result:')
        for alternative in result['alternatives']:
            print(u'  Alternative: {}'.format(alternative['transcript']))
        out.append(result)
    return response

r = main("/Users/user/Downloads/brooklyn.flac")
</code>```

Yet my print is the following:

```<code>{"name": "3202776140236290963"}
Waiting for server processing...
Waiting for server processing...
{
  "@type": "type.googleapis.com/google.cloud.speech.v1beta1.AsyncRecognizeResponse"
}
</code>```

And my returned object is:

```<code>{u'done': True,
 u'metadata': {u'@type': u'type.googleapis.com/google.cloud.speech.v1beta1.AsyncRecognizeMetadata',
  u'lastUpdateTime': u'2017-03-25T15:54:46.136925Z',
  u'progressPercent': 100,
  u'startTime': u'2017-03-25T15:54:44.514614Z'},
 u'name': u'2024312474309214820',
 u'response': {u'@type': u'type.googleapis.com/google.cloud.speech.v1beta1.AsyncRecognizeResponse'}}
</code>```

On my console screen I see the requests coming through via:

Unsure why I am not getting the proper transcription back from the sample file.

Any input is appreciated!

答:
Well your config options have the following:

```<code>        'config': {
            # There are a bunch of config options you can specify. See
            # https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig for the full list.
            'encoding': 'LINEAR16',  # raw 16-bit signed LE samples
            'sampleRate': 16000,  # 16 khz
            # See http://g.co/cloud/speech/docs/languages for a list of
            # supported languages.
            'languageCode': 'en-US',  # a BCP-47 language tag
        },
</code>```

However, you are using a FLAC file:

```<code>r = main("/Users/user/Downloads/brooklyn.flac")
</code>```

Quoting https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig:

LINEAR16

Uncompressed 16-bit signed little-endian samples (Linear PCM). This is the only encoding that may be used by speech.asyncrecognize.

FLAC

This is the recommended encoding for speech.syncrecognize and StreamingRecognize because it uses lossless compression; therefore recognition accuracy is not compromised by a lossy codec.

In other words you can't use FLAC with speech.asyncrecognize, you may need to transcode your sample to Linear PCM first, or use speech.syncrecognize with FLAC encoding option.

Body:
I am using the sample code provided here and have implemented with the following:

# [START import_libraries]
import argparse
import base64
import json
import time
from oauth2client.service_account import ServiceAccountCredentials
import googleapiclient.discovery
import googleapiclient as gac
# [END import_libraries]

# [START authenticating]

# Application default credentials provided by env variable
# GOOGLE_APPLICATION_CREDENTIALS
def get_speech_service(credentials):
    return googleapiclient.discovery.build('speech', 'v1beta1',credentials = credentials)

def main(speech_file):
    """Transcribe the given audio file asynchronously.
    Args:
        speech_file: the name of the audio file.
    """
    # [START construct_request]
    with open(speech_file, 'rb') as speech:
        # Base64 encode the binary audio file for inclusion in the request.
        speech_content = base64.b64encode(speech.read())

#    print speech_content

    scopes = ['https://www.googleapis.com/auth/cloud-platform']

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        '/Users/user/Documents/google_cloud/myjson.json', scopes)

    service = get_speech_service(credentials)
    service_request = service.speech().asyncrecognize(
        body={
            'config': {
                # There are a bunch of config options you can specify. See
                # https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig for the full list.
                'encoding': 'LINEAR16',  # raw 16-bit signed LE samples
                'sampleRate': 16000,  # 16 khz
                # See http://g.co/cloud/speech/docs/languages for a list of
                # supported languages.
                'languageCode': 'en-US',  # a BCP-47 language tag
            },
            'audio': {
                'content': speech_content.decode('UTF-8')
                }
            })
    # [END construct_request]
    # [START send_request]
    response = service_request.execute()
    print(json.dumps(response))
    # [END send_request]

    name = response['name']
    # Construct a GetOperation request.
    service_request = service.operations().get(name=name)

    while True:
        # Give the server a few seconds to process.
        print('Waiting for server processing...')
        time.sleep(1)
        # Get the long running operation with response.
        response = service_request.execute()

        if 'done' in response and response['done']:
            break

    # First print the raw json response
    print(json.dumps(response['response'], indent=2))

    # Now print the actual transcriptions
    out = []
    for result in response['response'].get('results', []):
        print 'poo'
        print('Result:')
        for alternative in result['alternatives']:
            print(u'  Alternative: {}'.format(alternative['transcript']))
        out.append(result)
    return response

r = main("/Users/user/Downloads/brooklyn.flac")

Yet my print is the following:

{"name": "3202776140236290963"}
Waiting for server processing...
Waiting for server processing...
{
  "@type": "type.googleapis.com/google.cloud.speech.v1beta1.AsyncRecognizeResponse"
}

And my returned object is:

{u'done': True,
 u'metadata': {u'@type': u'type.googleapis.com/google.cloud.speech.v1beta1.AsyncRecognizeMetadata',
  u'lastUpdateTime': u'2017-03-25T15:54:46.136925Z',
  u'progressPercent': 100,
  u'startTime': u'2017-03-25T15:54:44.514614Z'},
 u'name': u'2024312474309214820',
 u'response': {u'@type': u'type.googleapis.com/google.cloud.speech.v1beta1.AsyncRecognizeResponse'}}

On my console screen I see the requests coming through via:

Unsure why I am not getting the proper transcription back from the sample file.

Any input is appreciated!

Body:
Well your config options have the following:

        'config': {
            # There are a bunch of config options you can specify. See
            # https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig for the full list.
            'encoding': 'LINEAR16',  # raw 16-bit signed LE samples
            'sampleRate': 16000,  # 16 khz
            # See http://g.co/cloud/speech/docs/languages for a list of
            # supported languages.
            'languageCode': 'en-US',  # a BCP-47 language tag
        },

However, you are using a FLAC file:

r = main("/Users/user/Downloads/brooklyn.flac")

Quoting https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig:

LINEAR16

Uncompressed 16-bit signed little-endian samples (Linear PCM). This is the only encoding that may be used by speech.asyncrecognize.

FLAC

This is the recommended encoding for speech.syncrecognize and StreamingRecognize because it uses lossless compression; therefore recognition accuracy is not compromised by a lossy codec.

In other words you can't use FLAC with speech.asyncrecognize, you may need to transcode your sample to Linear PCM first, or use speech.syncrecognize with FLAC encoding option.


问:
What is the difference between a mutable and immutable string in C#?
What is the difference between a mutable and immutable string in C#?</p>

答:
To clarify there is no such thing as a mutable string in C# (or .NET in general).  Other langues support mutable strings (string which can change) but the .NET framework does not.

So the correct answer to your question is ALL string are immutable in C#.

string has a specific meaning. "string" lowercase keyword is merely a shortcut for an object instantiated from System.String class.  All objects created from string class are ALWAYS immutable.

If you want a mutable representation of text then you need to use another class like StringBuilder. StringBuilder allows you to iteratively build a collection of 'words' and then convert that to a string (once again immutable).


问:
[SQL]How to calculate valid VIP no. per month?
I want to  calculate valid VIP no. per month.
There is a VIP table with vip_card_no,create_date,expire_date

The result set should be like that:

```<code>period   |   valid vip number
june2016         20
july2016         18
august2016       30
.....
march2017        40
april2017        30
</code>```

(period is a range selected by user.For example,user selects june2016 to april2017 this time)

Expired vip card should be excluded.
E.g a vip card created on 20170321 and it will expire on april2017 .
It will be counted in march2017 but not counted in april2017

The problems are

1.I don't know how to group by period since the the time range is a variable

2.I tried to write an Accumulated query,but I don't know how to eliminate the expired data.

something like that

```<code>select t1.date, COUNT(t2.vip_card_no) as AccumulateNoOfCases
FROM vip t1
join vip t2 on t2.date <=t1.date
group by t1.date;
</code>```

I have spent a whole on it and I hope anyone could help me!!
A Ton of Thanks!

答:
@Teris, you have not provided any sample data, it's difficult to solve any problem without proper information.

I've tried to solve it, and I've created a Table according to your description. Inserted some sample data. I've considered your description:

Expired vip card should be excluded. E.g a vip card created on 20170321 and it will expire on april2017 . It will be counted in march2017 but not counted in april2017.

I've counted VIP card based on create_date. Please check this:

Sample Data

```<code>Insert Into VIPTable Values('0000','02/15/2017','02/15/2018')
Insert Into VIPTable Values('1111','03/15/2017','03/15/2018')
Insert Into VIPTable Values('2222','03/16/2017','03/16/2018')
Insert Into VIPTable Values('3333','04/15/2017','04/15/2018')
Insert Into VIPTable Values('4444','04/15/2017','04/15/2018')
Insert Into VIPTable Values('5555','04/15/2017','04/15/2018')
Insert Into VIPTable Values('6666','05/15/2017','05/15/2018')
Insert Into VIPTable Values('7777','05/15/2017','05/15/2018')
Insert Into VIPTable Values('8888','06/15/2017','06/15/2018')
Insert Into VIPTable Values('9999','06/15/2017','06/15/2018')
</code>```

SQL

```<code>Declare @periodStart DateTime, @periodEnd DateTime
Set @periodStart = '01/01/2017'
Set @periodEnd = '12/30/2017'

Select
    Convert(Char(4), create_date, 100) + Convert(Char(4), create_date, 120) As Period,
    Count(vip_card_no) As AccumulateNoOfCases
From VIPTable
Where create_date Between @periodStart And @periodEnd
Group By Convert(Char(4), create_date, 100) + Convert(Char(4), create_date, 120)
Order By AccumulateNoOfCases Desc
</code>```

Output

Body:
I want to  calculate valid VIP no. per month.
There is a VIP table with vip_card_no,create_date,expire_date

The result set should be like that:

period   |   valid vip number
june2016         20
july2016         18
august2016       30
.....
march2017        40
april2017        30

(period is a range selected by user.For example,user selects june2016 to april2017 this time)

Expired vip card should be excluded.
E.g a vip card created on 20170321 and it will expire on april2017 .
It will be counted in march2017 but not counted in april2017

The problems are

1.I don't know how to group by period since the the time range is a variable

2.I tried to write an Accumulated query,but I don't know how to eliminate the expired data.

something like that

select t1.date, COUNT(t2.vip_card_no) as AccumulateNoOfCases
FROM vip t1
join vip t2 on t2.date <=t1.date
group by t1.date;

I have spent a whole on it and I hope anyone could help me!!
A Ton of Thanks!

Body:
@Teris, you have not provided any sample data, it's difficult to solve any problem without proper information.

I've tried to solve it, and I've created a Table according to your description. Inserted some sample data. I've considered your description:

Expired vip card should be excluded. E.g a vip card created on 20170321 and it will expire on april2017 . It will be counted in march2017 but not counted in april2017.

I've counted VIP card based on create_date. Please check this:

Sample Data

Insert Into VIPTable Values('0000','02/15/2017','02/15/2018')
Insert Into VIPTable Values('1111','03/15/2017','03/15/2018')
Insert Into VIPTable Values('2222','03/16/2017','03/16/2018')
Insert Into VIPTable Values('3333','04/15/2017','04/15/2018')
Insert Into VIPTable Values('4444','04/15/2017','04/15/2018')
Insert Into VIPTable Values('5555','04/15/2017','04/15/2018')
Insert Into VIPTable Values('6666','05/15/2017','05/15/2018')
Insert Into VIPTable Values('7777','05/15/2017','05/15/2018')
Insert Into VIPTable Values('8888','06/15/2017','06/15/2018')
Insert Into VIPTable Values('9999','06/15/2017','06/15/2018')

SQL

Declare @periodStart DateTime, @periodEnd DateTime
Set @periodStart = '01/01/2017'
Set @periodEnd = '12/30/2017'

Select
    Convert(Char(4), create_date, 100) + Convert(Char(4), create_date, 120) As Period,
    Count(vip_card_no) As AccumulateNoOfCases
From VIPTable
Where create_date Between @periodStart And @periodEnd
Group By Convert(Char(4), create_date, 100) + Convert(Char(4), create_date, 120)
Order By AccumulateNoOfCases Desc

Output


问:
Recursion - digits in reverse order
I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.

This is what I have so far:

```<code>public class PrintDigits {

    public static void main(String[] args) {
        System.out.println("Reverse of no. is " + reversDigits(91));
    }

    /* Recursive function to reverse digits of num */
    public static int reversDigits(int number) {
        if (number == 0)
            return number;
        else {
            return number % 10;
        }
    }
}
</code>```

I feel like there is only one line of code that I am missing, but not sure what I need to do to fix it.

答:
This method reverse the integer and returns the result without using any string functions, Math, or by just printing</p>

```<code>public class ReverseNumber {

    public static void main (String[] args) {
        ReverseNumber rNumber = new ReverseNumber();
        System.out.println(rNumber.reverseRecursive(1234,0)); // pass zero to initialize the reverse number
    }
    public int reverseRecursive(int n, int reverse) {// n - the number to reverse
        // System.out.println(n);

        if (n != 0){
            reverse = reverse * 10;
            reverse = reverse + n %10;
            n = n/10;
        } else {
              return reverse;
        }
    return reverseRecursive(n,reverse);
}}
</code>```

Title: Recursion - digits in reverse order

Body:
I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.

This is what I have so far:

public class PrintDigits {

    public static void main(String[] args) {
        System.out.println("Reverse of no. is " + reversDigits(91));
    }

    /* Recursive function to reverse digits of num */
    public static int reversDigits(int number) {
        if (number == 0)
            return number;
        else {
            return number % 10;
        }
    }
}

I feel like there is only one line of code that I am missing, but not sure what I need to do to fix it.

Body:
This method reverse the integer and returns the result without using any string functions, Math, or by just printing

public class ReverseNumber {

    public static void main (String[] args) {
        ReverseNumber rNumber = new ReverseNumber();
        System.out.println(rNumber.reverseRecursive(1234,0)); // pass zero to initialize the reverse number
    }
    public int reverseRecursive(int n, int reverse) {// n - the number to reverse
        // System.out.println(n);

        if (n != 0){
            reverse = reverse * 10;
            reverse = reverse + n %10;
            n = n/10;
        } else {
              return reverse;
        }
    return reverseRecursive(n,reverse);
}}


问:
Java loop algorithm
Given this:

```<code> public enum States implements StateEnum {
    SHOWING_WELCOME,
    WAITING_FOR_PIN,
    CHECKING_PIN,
    RETURNING_CARD,
    SHOWING_MAIN_MENU,
    SHOWING_PIN_INVALID,
    SHOWING_CARD_LOCKED,
    SHOWING_BALANCE,
    SHOWING_WITHDRAW_MENU,
    SHOWING_TAKE_CASH,
    TERMINATED
}

public enum Events implements EventEnum {
    cardPresent,
    cardExtracted,
    pinProvided,
    pinValid,
    pinInvalid,
    tryAgain,
    noMoreTries,
    cancel,
    confirm,
    menuShowBalance,
    menuWithdrawCash,
    menuExit,
    switchOff,
    cashExtracted
}
</code>```

I would like to know if there is a way to create an algorithm to automatize this:

```<code>from(SHOWING_WELCOME).transit(
    on(cardPresent).to(WAITING_FOR_PIN).transit(
        on(pinProvided).to(CHECKING_PIN).transit(
            on(pinValid).to(SHOWING_MAIN_MENU).transit(
                on(menuShowBalance).to(SHOWING_BALANCE).transit(
                    on(cancel).to(SHOWING_MAIN_MENU)
                ),
                on(menuWithdrawCash).to(SHOWING_WITHDRAW_MENU).transit(
                    on(cancel).to(SHOWING_MAIN_MENU),
                    on(confirm).to(SHOWING_TAKE_CASH).transit(
                        on(cashExtracted).to(SHOWING_MAIN_MENU)
                    )
                ),
                on(menuExit).to(RETURNING_CARD)
            ),
            on(pinInvalid).to(SHOWING_PIN_INVALID).transit(
                on(tryAgain).to(WAITING_FOR_PIN),
                on(noMoreTries).to(SHOWING_CARD_LOCKED).transit(
                    on(confirm).to(SHOWING_WELCOME)
                ),
                on(cancel).to(RETURNING_CARD)
            )
        ),
        on(cancel).to(RETURNING_CARD).transit(
            on(cardExtracted).to(SHOWING_WELCOME)
        )
    ),
    on(switchOff).finish(TERMINATED)
);
</code>```

I was thinking to create two list (Events and States) to use the values in this way:

on(Events.valueOf(EventsList.get(0))).to(States.valueOf(EventsList.get(0)).trans it(

...

But, Im not sure which is the pattern for iterating.

I really appreciate any advise.

Thank you

//////////////////////////// UPDATED///////////////////////////////////

Solution based on the @Dukeling advice

```<code>  public  Map<States, List<Events>> transitMap;
   public Map<Events, States> toMap;

void transitCaller(States initialState, Events events)
  {
  transitCallerHelper(on(events).to(initialState),
  transitMap.get(initialState));
  }

Transition  transitCallerHelper(Transition toResult, List<Events> events)
 {
   List<Transition> transitCalls = new ArrayList<Transition>();
   for (Events e: events)
    {
      States s = toMap.get(e);
      if (isFinishEvent(e)) // or isFinishState(s)
      transitCalls.add(on(e).finish(s));
   else
    {
      events = (s != null ? transitMap.get(s) : null);
      if (events == null)
         transitCalls.add(on(e).to(s));
     else
         transitCalls.add(transitCallerHelper(on(e).to(s), events));
    }
  }
 return toResult.transit(transitCalls.get(0));
</code>```

}

答:
My initial thought would be to have maps to define your transit and to mappings:

```<code>Map<States, List<Events>> transitMap;
Map<Events, States> toMap;
</code>```

You can store these mappings in a text file somewhere from which you can construct the above maps.

From here you can create a recursive method which calls your methods:

(It's a bit messy since from returns a different type)

```<code>void transitCaller(State initialState)
{
   from(initialState).transit(getTransitArgs(transitMap.get(initialState)));
}

Transition transitCallerHelper(Transition toResult, List<Events> events)
{
   return toResult.transit(getTransitArgs(events));
}

Transition[] getTransitArgs(List<Events> events)
{
   List<Transition> transitArgs = new ArrayList<Transition>();
   for (Events e: events)
   {
      States s = toMap.get(e);
      if (isFinishEvent(e)) // or isFinishState(s)
         transitArgs.add(on(e).finish(s));
      else
      {
         List<Events> events = (s != null ? transitMap.get(s) : null);
         if (events == null)
            transitArgs.add(on(e).to(s));
         else
            transitArgs.add(transitCallerHelper(on(e).to(s), events));
      }
   }
   return transitArgs.toArray(new Transaction[0]);
}
</code>```

(Add error checking as appropriate)

Side note: You may want to make States and Events singular as opposed to plural, since each value in the enum only defines a single state and event respectively.

Title: Java loop algorithm

Body:
Given this:

 public enum States implements StateEnum {
    SHOWING_WELCOME,
    WAITING_FOR_PIN,
    CHECKING_PIN,
    RETURNING_CARD,
    SHOWING_MAIN_MENU,
    SHOWING_PIN_INVALID,
    SHOWING_CARD_LOCKED,
    SHOWING_BALANCE,
    SHOWING_WITHDRAW_MENU,
    SHOWING_TAKE_CASH,
    TERMINATED
}

public enum Events implements EventEnum {
    cardPresent,
    cardExtracted,
    pinProvided,
    pinValid,
    pinInvalid,
    tryAgain,
    noMoreTries,
    cancel,
    confirm,
    menuShowBalance,
    menuWithdrawCash,
    menuExit,
    switchOff,
    cashExtracted
}

I would like to know if there is a way to create an algorithm to automatize this:

from(SHOWING_WELCOME).transit(
    on(cardPresent).to(WAITING_FOR_PIN).transit(
        on(pinProvided).to(CHECKING_PIN).transit(
            on(pinValid).to(SHOWING_MAIN_MENU).transit(
                on(menuShowBalance).to(SHOWING_BALANCE).transit(
                    on(cancel).to(SHOWING_MAIN_MENU)
                ),
                on(menuWithdrawCash).to(SHOWING_WITHDRAW_MENU).transit(
                    on(cancel).to(SHOWING_MAIN_MENU),
                    on(confirm).to(SHOWING_TAKE_CASH).transit(
                        on(cashExtracted).to(SHOWING_MAIN_MENU)
                    )
                ),
                on(menuExit).to(RETURNING_CARD)
            ),
            on(pinInvalid).to(SHOWING_PIN_INVALID).transit(
                on(tryAgain).to(WAITING_FOR_PIN),
                on(noMoreTries).to(SHOWING_CARD_LOCKED).transit(
                    on(confirm).to(SHOWING_WELCOME)
                ),
                on(cancel).to(RETURNING_CARD)
            )
        ),
        on(cancel).to(RETURNING_CARD).transit(
            on(cardExtracted).to(SHOWING_WELCOME)
        )
    ),
    on(switchOff).finish(TERMINATED)
);

I was thinking to create two list (Events and States) to use the values in this way:

on(Events.valueOf(EventsList.get(0))).to(States.valueOf(EventsList.get(0)).trans it(

...

But, Im not sure which is the pattern for iterating.

I really appreciate any advise.

Thank you

//////////////////////////// UPDATED///////////////////////////////////

Solution based on the @Dukeling advice

  public  Map<States, List<Events>> transitMap;
   public Map<Events, States> toMap;

void transitCaller(States initialState, Events events)
  {
  transitCallerHelper(on(events).to(initialState),
  transitMap.get(initialState));
  }

Transition  transitCallerHelper(Transition toResult, List<Events> events)
 {
   List<Transition> transitCalls = new ArrayList<Transition>();
   for (Events e: events)
    {
      States s = toMap.get(e);
      if (isFinishEvent(e)) // or isFinishState(s)
      transitCalls.add(on(e).finish(s));
   else
    {
      events = (s != null ? transitMap.get(s) : null);
      if (events == null)
         transitCalls.add(on(e).to(s));
     else
         transitCalls.add(transitCallerHelper(on(e).to(s), events));
    }
  }
 return toResult.transit(transitCalls.get(0));

}

Body:
My initial thought would be to have maps to define your transit and to mappings:

Map<States, List<Events>> transitMap;
Map<Events, States> toMap;

You can store these mappings in a text file somewhere from which you can construct the above maps.

From here you can create a recursive method which calls your methods:

(It's a bit messy since from returns a different type)

void transitCaller(State initialState)
{
   from(initialState).transit(getTransitArgs(transitMap.get(initialState)));
}

Transition transitCallerHelper(Transition toResult, List<Events> events)
{
   return toResult.transit(getTransitArgs(events));
}

Transition[] getTransitArgs(List<Events> events)
{
   List<Transition> transitArgs = new ArrayList<Transition>();
   for (Events e: events)
   {
      States s = toMap.get(e);
      if (isFinishEvent(e)) // or isFinishState(s)
         transitArgs.add(on(e).finish(s));
      else
      {
         List<Events> events = (s != null ? transitMap.get(s) : null);
         if (events == null)
            transitArgs.add(on(e).to(s));
         else
            transitArgs.add(transitCallerHelper(on(e).to(s), events));
      }
   }
   return transitArgs.toArray(new Transaction[0]);
}

(Add error checking as appropriate)

Side note: You may want to make States and Events singular as opposed to plural, since each value in the enum only defines a single state and event respectively.


问:
PHP: Find last occurence of string in array
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

```<code>$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
</code>```

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

答:
Here is the more simple and highly performace way. For it only calculate once, you can access it many time. The live demo.

```<code>$data = array_flip($Data);
echo $data['bike'];
</code>```

after the flip, only keep the last element of the same elements. Here is the print_r($data)

```<code>Array
(
    [car] => 0
    [bike] => 3
    [bus] => 2
    [boat] => 4
)
</code>```

Body:
I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.

$Data = array(
    '0' => 'car',
    '1' => 'bike',
    '2' => 'bus',
    '3' => 'bike',
    '4' => 'boat'
 );

$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.

I want $key = 3 which is the last matched element.

Any suggestion appreciated.

Body:
Here is the more simple and highly performace way. For it only calculate once, you can access it many time. The live demo.

$data = array_flip($Data);
echo $data['bike'];

after the flip, only keep the last element of the same elements. Here is the print_r($data)

Array
(
    [car] => 0
    [bike] => 3
    [bus] => 2
    [boat] => 4
)


问:
Why -1 >> 1 is -1 ? And 1 >> 1 is 0!
I have next code:

```<code>std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;
</code>```

The result is:

```<code>-5
-5
-4
-4
-3
-3
-2
-2
-1
-1
</code>```

But why?

-1 is 1111 1111 (for 1 byte), -1 >> 1 must be : 1011 1111 and it is not -1 or 0! (sign-bit is not shifted, I know)

Can someone explain to me how this works?

答:
Standard 5.8/3 (Shift operators) :

The value of E1 >> E2 is E1
  right-shifted E2 bit positions. If E1
  has an unsigned type or if E1 has a
  signed type and a nonnegative value,
  the value of the result is the
  integral part of the quotient of E1
  divided by the quantity 2 raised to
  the power E2. If E1 has a signed type
  and a negative value, the resulting
  value is implementation-defined.

So to the question "why ?", the standard answer is : why not.

Title: Why -1 >> 1 is -1 ? And 1 >> 1 is 0!

Body:
I have next code:

std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;

The result is:

-5
-5
-4
-4
-3
-3
-2
-2
-1
-1

But why?

-1 is 1111 1111 (for 1 byte), -1 >> 1 must be : 1011 1111 and it is not -1 or 0! (sign-bit is not shifted, I know)

Can someone explain to me how this works?


问:
TypeScript Errors in a Javascript Project that has no TypeScript files
I'm not exactly sure what's going on here but I have a node.js project (type: javascript) with no ts files in it (go figure) that is throwing 3 typescript errors:

```<code>Error   TS2304  Cannot find name 'object'.
Error   TS2428  All declarations of 'WeakMap' must have identical type parameters.
Error   TS2304  Cannot find name 'object'.
</code>```

All 3 of these are in relation to lodash. I'm not quite sure enough about what I'm doing here to even know what to actually search for but I've stumbled across some fixes referencing a tsconfig file or rolling back the lodash version but most of those are old. On top of that, I'm not sure why I would even need that since I'm doing exactly nothing with typescript...

Anyone have any ideas?

答:
I had the same problem begin working on an existing vanilla Javascript project which uses JQuery version 2.1.4, I want to use latest version of JQuery, Typescript and Webpack in this project but if kept failing when I tried to import some Typescript code into a plain Javascript file. And in this js file, the previous developer added a class called Map to the window object

```<code>$(function () {
    window.Map = function ()...;
});
</code>```

Which conflicts with es6 Map native object, and I kept getting incorrect parameters passes type of error, I then removed the latest jquery version I tried to use, and continue using the same jquery version the developer used initially, and it works again. I still have no idea why using the latest jquery version caused the error.

Not sure if it was helpful

Body:
I'm not exactly sure what's going on here but I have a node.js project (type: javascript) with no ts files in it (go figure) that is throwing 3 typescript errors:

Error   TS2304  Cannot find name 'object'.
Error   TS2428  All declarations of 'WeakMap' must have identical type parameters.
Error   TS2304  Cannot find name 'object'.

All 3 of these are in relation to lodash. I'm not quite sure enough about what I'm doing here to even know what to actually search for but I've stumbled across some fixes referencing a tsconfig file or rolling back the lodash version but most of those are old. On top of that, I'm not sure why I would even need that since I'm doing exactly nothing with typescript...

Anyone have any ideas?

Body:
I had the same problem begin working on an existing vanilla Javascript project which uses JQuery version 2.1.4, I want to use latest version of JQuery, Typescript and Webpack in this project but if kept failing when I tried to import some Typescript code into a plain Javascript file. And in this js file, the previous developer added a class called Map to the window object

$(function () {
    window.Map = function ()...;
});

Which conflicts with es6 Map native object, and I kept getting incorrect parameters passes type of error, I then removed the latest jquery version I tried to use, and continue using the same jquery version the developer used initially, and it works again. I still have no idea why using the latest jquery version caused the error.

Not sure if it was helpful


问:
What is the difference between eof(), fail(), bad(), and good() in C++ streams?
I am currently learning C++ from the C++ Primer 5th edition. I am confused about the behavior of the methods to check the status of a stream due to seemingly conflicting information. On page 312 it states

If any of badbit, failbit, or eofbit are set, then a condition
  that evaluates that stream will fail.

On the very next page, it says that s.fail() is

true if failbit or badbit in the stream is set

and that

the code that is executed when we use a stream as a condition is
  equivalent to calling !fail().

This doesn't make sense because any expression that uses fail() should only know about failbit and badbit (since those are what make up fail()'s value) and yet !fail() is equivalent to all three of badbit, failbit, and eofbit being false.

How do these seemingly contradictory statements fit together?

答:
The second and third statements are correct and in agreement with the C++ standard. The first one, then, is simply a mistake. Neither fail nor operator bool nor operator ! take into account the eofbit state of a stream. Only good and eof do.

In the usual course of events, trying to read past the end of the stream sets both the eofbit and failbit, which is one likely reason why this mistake was so easy to make.


答:
```<code><?php
//allows you to start a session
session_start();
</code>```

when you want to end the session

```<code>session_destroy();
</code>```

Title: Can't work : $_SESSION['qty'] = '$qty';

Body:
I'm making a shopping website and I faced a problem. When I filled in some numbers in quantity column, it will show the number as the end of the column. Is there domething wrong?

    <input type="checkbox" name="remove[]" value="<?php echo $pro_id;?>" />
    <?php echo $product_title; ?>
<img src="admin_area/product_images/<?php echo $product_image; ?>" width='60' height="60"/>
    <input type="text" size="4" name="qty" value="<?php echo $_SESSION['qty'];?>"/>
    <?php
    if(isset($_POST['update_cart'])){
        $qty = $_POST['qty'];
        $update_qty="Update cart set qty='$qty'";
        $run_qty = mysqli_query($con, $update_qty);
        $_SESSION['qty'] = $qty;
    }
    ?>
    <?php echo "$".$single_price; ?>

Body:
<?php
//allows you to start a session
session_start();

when you want to end the session

session_destroy();


问:
Are my subclasses causing memory leaks?
I'm subclassing UINavigationController and UITableview and for some reason, my views are leaking memory, although I've implemented all of the proper methods and release calls. When I use the native class instead of a subclass, everything works just fine, without leaking.

EDIT:

Here's my superclass header:

```<code>//
//  MBAbstractViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MBAbstractViewController : UIViewController {
    IBOutlet UIImageView *backgroundImageView;
    NSString *announcementText;
}

@property (nonatomic, retain) NSString *type;
@property (nonatomic, retain) NSDictionary *options;
@property (nonatomic, retain) NSString *announcementText;

-(void) setAnnouncementText:(NSString *)text;

@end
</code>```

Superclass implementation:

```<code>//
//  MBAbstractViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAbstractViewController.h"

@implementation MBAbstractViewController

@synthesize type, options, announcementText;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *clearColor = [[UIColor alloc] colorWithAlphaComponent:0.0];
    [self.view setBackgroundColor: clearColor];
    [clearColor release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||  interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }else{
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}

- (void)dealloc {
    [announcementText release];
    [options release];
    [type release];
    [super dealloc];
}

@end
</code>```

Here's my subclass header:

```<code>//
//  MBAnnouncementViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MBAbstractViewController.h"

@interface MBAnnouncementViewController : MBAbstractViewController {
    IBOutlet UILabel *announcement;
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size;

@end
</code>```

and the subclass implementation:

```<code>        //
//  MBAnnouncementViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAnnouncementViewController.h"
#import "Constants.h"[

@implementation MBAnnouncementViewController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [announcement setText:announcementText];

    UIImage *slideImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_slide", kTheme]description] ofType:@"png"]];
    [backgroundImageView setImage:slideImage];
    [slideImage release];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size{
    UIFont *font = [[UIFont alloc] fontWithSize:size];
    [announcement setFont:font];
    [font release];
    [announcement setText:text];

}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [announcementText release];
    [super dealloc];
}

@end
</code>```

What could be causing memory leaks in a subclass? Am I missing something? (There is more relevant code here.)

答: What does 'announcement' represent in your second class?  Is it an IBOutlet(I do not see a synthesize for it)?  If it is a property or IBOutlet you will want to make sure to release it in your dealloc.</p>

Title: Are my subclasses causing memory leaks?

Body:
I'm subclassing UINavigationController and UITableview and for some reason, my views are leaking memory, although I've implemented all of the proper methods and release calls. When I use the native class instead of a subclass, everything works just fine, without leaking.

EDIT:

Here's my superclass header:

//
//  MBAbstractViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MBAbstractViewController : UIViewController {
    IBOutlet UIImageView *backgroundImageView;
    NSString *announcementText;
}

@property (nonatomic, retain) NSString *type;
@property (nonatomic, retain) NSDictionary *options;
@property (nonatomic, retain) NSString *announcementText;

-(void) setAnnouncementText:(NSString *)text;

@end

Superclass implementation:

//
//  MBAbstractViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAbstractViewController.h"

@implementation MBAbstractViewController

@synthesize type, options, announcementText;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *clearColor = [[UIColor alloc] colorWithAlphaComponent:0.0];
    [self.view setBackgroundColor: clearColor];
    [clearColor release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||  interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }else{
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}

- (void)dealloc {
    [announcementText release];
    [options release];
    [type release];
    [super dealloc];
}

@end

Here's my subclass header:

//
//  MBAnnouncementViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MBAbstractViewController.h"

@interface MBAnnouncementViewController : MBAbstractViewController {
    IBOutlet UILabel *announcement;
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size;

@end

and the subclass implementation:

        //
//  MBAnnouncementViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAnnouncementViewController.h"
#import "Constants.h"[

@implementation MBAnnouncementViewController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [announcement setText:announcementText];

    UIImage *slideImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_slide", kTheme]description] ofType:@"png"]];
    [backgroundImageView setImage:slideImage];
    [slideImage release];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size{
    UIFont *font = [[UIFont alloc] fontWithSize:size];
    [announcement setFont:font];
    [font release];
    [announcement setText:text];

}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [announcementText release];
    [super dealloc];
}

@end

What could be causing memory leaks in a subclass? Am I missing something? (There is more relevant code here.)


问:
React JS pass state altering function to child
I am currently working on a react js project for one of my classes and cannot seem to figure out where I am going wrong. I cannot post any code for this, and I understand that this may make it fairly hard to answer this question, but here is my problem.

I have a parent function, which has a state that decides between 3 different possible components to render as the page depending on the state variable 'currentPage'. In this parent component, I have made functions that will alter the currentPage state variable. I am trying to pass these state altering functions through props and then call them inside of the children components to change the state of the parent and re-render the page. For example, I have a function called signup which changes the currentPage to 'signup', so I have <Login goToSignup = {this.signup} />. Then, inside of my Login component, I try to set the on click of a button to: onClick = {this.props.goToSignup}. But this doesn't seem to work. I am very new to react and am maybe misunderstanding how I am supposed to do this, so any help would be much appreciated.

答:
In this example, there are 3 components Detail, Post, XYZ and a parent component App. On the basis of state value in parent, rendering the different component. In all the 3 component passing a function that is used to change the currentPage state value in parent component.

For Stateless Functional Component, check the DOC.

Check this example:

var Post = (props) => {
    return
props.changeComponent('detail')}> POST

}
var Detail = (props) => {
    return
props.changeComponent('xyz')}> DETAIL

}
var XYZ = (props) => {
    return
props.changeComponent('post')}> XYZ

}

class App extends React.Component{

   constructor(){
      super();
      this.state = {currentPage: 'post'}
      this.changeComponent = this.changeComponent.bind(this)
   }

   changeComponent(currentPage){
      this.setState({currentPage});
   }

   renderTab(){
      switch(this.state.currentPage){
         case 'post': return <Post changeComponent={this.changeComponent}/>
         case 'detail': return <Detail changeComponent={this.changeComponent}/>
         case 'xyz': return <XYZ changeComponent={this.changeComponent}/>
      }
   }

   render(){
      return(

            {this.renderTab()}

*Click on Page name to render different page

      )
   }
}

ReactDOM.render(
    <App/>,
    document.getElementById('app')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'></code>```

Update (OP asked for same example in es5)

Same example written in ES5 (don't know much about es5, correct me if i did some mistake):

function Post(props) {
    return
props.changeComponent('detail')}> POST

}
function Detail(props){
    return
props.changeComponent('xyz')}> DETAIL

}
function XYZ(props){
    return
props.changeComponent('post')}> XYZ

}

var App = React.createClass({

   getInitialState: function(){
      return (
          {currentPage: 'post'}
      )
   },

   changeComponent: function(currentPage){
      this.setState({currentPage});
   },

   renderTab: function(){
      switch(this.state.currentPage){
         case 'post': return <Post changeComponent={this.changeComponent}/>
         case 'detail': return <Detail changeComponent={this.changeComponent}/>
         case 'xyz': return <XYZ changeComponent={this.changeComponent}/>
      }
   },

   render: function(){
      return(

            {this.renderTab()}

*Click on Page name to render different page

      )
   }
})

ReactDOM.render(
    <App/>,
    document.getElementById('app')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'></code>```

Body:
In this example, there are 3 components Detail, Post, XYZ and a parent component App. On the basis of state value in parent, rendering the different component. In all the 3 component passing a function that is used to change the currentPage state value in parent component.

For Stateless Functional Component, check the DOC.

Check this example:

var Post = (props) => {
    return <div onClick={()=>props.changeComponent('detail')}> POST </div>
}
var Detail = (props) => {
    return <div onClick={()=>props.changeComponent('xyz')}> DETAIL </div>
}
var XYZ = (props) => {
    return <div onClick={()=>props.changeComponent('post')}> XYZ </div>
}

class App extends React.Component{

   constructor(){
      super();
      this.state = {currentPage: 'post'}
      this.changeComponent = this.changeComponent.bind(this)
   }

   changeComponent(currentPage){
      this.setState({currentPage});
   }

   renderTab(){
      switch(this.state.currentPage){
         case 'post': return <Post changeComponent={this.changeComponent}/>
         case 'detail': return <Detail changeComponent={this.changeComponent}/>
         case 'xyz': return <XYZ changeComponent={this.changeComponent}/>
      }
   }

   render(){
      return(
         <div>
            {this.renderTab()}
            <div style={{marginTop: 100}}>*Click on Page name to render different page</div>
         </div>
      )
   }
}

ReactDOM.render(
    <App/>,
    document.getElementById('app')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'>

Update (OP asked for same example in es5)

Same example written in ES5 (don't know much about es5, correct me if i did some mistake):

function Post(props) {
    return <div onClick={()=>props.changeComponent('detail')}> POST </div>
}
function Detail(props){
    return <div onClick={()=>props.changeComponent('xyz')}> DETAIL </div>
}
function XYZ(props){
    return <div onClick={()=>props.changeComponent('post')}> XYZ </div>
}

var App = React.createClass({

   getInitialState: function(){
      return (
          {currentPage: 'post'}
      )
   },

   changeComponent: function(currentPage){
      this.setState({currentPage});
   },

   renderTab: function(){
      switch(this.state.currentPage){
         case 'post': return <Post changeComponent={this.changeComponent}/>
         case 'detail': return <Detail changeComponent={this.changeComponent}/>
         case 'xyz': return <XYZ changeComponent={this.changeComponent}/>
      }
   },

   render: function(){
      return(
         <div>
            {this.renderTab()}
            <div style={{marginTop: 100}}>*Click on Page name to render different page</div>
         </div>
      )
   }
})

ReactDOM.render(
    <App/>,
    document.getElementById('app')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'>