qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
277,224 |
<p>I can use <code>set_error_handler()</code> to catch most PHP errors, but it doesn't work for fatal (<code>E_ERROR</code>) errors, such as calling a function that doesn't exist. Is there another way to catch these errors?</p>
<p>I am trying to call <code>mail()</code> for all errors and am running PHP 5.2.3.</p>
|
[
{
"answer_id": 277387,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": false,
"text": "<p>Not really. Fatal errors are called that, because they are fatal. You can't recover from them.</p>\n"
},
{
"answer_id": 277443,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 7,
"selected": false,
"text": "<p>PHP doesn't provide conventional means for catching and recovering from fatal errors. This is because processing should not typically be recovered after a fatal error. String matching an output buffer (as suggested by the original post the technique described on PHP.net) is definitely ill-advised. It's simply unreliable.</p>\n\n<p>Calling the mail() function from within an error handler method prove to be problematic, too. If you had a lot of errors, your mail server would be loaded with work, and you could find yourself with a gnarly inbox. To avoid this, you might consider running a cron to scan error logs periodically and send notifications accordingly. You might also like to look into system monitoring software, such as <a href=\"http://www.nagios.org/\" rel=\"noreferrer\">Nagios</a>.</p>\n\n<hr>\n\n<p>To speak to the bit about registering a shutdown function:</p>\n\n<p>It's true that you can register a shutdown function, and that's a good answer.</p>\n\n<p>The point here is that we typically shouldn't try to recover from fatal errors, especially not by using a regular expression against your output buffer. I was responding to the <a href=\"https://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-error/277230#277230\">accepted answer</a>, which linked to a suggestion on php.net which has since been changed or removed.</p>\n\n<p>That suggestion was to use a regex against the output buffer during exception handling, and in the case of a fatal error (detected by the matching against whatever configured error text you might be expecting), try to do some sort of recovery or continued processing. That would not be a recommended practice (I believe that's why I can't find the original suggestion, too. I'm either overlooking it, or the php community shot it down).</p>\n\n<p>It might be worth noting that the more recent versions of PHP (around 5.1) seem to call the shutdown function earlier, before the output buffering callback is envoked. In version 5 and earlier, that order was the reverse (the output buffering callback was followed by the shutdown function). Also, since about 5.0.5 (which is much earlier than the questioner's version 5.2.3), objects are unloaded well before a registered shutdown function is called, so you won't be able to rely on your in-memory objects to do much of anything.</p>\n\n<p>So registering a shutdown function is fine, but the sort of tasks that ought to be performed by a shutdown function are probably limited to a handful of gentle shutdown procedures.</p>\n\n<p>The key take-away here is just some words of wisdom for anyone who stumbles upon this question and sees the advice in the originally accepted answer. Don't regex your output buffer.</p>\n"
},
{
"answer_id": 2146171,
"author": "user259973",
"author_id": 259973,
"author_profile": "https://Stackoverflow.com/users/259973",
"pm_score": 9,
"selected": false,
"text": "<p>Log fatal errors using the <code>register_shutdown_function</code>, which requires PHP 5.2+:</p>\n\n<pre><code>register_shutdown_function( \"fatal_handler\" );\n\nfunction fatal_handler() {\n $errfile = \"unknown file\";\n $errstr = \"shutdown\";\n $errno = E_CORE_ERROR;\n $errline = 0;\n\n $error = error_get_last();\n\n if($error !== NULL) {\n $errno = $error[\"type\"];\n $errfile = $error[\"file\"];\n $errline = $error[\"line\"];\n $errstr = $error[\"message\"];\n\n error_mail(format_error( $errno, $errstr, $errfile, $errline));\n }\n}\n</code></pre>\n\n<p>You will have to define the <code>error_mail</code> and <code>format_error</code> functions. For example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function format_error( $errno, $errstr, $errfile, $errline ) {\n $trace = print_r( debug_backtrace( false ), true );\n\n $content = \"\n <table>\n <thead><th>Item</th><th>Description</th></thead>\n <tbody>\n <tr>\n <th>Error</th>\n <td><pre>$errstr</pre></td>\n </tr>\n <tr>\n <th>Errno</th>\n <td><pre>$errno</pre></td>\n </tr>\n <tr>\n <th>File</th>\n <td>$errfile</td>\n </tr>\n <tr>\n <th>Line</th>\n <td>$errline</td>\n </tr>\n <tr>\n <th>Trace</th>\n <td><pre>$trace</pre></td>\n </tr>\n </tbody>\n </table>\";\n return $content;\n}\n</code></pre>\n\n<p>Use <a href=\"http://swiftmailer.org/\" rel=\"noreferrer\">Swift Mailer</a> to write the <code>error_mail</code> function.</p>\n\n<p>See also:</p>\n\n<ul>\n<li><em><a href=\"http://php.net/manual/en/reserved.variables.phperrormsg.php\" rel=\"noreferrer\">$php_errormsg</a></em></li>\n<li><em><a href=\"http://php.net/manual/en/errorfunc.constants.php\" rel=\"noreferrer\">Predefined Constants</a></em></li>\n</ul>\n"
},
{
"answer_id": 3389021,
"author": "periklis",
"author_id": 408773,
"author_profile": "https://Stackoverflow.com/users/408773",
"pm_score": 7,
"selected": false,
"text": "<p>I just came up with this solution (PHP 5.2.0+):</p>\n\n<pre><code>function shutDownFunction() {\n $error = error_get_last();\n // Fatal error, E_ERROR === 1\n if ($error['type'] === E_ERROR) {\n // Do your stuff\n }\n}\nregister_shutdown_function('shutDownFunction');\n</code></pre>\n\n<p>Different error types are defined at <em><a href=\"http://www.php.net/manual/en/errorfunc.constants.php\" rel=\"noreferrer\">Predefined Constants</a></em>.</p>\n"
},
{
"answer_id": 3795403,
"author": "hipertracker",
"author_id": 247200,
"author_profile": "https://Stackoverflow.com/users/247200",
"pm_score": 4,
"selected": false,
"text": "<p>You cannot throw an exception inside a registered shutdown function like that:</p>\n\n<pre><code><?php\n function shutdown() {\n if (($error = error_get_last())) {\n ob_clean();\n throw new Exception(\"fatal error\");\n }\n }\n\n try {\n $x = null;\n $x->method()\n } catch(Exception $e) {\n # This won't work\n }\n?>\n</code></pre>\n\n<p>But you can capture and redirect request to another page.</p>\n\n<pre><code><?php\n function shutdown() {\n if (($error = error_get_last())) {\n ob_clean();\n # Report the event, send email, etc.\n header(\"Location: http://localhost/error-capture\");\n # From /error-capture. You can use another\n # redirect, to e.g. the home page\n }\n }\n register_shutdown_function('shutdown');\n\n $x = null;\n $x->method()\n?>\n</code></pre>\n"
},
{
"answer_id": 5192011,
"author": "sakhunzai",
"author_id": 416100,
"author_profile": "https://Stackoverflow.com/users/416100",
"pm_score": 5,
"selected": false,
"text": "<p>Well, it seems possible to catch fatal errors some other way :)</p>\n\n<pre><code>ob_start('fatal_error_handler');\n\nfunction fatal_error_handler($buffer){\n $error = error_get_last();\n if($error['type'] == 1){\n // Type, message, file, line\n $newBuffer='<html><header><title>Fatal Error </title></header>\n <style>\n .error_content{\n background: ghostwhite;\n vertical-align: middle;\n margin:0 auto;\n padding: 10px;\n width: 50%;\n }\n .error_content label{color: red;font-family: Georgia;font-size: 16pt;font-style: italic;}\n .error_content ul li{ background: none repeat scroll 0 0 FloralWhite;\n border: 1px solid AliceBlue;\n display: block;\n font-family: monospace;\n padding: 2%;\n text-align: left;\n }\n </style>\n <body style=\"text-align: center;\">\n <div class=\"error_content\">\n <label >Fatal Error </label>\n <ul>\n <li><b>Line</b> ' . $error['line'] . '</li>\n <li><b>Message</b> ' . $error['message'] . '</li>\n <li><b>File</b> ' . $error['file'] . '</li>\n </ul>\n\n <a href=\"javascript:history.back()\"> Back </a>\n </div>\n </body></html>';\n\n return $newBuffer;\n }\n return $buffer;\n}\n</code></pre>\n"
},
{
"answer_id": 7827720,
"author": "Prof",
"author_id": 629157,
"author_profile": "https://Stackoverflow.com/users/629157",
"pm_score": 3,
"selected": false,
"text": "<p>I need to handle fatal errors for production to instead show a static styled <em>503 Service Unavailable</em> HTML output. This is surely a reasonable approach to \"catching fatal errors\". This is what I've done:</p>\n\n<p>I have a custom error handling function \"error_handler\" which will display my \"503 service unavailable\" HTML page on any E_ERROR, E_USER_ERROR, etc. This will now be called on the shutdown function, catching my fatal error,</p>\n\n<pre><code>function fatal_error_handler() {\n\n if (@is_array($e = @error_get_last())) {\n $code = isset($e['type']) ? $e['type'] : 0;\n $msg = isset($e['message']) ? $e['message'] : '';\n $file = isset($e['file']) ? $e['file'] : '';\n $line = isset($e['line']) ? $e['line'] : '';\n if ($code>0)\n error_handler($code, $msg, $file, $line);\n }\n}\nset_error_handler(\"error_handler\");\nregister_shutdown_function('fatal_error_handler');\n</code></pre>\n\n<p>in my custom error_handler function, if the error is E_ERROR, E_USER_ERROR, etc. I also call <code>@ob_end_clean();</code> to empty the buffer, thus removing PHP's \"fatal error\" message.</p>\n\n<p>Take important note of the strict isset() checking and <code>@</code> silencing functions since we don’t want our error_handler scripts to generate any errors.</p>\n\n<p>In still agreeing with keparo, catching fatal errors does defeat the purpose of \"FATAL error\" so it's not really intended for you to do further processing. Do not run any mail() functions in this shutdown process as you will certainly back up the mail server or your inbox. Rather log these occurrences to file and schedule a <a href=\"https://en.wikipedia.org/wiki/Cron\" rel=\"nofollow noreferrer\">cron</a> job to find these <em>error.log</em> files and mail them to administrators.</p>\n"
},
{
"answer_id": 8057591,
"author": "Kendall Hopkins",
"author_id": 188044,
"author_profile": "https://Stackoverflow.com/users/188044",
"pm_score": 2,
"selected": false,
"text": "<p>I developed this function to make it possible to \"sandbox\" code that could cause a fatal error. Since exceptions thrown from the closure <code>register_shutdown_function</code> don't get emitted from the pre-fatal error call stack, I'm forced to exit after this function to provide a uniform way of using it.</p>\n\n<pre><code>function superTryCatchFinallyAndExit( Closure $try, Closure $catch = NULL, Closure $finally )\n{\n $finished = FALSE;\n register_shutdown_function( function() use ( &$finished, $catch, $finally ) {\n if( ! $finished ) {\n $finished = TRUE;\n print \"EXPLODE!\".PHP_EOL;\n if( $catch ) {\n superTryCatchFinallyAndExit( function() use ( $catch ) {\n $catch( new Exception( \"Fatal Error!!!\" ) );\n }, NULL, $finally ); \n } else {\n $finally(); \n }\n }\n } );\n try {\n $try();\n } catch( Exception $e ) {\n if( $catch ) {\n try {\n $catch( $e );\n } catch( Exception $e ) {}\n }\n }\n $finished = TRUE;\n $finally();\n exit();\n}\n</code></pre>\n"
},
{
"answer_id": 10423163,
"author": "None",
"author_id": 1038726,
"author_profile": "https://Stackoverflow.com/users/1038726",
"pm_score": 3,
"selected": false,
"text": "<p>PHP has catchable fatal errors. They are defined as E_RECOVERABLE_ERROR. The PHP manual describes an E_RECOVERABLE_ERROR as:</p>\n\n<blockquote>\n <p>Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also <a href=\"http://www.php.net/manual/en/function.set-error-handler.php\" rel=\"nofollow noreferrer\">set_error_handler()</a>), the application aborts as it was an E_ERROR.</p>\n</blockquote>\n\n<p>You can \"catch\" these \"fatal\" errors by using <a href=\"http://www.php.net/manual/en/function.set-error-handler.php\" rel=\"nofollow noreferrer\">set_error_handler()</a> and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.</p>\n\n<p>This question and answer provides a useful example: <a href=\"https://stackoverflow.com/questions/2468487/how-can-i-catch-a-catchable-fatal-error-on-php-type-hinting\">How can I catch a "catchable fatal error" on PHP type hinting?</a></p>\n\n<p>E_ERROR errors, however, can be handled, but not recovered from as the engine is in an unstable state.</p>\n"
},
{
"answer_id": 10545621,
"author": "Lucas Batistussi",
"author_id": 1238654,
"author_profile": "https://Stackoverflow.com/users/1238654",
"pm_score": 5,
"selected": false,
"text": "<p>I developed a way to catch all error types in PHP (almost all)! I have no sure about E_CORE_ERROR (I think will not works only for that error)! But, for other fatal errors (E_ERROR, E_PARSE, E_COMPILE...) works fine using only one error handler function! There goes my solution:</p>\n\n<p>Put this following code on your main file (index.php):</p>\n\n<pre><code><?php\n define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR |\n E_COMPILE_ERROR | E_RECOVERABLE_ERROR);\n\n define('ENV', 'dev');\n\n // Custom error handling vars\n define('DISPLAY_ERRORS', TRUE);\n define('ERROR_REPORTING', E_ALL | E_STRICT);\n define('LOG_ERRORS', TRUE);\n\n register_shutdown_function('shut');\n\n set_error_handler('handler');\n\n // Function to catch no user error handler function errors...\n function shut(){\n\n $error = error_get_last();\n\n if($error && ($error['type'] & E_FATAL)){\n handler($error['type'], $error['message'], $error['file'], $error['line']);\n }\n\n }\n\n function handler( $errno, $errstr, $errfile, $errline ) {\n\n switch ($errno){\n\n case E_ERROR: // 1 //\n $typestr = 'E_ERROR'; break;\n case E_WARNING: // 2 //\n $typestr = 'E_WARNING'; break;\n case E_PARSE: // 4 //\n $typestr = 'E_PARSE'; break;\n case E_NOTICE: // 8 //\n $typestr = 'E_NOTICE'; break;\n case E_CORE_ERROR: // 16 //\n $typestr = 'E_CORE_ERROR'; break;\n case E_CORE_WARNING: // 32 //\n $typestr = 'E_CORE_WARNING'; break;\n case E_COMPILE_ERROR: // 64 //\n $typestr = 'E_COMPILE_ERROR'; break;\n case E_CORE_WARNING: // 128 //\n $typestr = 'E_COMPILE_WARNING'; break;\n case E_USER_ERROR: // 256 //\n $typestr = 'E_USER_ERROR'; break;\n case E_USER_WARNING: // 512 //\n $typestr = 'E_USER_WARNING'; break;\n case E_USER_NOTICE: // 1024 //\n $typestr = 'E_USER_NOTICE'; break;\n case E_STRICT: // 2048 //\n $typestr = 'E_STRICT'; break;\n case E_RECOVERABLE_ERROR: // 4096 //\n $typestr = 'E_RECOVERABLE_ERROR'; break;\n case E_DEPRECATED: // 8192 //\n $typestr = 'E_DEPRECATED'; break;\n case E_USER_DEPRECATED: // 16384 //\n $typestr = 'E_USER_DEPRECATED'; break;\n }\n\n $message =\n '<b>' . $typestr .\n ': </b>' . $errstr .\n ' in <b>' . $errfile .\n '</b> on line <b>' . $errline .\n '</b><br/>';\n\n if(($errno & E_FATAL) && ENV === 'production'){\n\n header('Location: 500.html');\n header('Status: 500 Internal Server Error');\n\n }\n\n if(!($errno & ERROR_REPORTING))\n return;\n\n if(DISPLAY_ERRORS)\n printf('%s', $message);\n\n //Logging error on php file error log...\n if(LOG_ERRORS)\n error_log(strip_tags($message), 0);\n }\n\n ob_start();\n\n @include 'content.php';\n\n ob_end_flush();\n?>\n</code></pre>\n"
},
{
"answer_id": 11633893,
"author": "Cyril Tata",
"author_id": 1549152,
"author_profile": "https://Stackoverflow.com/users/1549152",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using PHP >= 5.1.0\nJust do something like this with the ErrorException class:</p>\n\n<pre><code><?php\n // Define an error handler\n function exception_error_handler($errno, $errstr, $errfile, $errline ) {\n throw new ErrorException($errstr, $errno, 0, $errfile, $errline);\n }\n\n // Set your error handler\n set_error_handler(\"exception_error_handler\");\n\n /* Trigger exception */\n try\n {\n // Try to do something like finding the end of the internet\n }\n catch(ErrorException $e)\n {\n // Anything you want to do with $e\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 13986716,
"author": "tix3",
"author_id": 900617,
"author_profile": "https://Stackoverflow.com/users/900617",
"pm_score": 2,
"selected": false,
"text": "<p>There are certain circumstances in which even fatal errors should be caught (you might need to do some clean up before exiting gracefully and don’t just die..).</p>\n\n<p>I have implemented a pre_system hook in my <a href=\"https://en.wikipedia.org/wiki/CodeIgniter\" rel=\"nofollow noreferrer\">CodeIgniter</a> applications so that I can get my fatal errors through emails, and this helped me finding bugs that were not reported (or were reported after they were fixed, as I already knew about them :)).</p>\n\n<p>Sendemail checks if the error has already been reported so that it does not spam you with known errors multiple times.</p>\n\n<pre><code>class PHPFatalError {\n\n public function setHandler() {\n register_shutdown_function('handleShutdown');\n }\n}\n\nfunction handleShutdown() {\n if (($error = error_get_last())) {\n ob_start();\n echo \"<pre>\";\n var_dump($error);\n echo \"</pre>\";\n $message = ob_get_clean();\n sendEmail($message);\n ob_start();\n echo '{\"status\":\"error\",\"message\":\"Internal application error!\"}';\n ob_flush();\n exit();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17343858,
"author": "Sander Visser",
"author_id": 2032020,
"author_profile": "https://Stackoverflow.com/users/2032020",
"pm_score": 3,
"selected": false,
"text": "<p>Here is just a nice trick to get the current error_handler method =)</p>\n\n<pre><code><?php\n register_shutdown_function('__fatalHandler');\n\n function __fatalHandler()\n {\n $error = error_get_last();\n\n // Check if it's a core/fatal error. Otherwise, it's a normal shutdown\n if($error !== NULL && $error['type'] === E_ERROR) {\n\n // It is a bit hackish, but the set_exception_handler\n // will return the old handler\n function fakeHandler() { }\n\n $handler = set_exception_handler('fakeHandler');\n restore_exception_handler();\n if($handler !== null) {\n call_user_func(\n $handler,\n new ErrorException(\n $error['message'],\n $error['type'],\n 0,\n $error['file'],\n $error['line']));\n }\n exit;\n }\n }\n?>\n</code></pre>\n\n<p>Also I want to note that if you call</p>\n\n<pre><code><?php\n ini_set('display_errors', false);\n?>\n</code></pre>\n\n<p>PHP stops displaying the error. Otherwise, the error text will be send to the client prior to your error handler.</p>\n"
},
{
"answer_id": 26487785,
"author": "algorhythm",
"author_id": 655224,
"author_profile": "https://Stackoverflow.com/users/655224",
"pm_score": 3,
"selected": false,
"text": "<h3>Nice solution found in Zend Framework 2:</h3>\n\n<pre><code>/**\n * ErrorHandler that can be used to catch internal PHP errors\n * and convert to an ErrorException instance.\n */\nabstract class ErrorHandler\n{\n /**\n * Active stack\n *\n * @var array\n */\n protected static $stack = array();\n\n /**\n * Check if this error handler is active\n *\n * @return bool\n */\n public static function started()\n {\n return (bool) static::getNestedLevel();\n }\n\n /**\n * Get the current nested level\n *\n * @return int\n */\n public static function getNestedLevel()\n {\n return count(static::$stack);\n }\n\n /**\n * Starting the error handler\n *\n * @param int $errorLevel\n */\n public static function start($errorLevel = \\E_WARNING)\n {\n if (!static::$stack) {\n set_error_handler(array(get_called_class(), 'addError'), $errorLevel);\n }\n\n static::$stack[] = null;\n }\n\n /**\n * Stopping the error handler\n *\n * @param bool $throw Throw the ErrorException if any\n * @return null|ErrorException\n * @throws ErrorException If an error has been catched and $throw is true\n */\n public static function stop($throw = false)\n {\n $errorException = null;\n\n if (static::$stack) {\n $errorException = array_pop(static::$stack);\n\n if (!static::$stack) {\n restore_error_handler();\n }\n\n if ($errorException && $throw) {\n throw $errorException;\n }\n }\n\n return $errorException;\n }\n\n /**\n * Stop all active handler\n *\n * @return void\n */\n public static function clean()\n {\n if (static::$stack) {\n restore_error_handler();\n }\n\n static::$stack = array();\n }\n\n /**\n * Add an error to the stack\n *\n * @param int $errno\n * @param string $errstr\n * @param string $errfile\n * @param int $errline\n * @return void\n */\n public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)\n {\n $stack = & static::$stack[count(static::$stack) - 1];\n $stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);\n }\n}\n</code></pre>\n\n<p>This class allows you to start the specific <code>ErrorHandler</code> sometimes if you need it. And then you can also stop the Handler.</p>\n\n<p>Use this class e.g. like this:</p>\n\n<pre><code>ErrorHandler::start(E_WARNING);\n$return = call_function_raises_E_WARNING();\n\nif ($innerException = ErrorHandler::stop()) {\n throw new Exception('Special Exception Text', 0, $innerException);\n}\n\n// or\nErrorHandler::stop(true); // directly throws an Exception;\n</code></pre>\n\n<p>Link to the full class code: <br /><a href=\"https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php\" rel=\"noreferrer\">https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php</a></p>\n\n<p><br /><h3>A maybe better solution is that one from <a href=\"https://github.com/Seldaek/monolog\" rel=\"noreferrer\">Monolog</a>:</h3>\nLink to the full class code: <br /><a href=\"https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php\" rel=\"noreferrer\">https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php</a></p>\n\n<p>It can also handle FATAL_ERRORS using the <code>register_shutdown_function</code> function. According to this class a FATAL_ERROR is one of the following <code>array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR)</code>.</p>\n\n<pre><code>class ErrorHandler\n{\n // [...]\n\n public function registerExceptionHandler($level = null, $callPrevious = true)\n {\n $prev = set_exception_handler(array($this, 'handleException'));\n $this->uncaughtExceptionLevel = $level;\n if ($callPrevious && $prev) {\n $this->previousExceptionHandler = $prev;\n }\n }\n\n public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)\n {\n $prev = set_error_handler(array($this, 'handleError'), $errorTypes);\n $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);\n if ($callPrevious) {\n $this->previousErrorHandler = $prev ?: true;\n }\n }\n\n public function registerFatalHandler($level = null, $reservedMemorySize = 20)\n {\n register_shutdown_function(array($this, 'handleFatalError'));\n\n $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);\n $this->fatalLevel = $level;\n }\n\n // [...]\n}\n</code></pre>\n"
},
{
"answer_id": 26828734,
"author": "Mahn",
"author_id": 1329367,
"author_profile": "https://Stackoverflow.com/users/1329367",
"pm_score": 3,
"selected": false,
"text": "<p>Since most answers here are unnecesarily verbose, here's my non-ugly version of the top voted answer:</p>\n\n<pre><code>function errorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = array()) {\n //Do stuff: mail, log, etc\n}\n\nfunction fatalHandler() {\n $error = error_get_last();\n if($error) errorHandler($error[\"type\"], $error[\"message\"], $error[\"file\"], $error[\"line\"]);\n}\n\nset_error_handler(\"errorHandler\")\nregister_shutdown_function(\"fatalHandler\");\n</code></pre>\n"
},
{
"answer_id": 36638910,
"author": "zainengineer",
"author_id": 3232611,
"author_profile": "https://Stackoverflow.com/users/3232611",
"pm_score": 5,
"selected": false,
"text": "<p>You can't catch/handle fatal errors, but you can log/report them.\nFor quick debugging I modified one answer to this simple code</p>\n\n<pre><code>function __fatalHandler()\n{\n $error = error_get_last();\n\n // Check if it's a core/fatal error, otherwise it's a normal shutdown\n if ($error !== NULL && in_array($error['type'],\n array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,\n E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {\n\n echo \"<pre>fatal error:\\n\";\n print_r($error);\n echo \"</pre>\";\n die;\n }\n}\n\nregister_shutdown_function('__fatalHandler');\n</code></pre>\n"
},
{
"answer_id": 48381661,
"author": "LugiHaue",
"author_id": 3271096,
"author_profile": "https://Stackoverflow.com/users/3271096",
"pm_score": 6,
"selected": false,
"text": "<p>Fatal errors or recoverable fatal errors now throw instances of <code>Error</code> in <strong>PHP 7 or higher versions</strong>. Like any other exceptions, <code>Error</code> objects can be caught using a <code>try/catch</code> block.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code><?php\n$variable = 'not an object';\n\ntry {\n $variable->method(); // Throws an Error object in PHP 7 or higger.\n} catch (Error $e) {\n // Handle error\n echo $e->getMessage(); // Call to a member function method() on string\n}\n</code></pre>\n\n<p><a href=\"https://3v4l.org/67vbk\" rel=\"noreferrer\">https://3v4l.org/67vbk</a></p>\n\n<p>Or you can use <code>Throwable</code> interface to catch all exceptions.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code><?php\n try {\n undefinedFunctionCall();\n } catch (Throwable $e) {\n // Handle error\n echo $e->getMessage(); // Call to undefined function undefinedFunctionCall()\n }\n</code></pre>\n\n<p><a href=\"https://3v4l.org/Br0MG\" rel=\"noreferrer\">https://3v4l.org/Br0MG</a></p>\n\n<p>For more information: <a href=\"http://php.net/manual/en/language.errors.php7.php\" rel=\"noreferrer\">http://php.net/manual/en/language.errors.php7.php</a></p>\n"
},
{
"answer_id": 68138459,
"author": "David Spector",
"author_id": 2184308,
"author_profile": "https://Stackoverflow.com/users/2184308",
"pm_score": 0,
"selected": false,
"text": "<p>As of PHP 7.4.13 my experience is that all possible errors and exceptions in a program can be caught with only two callback functions:</p>\n<pre><code>set_error_handler("ErrorCB");\nset_exception_handler("ExceptCB");\n</code></pre>\n<p>ErrorCB simply reports its arguments in any way desired and calls Exit().</p>\n<p>ExceptCB calls "get" methods on its exception argument and does some logic to determine where the file, line, and function are (ask me if you would like details), and reports the information in any way desired and returns.</p>\n<p>The only need for try/catch is if you need to suppress errors for certain code, when @ or isset() isn't enough. Using try/catch for a "main function" without setting handlers fails, since it doesn't catch all errors.</p>\n<p>If anyone finds code that generates an error that this approach doesn't catch, please let me know and I'll edit this answer. One error that this approach can't intercept is a single { character near the end of a PHP program; this generates a Parse error, which requires that you run your main PHP program via an Include file that contains the error handling.</p>\n<p>I haven't found any need for register_shutdown_function().</p>\n<p>Note that all I care about is reporting errors and then quitting the program; I don't need to recover from errors--that would be a much more difficult question indeed.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] |
I can use `set_error_handler()` to catch most PHP errors, but it doesn't work for fatal (`E_ERROR`) errors, such as calling a function that doesn't exist. Is there another way to catch these errors?
I am trying to call `mail()` for all errors and am running PHP 5.2.3.
|
Log fatal errors using the `register_shutdown_function`, which requires PHP 5.2+:
```
register_shutdown_function( "fatal_handler" );
function fatal_handler() {
$errfile = "unknown file";
$errstr = "shutdown";
$errno = E_CORE_ERROR;
$errline = 0;
$error = error_get_last();
if($error !== NULL) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
error_mail(format_error( $errno, $errstr, $errfile, $errline));
}
}
```
You will have to define the `error_mail` and `format_error` functions. For example:
```php
function format_error( $errno, $errstr, $errfile, $errline ) {
$trace = print_r( debug_backtrace( false ), true );
$content = "
<table>
<thead><th>Item</th><th>Description</th></thead>
<tbody>
<tr>
<th>Error</th>
<td><pre>$errstr</pre></td>
</tr>
<tr>
<th>Errno</th>
<td><pre>$errno</pre></td>
</tr>
<tr>
<th>File</th>
<td>$errfile</td>
</tr>
<tr>
<th>Line</th>
<td>$errline</td>
</tr>
<tr>
<th>Trace</th>
<td><pre>$trace</pre></td>
</tr>
</tbody>
</table>";
return $content;
}
```
Use [Swift Mailer](http://swiftmailer.org/) to write the `error_mail` function.
See also:
* *[$php\_errormsg](http://php.net/manual/en/reserved.variables.phperrormsg.php)*
* *[Predefined Constants](http://php.net/manual/en/errorfunc.constants.php)*
|
277,247 |
<p>How do I add a certain number of days to the current date in PHP?</p>
<p>I already got the current date with:</p>
<pre><code>$today = date('y:m:d');
</code></pre>
<p>Just need to add x number of days to it</p>
|
[
{
"answer_id": 277251,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": false,
"text": "<p>a day is 86400 seconds.</p>\n\n<pre><code>$tomorrow = date('y:m:d', time() + 86400);\n</code></pre>\n"
},
{
"answer_id": 277252,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://ca.php.net/manual/en/function.date-add.php\" rel=\"noreferrer\"><code>date_add()</code></a> function should do what you want. In addition, check out the docs (unofficial, but the official ones are a bit sparse) for the <a href=\"http://laughingmeme.org/2007/02/27/\" rel=\"noreferrer\"><code>DateTime</code></a> object, it's much nicer to work with than the procedural functions in PHP.</p>\n"
},
{
"answer_id": 277259,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": true,
"text": "<p><code>php</code> supports c style date functions. You can add or substract date-periods with English-language style phrases via the <code>strtotime</code> function. examples...</p>\n\n<pre><code>$Today=date('y:m:d');\n\n// add 3 days to date\n$NewDate=Date('y:m:d', strtotime('+3 days'));\n\n// subtract 3 days from date\n$NewDate=Date('y:m:d', strtotime('-3 days'));\n\n// PHP returns last sunday's date\n$NewDate=Date('y:m:d', strtotime('Last Sunday'));\n\n// One week from last sunday\n$NewDate=Date('y:m:d', strtotime('+7 days Last Sunday'));\n</code></pre>\n\n<p>or </p>\n\n<pre><code><select id=\"date_list\" class=\"form-control\" style=\"width:100%;\">\n<?php\n$max_dates = 15;\n$countDates = 0;\nwhile ($countDates < $max_dates) {\n $NewDate=Date('F d, Y', strtotime(\"+\".$countDates.\" days\"));\n echo \"<option>\" . $NewDate . \"</option>\";\n $countDates += 1;\n}\n?>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 14027441,
"author": "Xavier John",
"author_id": 1394827,
"author_profile": "https://Stackoverflow.com/users/1394827",
"pm_score": 3,
"selected": false,
"text": "<p>With php 5.3 </p>\n\n<pre><code> $date = new DateTime();\n $interval = new DateInterval('P1D');\n echo $date->format('Y-m-d') , PHP_EOL;\n $date->add($interval);\n echo $date->format('Y-m-d'), PHP_EOL;\n $date->add($interval);\n echo $date->format('Y-m-d'), PHP_EOL;\n</code></pre>\n\n<p>will output </p>\n\n<p>2012-12-24</p>\n\n<p>2012-12-25</p>\n\n<p>2012-12-26</p>\n"
},
{
"answer_id": 28011356,
"author": "Biswadeep Sarkar",
"author_id": 4367758,
"author_profile": "https://Stackoverflow.com/users/4367758",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest way to add x no. of days..</p>\n\n<pre><code>echo date('Y-m-d',strtotime('+1 day')); //+1 day from today\n</code></pre>\n\n<p>OR from specified date...</p>\n\n<pre><code>echo date('Y-m-d',strtotime('+1 day', strtotime('2007-02-28')));\n</code></pre>\n"
},
{
"answer_id": 29850650,
"author": "Philipp",
"author_id": 313501,
"author_profile": "https://Stackoverflow.com/users/313501",
"pm_score": 2,
"selected": false,
"text": "<p>If you need this code in several places then I'd suggest that you add a short function to keep your code simpler and easier to test.</p>\n\n<pre><code>function add_days( $days, $from_date = null ) {\n if ( is_numeric( $from_date ) ) { \n $new_date = $from_date; \n } else { \n $new_date = time();\n }\n\n // Timestamp is the number of seconds since an event in the past\n // To increate the value by one day we have to add 86400 seconds to the value\n // 86400 = 24h * 60m * 60s\n $new_date += $days * 86400;\n\n return $new_date;\n}\n</code></pre>\n\n<p>Then you can use it anywhere like this:</p>\n\n<pre><code>$today = add_days( 0 );\n$tomorrow = add_days( 1 );\n$yesterday = add_days( -1 );\n$in_36_hours = add_days( 1.5 );\n\n$first_reminder = add_days( 10 );\n$second_reminder = add_days( 5, $first_reminder );\n$last_reminder = add_days( 3, $second_reminder );\n</code></pre>\n"
},
{
"answer_id": 40903830,
"author": "Abdul Rafay",
"author_id": 7224751,
"author_profile": "https://Stackoverflow.com/users/7224751",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n$dt = new DateTime;\nif(isset($_GET['year']) && isset($_GET['week'])) {\n $dt->setISODate($_GET['year'], $_GET['week']);\n} else {\n $dt->setISODate($dt->format('o'), $dt->format('W'));\n}\n$year = $dt->format('o');\n$week = $dt->format('W');\n?>\n\n<a href=\"<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>\">Pre Week</a> \n<a href=\"<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>\">Next Week</a>\n<table width=\"100%\" style=\"height: 75px; border: 1px solid #00A2FF;\">\n<tr>\n<td style=\"display: table-cell;\n vertical-align: middle;\n cursor: pointer;\n width: 75px;\n height: 75px;\n border: 4px solid #00A2FF;\n border-radius: 50%;\">Employee</td>\n<?php\ndo {\n echo \"<td>\" . $dt->format('M') . \"<br>\" . $dt->format('d M Y') . \"</td>\\n\";\n $dt->modify('+1 day');\n} while ($week == $dt->format('W'));\n?>\n</tr>\n</table>\n</code></pre>\n"
},
{
"answer_id": 49948517,
"author": "Rayed",
"author_id": 2284961,
"author_profile": "https://Stackoverflow.com/users/2284961",
"pm_score": 0,
"selected": false,
"text": "<p>Add 15 day to a select element (using \"Alive to Die\" suggestion)</p>\n\n<pre><code><select id=\"date_list\" class=\"form-control\" style=\"width:100%;\">\n<?php\n$max_dates = 15;\n$countDates = 0;\nwhile ($countDates < $max_dates) {\n $NewDate=Date('F d, Y', strtotime(\"+\".$countDates.\" days\"));\n echo \"<option>\" . $NewDate . \"</option>\";\n $countDates += 1;\n}\n?>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 56249975,
"author": "Kaushik shrimali",
"author_id": 9106811,
"author_profile": "https://Stackoverflow.com/users/9106811",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$NewDate=Date('Y-m-d', strtotime('+365 days'));\n</code></pre>\n\n<blockquote>\n <p>echo $NewDate; //2020-05-21</p>\n</blockquote>\n"
},
{
"answer_id": 56546423,
"author": "humbads",
"author_id": 553396,
"author_profile": "https://Stackoverflow.com/users/553396",
"pm_score": 0,
"selected": false,
"text": "<p><code>$NewTime = mktime(date('G'), date('i'), date('s'), date('n'), date('j') + $DaysToAdd, date('Y'));</code></p>\n\n<p>From <a href=\"https://www.php.net/manual/en/function.mktime.php\" rel=\"nofollow noreferrer\">mktime documentation</a>:</p>\n\n<blockquote>\n <p>mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. </p>\n</blockquote>\n\n<p>The advantage of this method is that you can add or subtract any time interval (hours, minutes, seconds, days, months, or years) in an easy to read line of code. </p>\n\n<p>Beware there is a tradeoff in performance, as this code is about 2.5x slower than strtotime(\"+1 day\") due to all the calls to the date() function. Consider re-using those values if you are in a loop.</p>\n"
},
{
"answer_id": 65058609,
"author": "pjehan",
"author_id": 2159979,
"author_profile": "https://Stackoverflow.com/users/2159979",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use Object Oriented Programming (OOP) instead of procedural programming:</p>\n<pre><code>$fiveDays = new DateInterval('P5D');\n$today = new DateTime();\n$fiveDaysAgo = $today->sub(fiveDays); // or ->add(fiveDays); to add 5 days\n</code></pre>\n<p>Or with just one line of code:</p>\n<pre><code>$fiveDaysAgo = (new DateTime())->sub(new DateInterval('P5D'));\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I add a certain number of days to the current date in PHP?
I already got the current date with:
```
$today = date('y:m:d');
```
Just need to add x number of days to it
|
`php` supports c style date functions. You can add or substract date-periods with English-language style phrases via the `strtotime` function. examples...
```
$Today=date('y:m:d');
// add 3 days to date
$NewDate=Date('y:m:d', strtotime('+3 days'));
// subtract 3 days from date
$NewDate=Date('y:m:d', strtotime('-3 days'));
// PHP returns last sunday's date
$NewDate=Date('y:m:d', strtotime('Last Sunday'));
// One week from last sunday
$NewDate=Date('y:m:d', strtotime('+7 days Last Sunday'));
```
or
```
<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
$NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
echo "<option>" . $NewDate . "</option>";
$countDates += 1;
}
?>
```
|
277,256 |
<p>Is it possible to have a CSS rule which basically "undoes" a prior rule?</p>
<p>An example:</p>
<pre><code><blockquote>
some text <em>more text</em> other text
</blockquote>
</code></pre>
<p>and let's say there's this CSS:</p>
<pre><code>blockquote {
color: red;
}
</code></pre>
<p>...but I want the <code><em></code> to remain the normal text color (which you may not necessarily know).</p>
<p>Basically, would there be a way to do something like this?</p>
<pre><code>blockquote em {
color: inherit-from-blockquote's-parent
}
</code></pre>
<hr>
<p>Edit: The code I'm actually trying to get this to work on is actually a bit more complicated. Maybe this would explain it better:</p>
<pre><code>This text should be *some unknown colour*
<ul>
<li>This text should be BLUE
<ul>
<li>Same as outside the UL</li>
<li>Same as outside the UL</li>
</ul>
</li>
</ul>
ul {
color: blue;
}
ul ul {
color: ???;
}
</code></pre>
|
[
{
"answer_id": 277270,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, the additional text with example clarifies the question a lot. And I'm affraid that what you want is not possible.</p>\n\n<p>If you know the \"unknown colour\" you can of course repeat the color. But I think CSS needs some mechanism to add variables or references. </p>\n\n<p>So you have to stick to the cumbersome:</p>\n\n<pre><code>ul {\n color: blue;\n}\nli ul {\n color: sameenvironment; /* Sorry but you have to add the specific colour here */\n}\n</code></pre>\n"
},
{
"answer_id": 277275,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "<p>My CSS is a bit rusty, but this should work:</p>\n\n<pre><code>blockquote {\n color: red;\n}\n\nblockquote em {\n color: inherit;\n}\n</code></pre>\n\n<p>You are setting blockquotes to red, but all <code><em>'s</code> that are contained in a blockquote should inherit... hmmm, should they inherit from the surrounding text, or from the blockquote? </p>\n\n<p>If the above does not work as you want, then there is no way to do it with the current markup, I think. You would have to work with additional markup, or set the colour explicitltly, e.g.</p>\n\n<pre><code>blockquote em {\n color: Purple;\n} \n</code></pre>\n"
},
{
"answer_id": 277299,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 0,
"selected": false,
"text": "<p>If you can change your html you could try </p>\n\n<pre><code><li><span>This text should be BLUE</span>\n <ul>\n <li>Same as outside the UL</li>\n <li>Same as outside the UL</li>\n </ul>\n</li>\n</code></pre>\n\n<p>and the style</p>\n\n<pre><code>li span{\n color: blue;\n}\n</code></pre>\n\n<p>EDIT\nanother way to accomplish this without the extra span tag:</p>\n\n<p>If we assume that we have a style class (or any other selector) that defines to parent of the outer ul. We can modify the css like this:</p>\n\n<pre><code>.parentStyle,\n.parentStyle li li{\n color:red;\n}\nli{\n color:blue;\n}\n</code></pre>\n"
},
{
"answer_id": 277343,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<p>With CSS alone, you can't refer to a parent's parent. </p>\n\n<p>The thing you can do is try a mix of specific CSS selectors and markup so that the desired effect appears. </p>\n\n<pre><code><td>\n This is the enclosing element.\n <ul>\n <li>This is the first level UL, direct child of TD\n <ul>\n <li>This is the second level UL</li>\n <li>Same as outside the UL</li>\n </ul>\n </li>\n </ul>\n</td>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>td > ul\n color: blue; /* this affects the \"direct child\" UL only */\n}\n</code></pre>\n\n<p>You would limit the depth of style inheritance to one level, consequently the inner UL is unstyled in regard to color and gets its setup from the enclosing text.</p>\n\n<p>Read more on the <a href=\"http://meyerweb.com/eric/articles/webrev/200006b.html\" rel=\"noreferrer\">CSS Child Selector</a>, and be aware that older browsers may have their quirks with them.</p>\n\n<hr>\n\n<p><strong>EDIT</strong></p>\n\n<p>For Internet Explorer 6, the child selector can be faked to some extend. Be sure to fasten seat belts (conditional comments or the like) before using this:</p>\n\n<pre><code>td ul {\n color: expression(/TD/.test(this.parentNode.tagName)? \"blue\" : \"black\");\n}\n</code></pre>\n\n<p>This assumes \"black\" as the outer color. If this color value is subject to change, your are out of luck, I'm afraid. Unless you can define an <code>expression()</code> that is able to get the color value from the context (e.g. checking some other properties of parent elements). Or you give up and use a JS framework, as someone else has already suggested.</p>\n\n<p>The wimpy solution without having to use JS would of course be:</p>\n\n<pre><code>td ul.first {\n color: blue;\n}\n</code></pre>\n\n<p>But I can see why you want to avoid that.</p>\n"
},
{
"answer_id": 277350,
"author": "conny",
"author_id": 23023,
"author_profile": "https://Stackoverflow.com/users/23023",
"pm_score": 2,
"selected": false,
"text": "<p>Give up and use a snippet of javascript to detect the style of the parent and set it? :)</p>\n"
},
{
"answer_id": 278705,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 3,
"selected": false,
"text": "<p>Use this to make sure the inherit overrides whatever else might have been setting the color:</p>\n\n<pre><code>blockquote em {\n color: inherit !important;\n}\n</code></pre>\n"
},
{
"answer_id": 428224,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than trying to force a selector to inherit font colour from its grandparent, I would suggest that you give the selector and its grandparent a shared declaration for the font colour.</p>\n\n<p>Taking the blockquote example, assuming that body is the grandparent:</p>\n\n<pre><code>body, blockquote em {\n color:[whatever];\n}\n\n\nblockquote {\n color:red;\n}\n</code></pre>\n\n<p>And in the case of the unordered lists, it would be:</p>\n\n<pre><code>body, ul ul {\n color:[whatever];\n}\n\n\nul {\n color:blue;\n}\n</code></pre>\n"
},
{
"answer_id": 23039159,
"author": "Codingale",
"author_id": 3340763,
"author_profile": "https://Stackoverflow.com/users/3340763",
"pm_score": 0,
"selected": false,
"text": "<p>I too had this question but after I glanced at the other answers it hit me, </p>\n\n<pre><code> body {\n color : initial;\n }\n</code></pre>\n\n<p>IE doesn't support this currently and Gecko requires a -moz-initial I believe..</p>\n\n<pre><code> body {\n color : unset;\n }\n</code></pre>\n\n<p>This one isn't quite as supported right now. I just thought I'd share my answer to this for anyone else who thinks about this.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
Is it possible to have a CSS rule which basically "undoes" a prior rule?
An example:
```
<blockquote>
some text <em>more text</em> other text
</blockquote>
```
and let's say there's this CSS:
```
blockquote {
color: red;
}
```
...but I want the `<em>` to remain the normal text color (which you may not necessarily know).
Basically, would there be a way to do something like this?
```
blockquote em {
color: inherit-from-blockquote's-parent
}
```
---
Edit: The code I'm actually trying to get this to work on is actually a bit more complicated. Maybe this would explain it better:
```
This text should be *some unknown colour*
<ul>
<li>This text should be BLUE
<ul>
<li>Same as outside the UL</li>
<li>Same as outside the UL</li>
</ul>
</li>
</ul>
ul {
color: blue;
}
ul ul {
color: ???;
}
```
|
With CSS alone, you can't refer to a parent's parent.
The thing you can do is try a mix of specific CSS selectors and markup so that the desired effect appears.
```
<td>
This is the enclosing element.
<ul>
<li>This is the first level UL, direct child of TD
<ul>
<li>This is the second level UL</li>
<li>Same as outside the UL</li>
</ul>
</li>
</ul>
</td>
```
CSS:
```
td > ul
color: blue; /* this affects the "direct child" UL only */
}
```
You would limit the depth of style inheritance to one level, consequently the inner UL is unstyled in regard to color and gets its setup from the enclosing text.
Read more on the [CSS Child Selector](http://meyerweb.com/eric/articles/webrev/200006b.html), and be aware that older browsers may have their quirks with them.
---
**EDIT**
For Internet Explorer 6, the child selector can be faked to some extend. Be sure to fasten seat belts (conditional comments or the like) before using this:
```
td ul {
color: expression(/TD/.test(this.parentNode.tagName)? "blue" : "black");
}
```
This assumes "black" as the outer color. If this color value is subject to change, your are out of luck, I'm afraid. Unless you can define an `expression()` that is able to get the color value from the context (e.g. checking some other properties of parent elements). Or you give up and use a JS framework, as someone else has already suggested.
The wimpy solution without having to use JS would of course be:
```
td ul.first {
color: blue;
}
```
But I can see why you want to avoid that.
|
277,284 |
<p>I've been playing around with ASP.NET MVC and had a question. Or maybe its a concern that I am doing this wrong. Just working on a lame site to stretch my wings a bit. I am sorry this question is not at all concise.</p>
<p>Ok, here's the scenario. When the user visits home/index, the page should show a list of products and a list of articles. The file layout is such (DAL is my data access layer):</p>
<pre>
Controllers
Home
Index
Views
Home
Index inherits from ViewPage
Product
List inherits from ViewUserControl<IEnumerable<DAL.Product>>
Single inherits from ViewUserControl<DAL.Product>
Article
List inherits from ViewUserControl<IEnumerable<DAL.Article>>
Single inherits from ViewUserControl<DAL.Article>
</pre>
<pre><code>Controllers.HomeController.Index produces a View whose ViewData contains two entries, a IEnumerable<DAL.Product> and a IEnumerable<DAL.Article>.
View.Home.Index will use those view entries to call:
Html.RenderPartial("~/Views/Product/List.ascx", ViewData["ProductList"])
and Html.RenderPartial("~/Views/Article/List.ascx", ViewData["ArticleList"])
View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial("Single", product);
View.Article.List does something similar to View.Product.List
</code></pre>
<p>This approach fails however. The approach makes sense to me, but maybe someone with more experience with these MVC platforms will recognize a better way.</p>
<p>The above produces an error inside View.Product.List. The call to <code>Html.RenderPartial("Single",...)</code> complains that "Single" view was not found. The error indicates:</p>
<pre>
The partial view 'Single' could not be found. The following locations were searched:
~/Views/Home/Single.aspx
~/Views/Home/Single.ascx
~/Views/Shared/Single.aspx
~/Views/Shared/Single.ascx
</pre>
<p>Because I was calling RenderAction() from a view in Product, I expected the runtime to look for the "Single" view within Views\Product. It seems however the lookup is relative the controller which invoked the original view (/Controller/Home invoked /Views/Product) rather than the current view.</p>
<p>So I am able to fix this by changing Views\Product, such that:</p>
<pre><code>View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial(<b>"~/Views/Product/Single.ascx"</b>, product);</code></pre>
<p>instead of</p>
<pre><code>View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial(<b>"Single"</b>, product);
</code></pre>
<p>This fix works but.. I do not understand why I needed to specify the full path of the view. It would make sense to me for the relative name to be interpreted relative to the current view's path rather than the original controller's view path. I cannot think of any useful case where interpreting the name relative to the controller's view instead of the current view is useful (except in the typical case where they are the same).</p>
<p>Around this time I should have a question mark? To emphasis this actually is a question.</p>
|
[
{
"answer_id": 281712,
"author": "anonymous",
"author_id": 36602,
"author_profile": "https://Stackoverflow.com/users/36602",
"pm_score": 2,
"selected": false,
"text": "<p>[edit:</p>\n\n<p>I was thinking, you have 2 cases:</p>\n\n<ul>\n<li>the Home controller is the only one that ever references Product / Articles List user control</li>\n<li>the user controls are shared by several controllers</li>\n</ul>\n\n<p>In the first case, the view user controls really belong to the home controller and it makes sense to put them in the home controller folder. In the second case, it makes sense to place them in the shared folder since they will be shared by controllers.</p>\n\n<p>In either case, maybe you can place them in a sub folder. Like Views/Home/Products and then try RendarPartial(\"Product/Single\") and see what happens? I don't know if it would try to resolve it to: Home/Product/Single and then Shared/Product/Single or not. If sub folders work, it seems to allow the logical seperation of Product and Article, while showing that they are still members of either the Home controller or Shared by all controllers.</p>\n\n<p>]</p>\n\n<p>Check out this blog entry by Steve Sanderson:</p>\n\n<p><a href=\"http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/\" rel=\"nofollow noreferrer\">http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/</a></p>\n\n<p>What you are doing isn't wrong, but it does seem to sort of go against the convention of View/Controller folder names. That said, it makes sense to want to define controller-agnostic view user controls and nesting them seems valid. So I dunno!</p>\n\n<p>Anyways, the link just describes a method of instead of using RenderPartial to render a use control, it defines a method of RenderPartialRequest that renders the return value (in your case a user control) of a controller action. So you could add a Product and Articles controller with an Action List that returns your user control, and then call those two actions from the Home/Index view. This seems more intuitive to me, but just an opinion.</p>\n\n<p>He also mentions subcontrollers from MVC Contrib, and I'm pretty sure there is desire for something like this to be a part of ASP.NET MVC release.</p>\n"
},
{
"answer_id": 282055,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p>Because I was calling RenderAction()\nfrom a view in Product</p>\n<p>...</p>\n<p>I do not understand why I needed\nto specify the full path of the view.\nIt would make sense to me for the\nrelative name to be interpreted\nrelative to the current view's path\nrather than the original controller's\nview path</p>\n</blockquote>\n<p>The part I think you're misunderstanding is the "execution location" for lack of a better or official term. Paths are not relative to your view, not even your "controller's view" as you put it. They are relative to your request URL, which defines a controller context. I may not be saying it very well, but if you spent a little time in Reflector looking at how URLs and routes are resolved, I think this would all fall into place in your head.</p>\n"
},
{
"answer_id": 282110,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<p>From looking at the MVCStoreFront sample this is how they have everything structured for calling RenderPartial</p>\n\n<pre><code>Views\n Shared\n ProductSingle\n ProductList\n ArticleSingle\n ArticleList\n</code></pre>\n\n<p>Then render them via:</p>\n\n<pre><code><% Html.RenderPartial(\"ProductSingle\", ViewData[\"ProductList\"]); %>\n<% Html.RenderPartial(\"ProductList\", product); %>\n<% Html.RenderPartial(\"ArticleSingle\", article); %>\n<% Html.RenderPartial(\"ArticleList\", ViewData[\"ArticleList\"]); %>\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32203/"
] |
I've been playing around with ASP.NET MVC and had a question. Or maybe its a concern that I am doing this wrong. Just working on a lame site to stretch my wings a bit. I am sorry this question is not at all concise.
Ok, here's the scenario. When the user visits home/index, the page should show a list of products and a list of articles. The file layout is such (DAL is my data access layer):
```
Controllers
Home
Index
Views
Home
Index inherits from ViewPage
Product
List inherits from ViewUserControl<IEnumerable<DAL.Product>>
Single inherits from ViewUserControl<DAL.Product>
Article
List inherits from ViewUserControl<IEnumerable<DAL.Article>>
Single inherits from ViewUserControl<DAL.Article>
```
```
Controllers.HomeController.Index produces a View whose ViewData contains two entries, a IEnumerable<DAL.Product> and a IEnumerable<DAL.Article>.
View.Home.Index will use those view entries to call:
Html.RenderPartial("~/Views/Product/List.ascx", ViewData["ProductList"])
and Html.RenderPartial("~/Views/Article/List.ascx", ViewData["ArticleList"])
View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial("Single", product);
View.Article.List does something similar to View.Product.List
```
This approach fails however. The approach makes sense to me, but maybe someone with more experience with these MVC platforms will recognize a better way.
The above produces an error inside View.Product.List. The call to `Html.RenderPartial("Single",...)` complains that "Single" view was not found. The error indicates:
```
The partial view 'Single' could not be found. The following locations were searched:
~/Views/Home/Single.aspx
~/Views/Home/Single.ascx
~/Views/Shared/Single.aspx
~/Views/Shared/Single.ascx
```
Because I was calling RenderAction() from a view in Product, I expected the runtime to look for the "Single" view within Views\Product. It seems however the lookup is relative the controller which invoked the original view (/Controller/Home invoked /Views/Product) rather than the current view.
So I am able to fix this by changing Views\Product, such that:
```
View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial(**"~/Views/Product/Single.ascx"**, product);
```
instead of
```
View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial(**"Single"**, product);
```
This fix works but.. I do not understand why I needed to specify the full path of the view. It would make sense to me for the relative name to be interpreted relative to the current view's path rather than the original controller's view path. I cannot think of any useful case where interpreting the name relative to the controller's view instead of the current view is useful (except in the typical case where they are the same).
Around this time I should have a question mark? To emphasis this actually is a question.
|
>
> Because I was calling RenderAction()
> from a view in Product
>
>
> ...
>
>
> I do not understand why I needed
> to specify the full path of the view.
> It would make sense to me for the
> relative name to be interpreted
> relative to the current view's path
> rather than the original controller's
> view path
>
>
>
The part I think you're misunderstanding is the "execution location" for lack of a better or official term. Paths are not relative to your view, not even your "controller's view" as you put it. They are relative to your request URL, which defines a controller context. I may not be saying it very well, but if you spent a little time in Reflector looking at how URLs and routes are resolved, I think this would all fall into place in your head.
|
277,288 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/334879/how-do-i-get-the-application-exit-code-from-a-windows-command-line">How do I get the application exit code from a Windows command line?</a> </p>
</blockquote>
<p>In Unix/bash, I can simply say:</p>
<blockquote>
<p>$ echo $?</p>
</blockquote>
<p>to find out the return/exit code of a program, both from interactive and non-interactive shells.</p>
<p>Now, how can I do the equivalent in Windows/cmd.exe? </p>
|
[
{
"answer_id": 277292,
"author": "CiNN",
"author_id": 2566,
"author_profile": "https://Stackoverflow.com/users/2566",
"pm_score": 2,
"selected": false,
"text": "<p>check for the ERRORLEVEL</p>\n"
},
{
"answer_id": 277302,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 4,
"selected": false,
"text": "<p>Use \"errorlevel\", like this:</p>\n\n<pre><code>IF ERRORLEVEL 1 GOTO ERROR\n</code></pre>\n\n<p>The errorlevel command is a little peculiar; it returns true if the return code was equal to or <strong>higher</strong> than the specified errorlevel. You can also write</p>\n\n<pre><code>IF %ERRORLEVEL% NEQ 0 GOTO ERROR\n</code></pre>\n\n<p><a href=\"http://www.robvanderwoude.com/errorlevel.html\" rel=\"noreferrer\">This page</a> is a good overview of how to use errorlevels in .bat files.</p>\n"
},
{
"answer_id": 1236989,
"author": "ebryn",
"author_id": 3572,
"author_profile": "https://Stackoverflow.com/users/3572",
"pm_score": 3,
"selected": false,
"text": "<p>The equivalent is:</p>\n\n<pre><code>echo %ERRORLEVEL%\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10955/"
] |
>
> **Possible Duplicate:**
>
> [How do I get the application exit code from a Windows command line?](https://stackoverflow.com/questions/334879/how-do-i-get-the-application-exit-code-from-a-windows-command-line)
>
>
>
In Unix/bash, I can simply say:
>
> $ echo $?
>
>
>
to find out the return/exit code of a program, both from interactive and non-interactive shells.
Now, how can I do the equivalent in Windows/cmd.exe?
|
Use "errorlevel", like this:
```
IF ERRORLEVEL 1 GOTO ERROR
```
The errorlevel command is a little peculiar; it returns true if the return code was equal to or **higher** than the specified errorlevel. You can also write
```
IF %ERRORLEVEL% NEQ 0 GOTO ERROR
```
[This page](http://www.robvanderwoude.com/errorlevel.html) is a good overview of how to use errorlevels in .bat files.
|
277,291 |
<p>In Eclipse RCP way of doing things, where should I keep my model objects? And when they are loaded or changed, how should they talk to the views?</p>
<p>I am attempting to port my existing application to Eclipse RCP. It could be viewed as an IDE-like application: I open a file, which contains links to source files. The source files are displayed in the tree view. I can edit the source, and build the sources into some output...</p>
<p>For example, when I handle the Open command, where would I create the model object so my views can see them? I'd rather avoid the use of singleton manager class, but that maybe the simplest way.</p>
<p>Interesting code I found browsing JDT's source code are JavaCore, JavaModel, JavaModelManager. and JavaProject.</p>
<hr>
<pre><code>IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
</code></pre>
<hr>
<pre><code>public static IJavaProject create(IProject project) {
if (project == null) {
return null;
}
JavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
return javaModel.getJavaProject(project);
}
</code></pre>
<hr>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/282509/how-do-you-communicate-between-eclipse-declarative-services-and-views-contentpr">How do you communicate between eclipse declarative services and Views (ContentProviders)</a></li>
<li><a href="http://www-128.ibm.com/developerworks/java/library/os-ecllink/index.html" rel="nofollow noreferrer">Make your Eclipse applications richer with view linking</a></li>
</ul>
|
[
{
"answer_id": 277411,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": true,
"text": "<p>I believe this is best achieved through Listeners.</p>\n\n<p>Your data (model) is in private package, and only Interfaces of those data are exposed in a public package.</p>\n\n<p><img src=\"https://wiki.eclipse.org/images/1/10/Mvc.png\" alt=\"alt text\"></p>\n\n<p>You will find in this <a href=\"http://wiki.eclipse.org/JFace_Data_Binding_Introduction\" rel=\"nofollow noreferrer\">wiki section</a> the principle, but also <a href=\"http://wiki.eclipse.org/JFace_Data_Binding/Snippets\" rel=\"nofollow noreferrer\">concrete examples here</a>.</p>\n\n<hr>\n\n<p>Regarding the model, an osgi-like approch would be to use a host plugin as the accessible object. i.e:</p>\n\n<pre><code>MyPlugin.getDefault().getModel()\n</code></pre>\n\n<p>This will allow you to setup/dispose the model along with the plugin lifecycle.</p>\n\n<p>If the model is in one plugin, it can define extension points for listeners. A view can extend these extension points which are then automatically registered in the loading of the Model plugin. The views can query the model for the required information as soon as they get the first message from the model.</p>\n\n<p>A good example of data binding can be found in <a href=\"http://www.vogella.de/articles/EclipseDataBinding/article.html\" rel=\"nofollow noreferrer\">this article</a>.</p>\n"
},
{
"answer_id": 277753,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 2,
"selected": false,
"text": "<p>We tend to use <code>IEditorPart</code>s to store keep a copy of the model (derived from the <code>IEditorInput</code>). </p>\n\n<p>If a view needs to know about the model, then use the ISelection framework and focus to move the model around from the editor to the view.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
In Eclipse RCP way of doing things, where should I keep my model objects? And when they are loaded or changed, how should they talk to the views?
I am attempting to port my existing application to Eclipse RCP. It could be viewed as an IDE-like application: I open a file, which contains links to source files. The source files are displayed in the tree view. I can edit the source, and build the sources into some output...
For example, when I handle the Open command, where would I create the model object so my views can see them? I'd rather avoid the use of singleton manager class, but that maybe the simplest way.
Interesting code I found browsing JDT's source code are JavaCore, JavaModel, JavaModelManager. and JavaProject.
---
```
IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
```
---
```
public static IJavaProject create(IProject project) {
if (project == null) {
return null;
}
JavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
return javaModel.getJavaProject(project);
}
```
---
Related:
* [How do you communicate between eclipse declarative services and Views (ContentProviders)](https://stackoverflow.com/questions/282509/how-do-you-communicate-between-eclipse-declarative-services-and-views-contentpr)
* [Make your Eclipse applications richer with view linking](http://www-128.ibm.com/developerworks/java/library/os-ecllink/index.html)
|
I believe this is best achieved through Listeners.
Your data (model) is in private package, and only Interfaces of those data are exposed in a public package.

You will find in this [wiki section](http://wiki.eclipse.org/JFace_Data_Binding_Introduction) the principle, but also [concrete examples here](http://wiki.eclipse.org/JFace_Data_Binding/Snippets).
---
Regarding the model, an osgi-like approch would be to use a host plugin as the accessible object. i.e:
```
MyPlugin.getDefault().getModel()
```
This will allow you to setup/dispose the model along with the plugin lifecycle.
If the model is in one plugin, it can define extension points for listeners. A view can extend these extension points which are then automatically registered in the loading of the Model plugin. The views can query the model for the required information as soon as they get the first message from the model.
A good example of data binding can be found in [this article](http://www.vogella.de/articles/EclipseDataBinding/article.html).
|
277,316 |
<p>I place the following statements in the second row of my grid in the xaml:</p>
<pre><code><ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="1">
<ListView Name="listView" Margin="5" Grid.Row="1">
<ListView.View>
<GridView AllowsColumnReorder="True">
<GridViewColumn DisplayMemberBinding="{Binding Path=DateTime}" Header="Date Time" Width="140"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Vehicle}" Header="Vehicle" Width="130"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=AlarmType}" Header="Alarm Type" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Direction}" Header="Direction" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Speed}" Header="Speed" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Alarmed}" Header="Alarmed" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=LoadType}" Header="Load Type" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Status}" Header="Status" Width="110"/>
</GridView>
</ListView.View>
</ListView>
</ScrollViewer>
</Grid>
</code></pre>
<p>I binded the listView.ItemSource to an ObservableCollection defined in the code to populate data to the list. When the number of items added to the GridView exceeded the listview height, the vertical scroll bar did not appear as i specified in the XAML. What did I do wrong? Your input is greatly appreciated. Thank you.</p>
|
[
{
"answer_id": 277436,
"author": "Artur Carvalho",
"author_id": 1013,
"author_profile": "https://Stackoverflow.com/users/1013",
"pm_score": 2,
"selected": false,
"text": "<p>See that the margins and paddings are correct. The scrollbar can be behind something.</p>\n\n<p>Put the exterior container height with a fixed value, It can be <em>stretching</em> the listview so it will never show the scrollbar.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 277567,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 3,
"selected": false,
"text": "<p>It works for me:</p>\n\n<pre><code><Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Window1\" Height=\"300\" Width=\"300\">\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"*\"/>\n <RowDefinition Height=\"*\"/>\n </Grid.RowDefinitions>\n\n <ScrollViewer VerticalScrollBarVisibility=\"Auto\" Grid.Row=\"1\">\n <ListView Name=\"listView\" Margin=\"5\" Grid.Row=\"1\">\n\n <ListView.View>\n <GridView AllowsColumnReorder=\"True\">\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=.}\" Header=\"Whatever\" Width=\"140\"/>\n </GridView>\n </ListView.View>\n </ListView>\n </ScrollViewer>\n </Grid>\n</Window>\n</code></pre>\n\n<p>However, the <code>ListView</code> control template contains a <code>ScrollViewer</code> already such that the <code>ScrollViewer</code> will appear <em>inside</em> the <code>ListView</code> as and when needed. Why do you need to wrap it in another?</p>\n"
},
{
"answer_id": 1865015,
"author": "Praveen Chandran",
"author_id": 226918,
"author_profile": "https://Stackoverflow.com/users/226918",
"pm_score": 0,
"selected": false,
"text": "<p>No need of using <code>ScrollViewer</code>. Just remove the <code>ScrollViewer</code> and use only the <code>ListView</code> and try.</p>\n\n<pre><code>ListView listView = new ListView();\nlistView.SetValue(Grid.RowProperty, 1);\nlistView.SetValue(Grid.ColumnProperty, 1);\nMainGrid.Children.Add(listView);\n</code></pre>\n\n<p>No need of specifying the width and height for the listview.</p>\n"
},
{
"answer_id": 10368063,
"author": "ankit",
"author_id": 1363480,
"author_profile": "https://Stackoverflow.com/users/1363480",
"pm_score": 0,
"selected": false,
"text": "<pre><code><Grid x:Name=\"MainMenuButtonGrid\">\n <StackPanel Margin=\"50,0,0,0\">\n <TextBlock Text=\"Please select any employee\" Foreground=\"Wheat\"/>\n <ListView x:Name=\"listEmployeeDetail\" SelectedValuePath=\"EmployeeID\">\n <ListView.View>\n <GridView>\n <GridViewColumn Header=\"EmployeeName\" Width=\"100\" DisplayMemberBinding=\"{Binding EmployeeName}\"></GridViewColumn>\n </GridView>\n </ListView.View>\n </ListView>\n </StackPanel>\n</Grid>\n</code></pre>\n"
},
{
"answer_id": 11238755,
"author": "lincy oommen",
"author_id": 1485461,
"author_profile": "https://Stackoverflow.com/users/1485461",
"pm_score": 1,
"selected": false,
"text": "<p>Try this code:</p>\n\n<pre><code>ListView listView = new ListView();\nlistView.SetValue(Grid.RowProperty, 1);\nlistView.SetValue(Grid.ColumnProperty, 1);\nMainGrid.Children.Add(listView);\n</code></pre>\n"
},
{
"answer_id": 65982305,
"author": "Baptiste Florentin",
"author_id": 9184081,
"author_profile": "https://Stackoverflow.com/users/9184081",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply use the MaxHeight property to constraint your listview to a specific height and the scrollbar will appear automaticly.\nFor example :</p>\n<pre><code> <ListView Name="listView" Margin="5" Grid.Row="1" MaxHeight="300">\n <ListView.View>\n <GridView AllowsColumnReorder="True">\n <GridViewColumn DisplayMemberBinding="{Binding Path=DateTime}" Header="Date Time" Width="140"/>\n <GridViewColumn DisplayMemberBinding="{Binding Path=Vehicle}" Header="Vehicle" Width="130"/>\n <GridViewColumn DisplayMemberBinding="{Binding Path=AlarmType}" Header="Alarm Type" Width="100"/>\n <GridViewColumn DisplayMemberBinding="{Binding Path=Direction}" Header="Direction" Width="100"/>\n <GridViewColumn DisplayMemberBinding="{Binding Path=Speed}" Header="Speed" Width="100"/>\n <GridViewColumn DisplayMemberBinding="{Binding Path=Alarmed}" Header="Alarmed" Width="100"/>\n <GridViewColumn DisplayMemberBinding="{Binding Path=LoadType}" Header="Load Type" Width="100"/>\n <GridViewColumn DisplayMemberBinding="{Binding Path=Status}" Header="Status" Width="110"/>\n </GridView>\n </ListView.View>\n </ListView> \n</code></pre>\n \n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I place the following statements in the second row of my grid in the xaml:
```
<ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="1">
<ListView Name="listView" Margin="5" Grid.Row="1">
<ListView.View>
<GridView AllowsColumnReorder="True">
<GridViewColumn DisplayMemberBinding="{Binding Path=DateTime}" Header="Date Time" Width="140"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Vehicle}" Header="Vehicle" Width="130"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=AlarmType}" Header="Alarm Type" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Direction}" Header="Direction" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Speed}" Header="Speed" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Alarmed}" Header="Alarmed" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=LoadType}" Header="Load Type" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Status}" Header="Status" Width="110"/>
</GridView>
</ListView.View>
</ListView>
</ScrollViewer>
</Grid>
```
I binded the listView.ItemSource to an ObservableCollection defined in the code to populate data to the list. When the number of items added to the GridView exceeded the listview height, the vertical scroll bar did not appear as i specified in the XAML. What did I do wrong? Your input is greatly appreciated. Thank you.
|
It works for me:
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="1">
<ListView Name="listView" Margin="5" Grid.Row="1">
<ListView.View>
<GridView AllowsColumnReorder="True">
<GridViewColumn DisplayMemberBinding="{Binding Path=.}" Header="Whatever" Width="140"/>
</GridView>
</ListView.View>
</ListView>
</ScrollViewer>
</Grid>
</Window>
```
However, the `ListView` control template contains a `ScrollViewer` already such that the `ScrollViewer` will appear *inside* the `ListView` as and when needed. Why do you need to wrap it in another?
|
277,327 |
<p>Is there a built in way to determine if a component is fully visible in a Flex application (i.e. not offscreen one way or the other). If not how would I go about figurin it out?</p>
<p>I want to show or hide additional 'next' and 'previous' buttons if my primary 'next' and 'previous' buttons are off screen.</p>
<p>What event would be best to listen to to 'recalculate' ? stage.resize?</p>
<p>thanks!</p>
|
[
{
"answer_id": 277426,
"author": "Jim Carroll",
"author_id": 35922,
"author_profile": "https://Stackoverflow.com/users/35922",
"pm_score": 0,
"selected": false,
"text": "<p>Could you give the specifics of the visible item and the container(s) it's in? Is it a matter of having to scroll some container to get to the buttons? Or is it a matter of someone has dragged a child window of a flexlib:MDICanvas partially off screen? </p>\n\n<p>I think it's going to come down to if the x,y position of the component is beyond the width and height of its container, (and so on up through the parent containers until you reach your top level Application.)</p>\n"
},
{
"answer_id": 280876,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 1,
"selected": false,
"text": "<p>here is a method for calculating if the component is within the bounds of the stage, it will not however tell you if the component is being hidden by another component, or if the component is being hidden because it is outside the bounds of another container.</p>\n\n<pre><code>public function isComponentWithinStage(c:UIComponent):Boolean {\n var tl:Point = c.localToGlobal(new Point(0, 0));\n var br:Point = c.localToGlobal(new Point(c.width, c.height));\n\n //are we off the left or top of stage?\n if ( tl.x < 0 || tl.y < 0 ) {\n return false;\n }\n\n var stage:Stage = Application.application.stage;\n\n //off the right or bottom of stage?\n if ( br.x > stage.width || br.y > stage.height ) {\n return false;\n }\n\n return true;\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
Is there a built in way to determine if a component is fully visible in a Flex application (i.e. not offscreen one way or the other). If not how would I go about figurin it out?
I want to show or hide additional 'next' and 'previous' buttons if my primary 'next' and 'previous' buttons are off screen.
What event would be best to listen to to 'recalculate' ? stage.resize?
thanks!
|
here is a method for calculating if the component is within the bounds of the stage, it will not however tell you if the component is being hidden by another component, or if the component is being hidden because it is outside the bounds of another container.
```
public function isComponentWithinStage(c:UIComponent):Boolean {
var tl:Point = c.localToGlobal(new Point(0, 0));
var br:Point = c.localToGlobal(new Point(c.width, c.height));
//are we off the left or top of stage?
if ( tl.x < 0 || tl.y < 0 ) {
return false;
}
var stage:Stage = Application.application.stage;
//off the right or bottom of stage?
if ( br.x > stage.width || br.y > stage.height ) {
return false;
}
return true;
}
```
|
277,340 |
<p>I'm executing a query like this</p>
<pre><code>select field from table;
</code></pre>
<p>In that query, there is a loop running on many tables. So, if the field is not present in a table I get a </p>
<blockquote>
<p>Runtime Error 3061</p>
</blockquote>
<p>How can I by pass this error such as that on this error flow should go to another point?</p>
<p>This is the code I have recently after going through this forum.</p>
<pre><code>Option Explicit
Private Sub UpdateNulls()
Dim rs2 As DAO.Recordset
Dim tdf As DAO.TableDef
Dim db As Database
Dim varii As Variant, strField As String
Dim strsql As String, strsql2 As String, strsql3 As String
Dim astrFields As Variant
Dim intIx As Integer
Dim field As Variant
Dim astrvalidcodes As Variant
Dim found As Boolean
Dim v As Variant
Open "C:\Documents and Settings\Desktop\testfile.txt" For Input As #1
varii = ""
Do While Not EOF(1)
Line Input #1, strField
varii = varii & "," & strField
Loop
Close #1
astrFields = Split(varii, ",") 'Element 0 empty
For intIx = 1 To UBound(astrFields)
'Function ListFieldDescriptions()
Dim cn As New ADODB.Connection, cn2 As New ADODB.Connection
Dim rs As ADODB.Recordset, rs3 As ADODB.Recordset
Dim connString As String
Dim SelectFieldName
Set cn = CurrentProject.Connection
SelectFieldName = astrFields(intIx)
Set rs = cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, Empty, SelectFieldName))
'Show the tables that have been selected '
While Not rs.EOF
'Exclude MS system tables '
If Left(rs!Table_Name, 4) <> "MSys" Then
strsql = "Select t.* From [" & rs!Table_Name & "] t Inner Join 01UMWELT On t.fall = [01UMWELT].fall Where [01UMWELT].Status = 4"
End If
Set rs3 = CurrentDb.OpenRecordset(strsql)
'End Function
strsql2 = "SELECT label.validcode FROM variablen s INNER JOIN label ON s.id=label.variablenid WHERE varname='" & astrFields(intIx) & "'"
Set db = OpenDatabase("C:\Documents and Settings\Desktop\Codebook.mdb")
Set rs2 = db.OpenRecordset(strsql2)
With rs2
.MoveLast
.MoveFirst
astrvalidcodes = rs2.GetRows(.RecordCount)
.Close '
End With
With rs3
.MoveFirst
While Not rs3.EOF
found = False
For Each v In astrvalidcodes
If v = .Fields(0) Then
found = True
Debug.Print .Fields(0)
Debug.Print .Fields(1)
Exit For
End If
Next
If Not found Then
msgbox "xxxxxxxxxxxxxxxx"
End If
End If
.MoveNext
Wend
End With
On Error GoTo 0 'End of special handling
Wend
Next intIx
End Sub
</code></pre>
<p>I'm getting a</p>
<blockquote>
<p>Type Mismatch Runtime Error </p>
</blockquote>
<p>in <code>Set rs3 = CurrentDb.OpenRecordset(strsql)</code></p>
<p>I guess I'm mixing up <code>ado</code> and <code>dao</code> but I'm not certainly sure where it is.</p>
|
[
{
"answer_id": 277366,
"author": "JTeagle",
"author_id": 162171,
"author_profile": "https://Stackoverflow.com/users/162171",
"pm_score": 0,
"selected": false,
"text": "<p>Try this: </p>\n\n<p>On Error Resume Next ' If an error occurs, move to next statement.</p>\n\n<p>...statement that tries the select...</p>\n\n<p>If (Err <> 0) Then</p>\n\n<pre><code>...act on error, or simply ignore if necessary...\n</code></pre>\n\n<p>End If</p>\n\n<p>On Error Goto 0 ' Reset error handling to previous state.</p>\n"
},
{
"answer_id": 277369,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>On Error</code> statement that VBA supplies:</p>\n\n<pre><code>Sub TableTest\n On Error Goto TableTest_Error\n\n ' ...code that can fail... '\n\n Exit Sub\n\n:TableTest_Error\n If Err.Number = 3061 Then\n Err.Clear()\n DoSomething()\n Else\n MsgBox Err.Description ' or whatever you find appropriate '\n End If\nEnd Sub\n</code></pre>\n\n<p>Alternatively, you can switch off automatic error handling (e.g. breaking execution and displaying an error message) on a line-by-line basis:</p>\n\n<pre><code>Sub TableTest\n ' ... fail-safe code ... '\n\n On Error Resume Next\n ' ...code that can fail... '\n If Err.Number = 3061 Then\n Err.Clear()\n DoSomething()\n Else\n MsgBox Err.Description\n End If\n On Error Goto 0\n\n ' ...mode fail-safe code... '\nEnd Sub\n</code></pre>\n\n<p>There are these statements available:</p>\n\n<ul>\n<li><code>On Error Resume Next</code> switches off VBA-integrated error handling (message box etc.) completely, execution simply resumes on the next line. Be sure to check for an error very early after you've used that, as a dangling error can disrupt the normal execution flow. Clear the error as soon as you caught it to prevent that. </li>\n<li><code>On Error Goto <Jump Label></code> resumes execution at a given label, primarily used for per-function error handlers that catch all sorts of errors.</li>\n<li><code>On Error Goto <Line Number></code> resumes at a given line number. Stay away from that, it's not useful, even dangerous.</li>\n<li><code>On Error Goto 0</code> it's close cousin. Reinstates the VBA integrated error management (message box etc.)</li>\n</ul>\n\n<hr>\n\n<p><strong>EDIT</strong></p>\n\n<p>From the edited qestion, this is my proposal to solve your problem.</p>\n\n<pre><code>For Each FieldName In FieldNames ' assuming you have some looping construct here '\n\n strsql3 = \"SELECT \" & FieldName & \" FROM table\"\n\n On Error Resume Next\n Set rs3 = CurrentDb.OpenRecordset(strsql3)\n\n If Err.Number = 3061 Then\n ' Do nothing. We dont care about this error '\n Err.Clear\n Else\n MsgBox \"Uncaught error number \" & Err.Number & \" (\" & Err.Description & \")\"\n Err.Clear\n End If\n\n On Error GoTo 0\n\nNext FieldName\n</code></pre>\n\n<p>Be sure to clear the error <em>in any case</em> before you go on with a loop in the same Sub or Function. As I said, a dangling error causes code flow to become unexpected!</p>\n"
},
{
"answer_id": 277612,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 3,
"selected": true,
"text": "<p>Rather than trapping the error, why not use the TableDefs to check for the field or use a mixture of ADO and DAO? ADO Schemas can provide a list of tables that contain the required field:</p>\n\n<pre><code>Function ListTablesContainingField()\nDim cn As New ADODB.Connection, cn2 As New ADODB.Connection\nDim rs As ADODB.Recordset, rs2 As ADODB.Recordset\nDim connString As String\nDim SelectFieldName\n\n Set cn = CurrentProject.Connection\n\n SelectFieldName = \"Fall\" 'For tksy '\n\n 'Get names of all tables that have a column called 'ID' '\n Set rs = cn.OpenSchema(adSchemaColumns, _\n Array(Empty, Empty, Empty, SelectFieldName))\n\n 'Show the tables that have been selected '\n While Not rs.EOF\n\n 'Exclude MS system tables '\n If Left(rs!Table_Name, 4) <> \"MSys\" Then\n ' Edit for tksy, who is using more than one forum '\n If tdf.Name = \"01UMWELT\" Then\n strSQL = \"Select * From 01UMWELT Where Status = 5\"\n Else\n strSQL = \"Select a.* From [\" & rs!Table_Name _\n & \"] a Inner Join 01UMWELT On a.fall = 01UMWELT.fall \" _\n & \"Where 01UMWELT.Status = 5\"\n End If\n Set rs2 = CurrentDb.OpenRecordset(strSQL)\n\n Do While Not rs2.EOF\n For i = 0 To rs2.Fields.Count - 1\n If IsNull(rs2.Fields(i)) Then\n rs2.Edit\n rs2.Fields(i) = 111111\n rs2.Update\n End If\n Next\n rs2.MoveNext\n Loop\n End If\n rs.MoveNext\n Wend\n rs.Close\n Set cn = Nothing\n\nEnd Function\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
I'm executing a query like this
```
select field from table;
```
In that query, there is a loop running on many tables. So, if the field is not present in a table I get a
>
> Runtime Error 3061
>
>
>
How can I by pass this error such as that on this error flow should go to another point?
This is the code I have recently after going through this forum.
```
Option Explicit
Private Sub UpdateNulls()
Dim rs2 As DAO.Recordset
Dim tdf As DAO.TableDef
Dim db As Database
Dim varii As Variant, strField As String
Dim strsql As String, strsql2 As String, strsql3 As String
Dim astrFields As Variant
Dim intIx As Integer
Dim field As Variant
Dim astrvalidcodes As Variant
Dim found As Boolean
Dim v As Variant
Open "C:\Documents and Settings\Desktop\testfile.txt" For Input As #1
varii = ""
Do While Not EOF(1)
Line Input #1, strField
varii = varii & "," & strField
Loop
Close #1
astrFields = Split(varii, ",") 'Element 0 empty
For intIx = 1 To UBound(astrFields)
'Function ListFieldDescriptions()
Dim cn As New ADODB.Connection, cn2 As New ADODB.Connection
Dim rs As ADODB.Recordset, rs3 As ADODB.Recordset
Dim connString As String
Dim SelectFieldName
Set cn = CurrentProject.Connection
SelectFieldName = astrFields(intIx)
Set rs = cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, Empty, SelectFieldName))
'Show the tables that have been selected '
While Not rs.EOF
'Exclude MS system tables '
If Left(rs!Table_Name, 4) <> "MSys" Then
strsql = "Select t.* From [" & rs!Table_Name & "] t Inner Join 01UMWELT On t.fall = [01UMWELT].fall Where [01UMWELT].Status = 4"
End If
Set rs3 = CurrentDb.OpenRecordset(strsql)
'End Function
strsql2 = "SELECT label.validcode FROM variablen s INNER JOIN label ON s.id=label.variablenid WHERE varname='" & astrFields(intIx) & "'"
Set db = OpenDatabase("C:\Documents and Settings\Desktop\Codebook.mdb")
Set rs2 = db.OpenRecordset(strsql2)
With rs2
.MoveLast
.MoveFirst
astrvalidcodes = rs2.GetRows(.RecordCount)
.Close '
End With
With rs3
.MoveFirst
While Not rs3.EOF
found = False
For Each v In astrvalidcodes
If v = .Fields(0) Then
found = True
Debug.Print .Fields(0)
Debug.Print .Fields(1)
Exit For
End If
Next
If Not found Then
msgbox "xxxxxxxxxxxxxxxx"
End If
End If
.MoveNext
Wend
End With
On Error GoTo 0 'End of special handling
Wend
Next intIx
End Sub
```
I'm getting a
>
> Type Mismatch Runtime Error
>
>
>
in `Set rs3 = CurrentDb.OpenRecordset(strsql)`
I guess I'm mixing up `ado` and `dao` but I'm not certainly sure where it is.
|
Rather than trapping the error, why not use the TableDefs to check for the field or use a mixture of ADO and DAO? ADO Schemas can provide a list of tables that contain the required field:
```
Function ListTablesContainingField()
Dim cn As New ADODB.Connection, cn2 As New ADODB.Connection
Dim rs As ADODB.Recordset, rs2 As ADODB.Recordset
Dim connString As String
Dim SelectFieldName
Set cn = CurrentProject.Connection
SelectFieldName = "Fall" 'For tksy '
'Get names of all tables that have a column called 'ID' '
Set rs = cn.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, Empty, SelectFieldName))
'Show the tables that have been selected '
While Not rs.EOF
'Exclude MS system tables '
If Left(rs!Table_Name, 4) <> "MSys" Then
' Edit for tksy, who is using more than one forum '
If tdf.Name = "01UMWELT" Then
strSQL = "Select * From 01UMWELT Where Status = 5"
Else
strSQL = "Select a.* From [" & rs!Table_Name _
& "] a Inner Join 01UMWELT On a.fall = 01UMWELT.fall " _
& "Where 01UMWELT.Status = 5"
End If
Set rs2 = CurrentDb.OpenRecordset(strSQL)
Do While Not rs2.EOF
For i = 0 To rs2.Fields.Count - 1
If IsNull(rs2.Fields(i)) Then
rs2.Edit
rs2.Fields(i) = 111111
rs2.Update
End If
Next
rs2.MoveNext
Loop
End If
rs.MoveNext
Wend
rs.Close
Set cn = Nothing
End Function
```
|
277,345 |
<p>I want to be able to compare Dates and Times in Rails without always having to call the to_time or to_date method. So I wrote the following code:</p>
<pre><code>class Date
def ==(other)
if other.kind_of?(Time)
self.to_time == other
else
super(other)
end
end
end
</code></pre>
<p>I know there's an easy way to write this so that I can make this work for >, <, >=, <= and <=>. But I forgot how :P Any ideas?</p>
|
[
{
"answer_id": 277520,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 0,
"selected": false,
"text": "<p>Your example looks okay, but I wouldn't use <code>kind_of?</code> - if <code>other</code> doesn't implement <code>to_time</code> you get an exception anyway!</p>\n\n<p>Update: What you are looking for is probably the <code><=></code> operator!</p>\n"
},
{
"answer_id": 277916,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 2,
"selected": false,
"text": "<p>Well, the Date and Time classes simply implement <=>, which is the normal Ruby comparison method/operator. </p>\n\n<p>See also the documentation of <a href=\"http://ruby-doc.org/core/classes/Date.html#M000685\" rel=\"nofollow noreferrer\">Date#<=></a> and <a href=\"http://ruby-doc.org/core/classes/Time.html#M000258\" rel=\"nofollow noreferrer\">Time#<=></a> .</p>\n"
},
{
"answer_id": 278073,
"author": "segy",
"author_id": 19006,
"author_profile": "https://Stackoverflow.com/users/19006",
"pm_score": 0,
"selected": false,
"text": "<p>I believe what you're asking for is already implemented using the comparison operator that the other posters have mentioned.</p>\n\n<pre><code>(segfault@megumi)(01:35)% ./script/console\nLoading development environment (Rails 2.2.0)\nirb(main):001:0> a = Date.now\nNoMethodError: private method `now' called for Date:Class\n from (irb):1\n from :0\nirb(main):002:0> a = Date.today\n => Mon, 10 Nov 2008\nirb(main):003:0> b = Time.today\n => Mon Nov 10 00:00:00 -0500 2008\nirb(main):004:0> a == b\n => nil\nirb(main):005:0> puts \"a\" if a == b\n => nil\nirb(main):006:0> puts \"a\" if a != b\n a\n => nil\nirb(main):007:0> \n</code></pre>\n"
},
{
"answer_id": 281075,
"author": "Chu Yeow",
"author_id": 25226,
"author_profile": "https://Stackoverflow.com/users/25226",
"pm_score": 4,
"selected": true,
"text": "<p>The easiest way to make any old Ruby class comparable is to implement the <=> instance method and include the <a href=\"http://www.ruby-doc.org/core/classes/Comparable.html\" rel=\"noreferrer\">Comparable</a> mixin. You'll get the >, <, >=, <=, ==, etc. methods for free then.</p>\n\n<p>One way of approaching this is to re-open the Date and Time classes to <code>include Comparable</code> and redefining their <code><=></code> methods to do the Date/Time conversions if necessary (falling back on the original <code><=></code> definition otherwise).</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11082/"
] |
I want to be able to compare Dates and Times in Rails without always having to call the to\_time or to\_date method. So I wrote the following code:
```
class Date
def ==(other)
if other.kind_of?(Time)
self.to_time == other
else
super(other)
end
end
end
```
I know there's an easy way to write this so that I can make this work for >, <, >=, <= and <=>. But I forgot how :P Any ideas?
|
The easiest way to make any old Ruby class comparable is to implement the <=> instance method and include the [Comparable](http://www.ruby-doc.org/core/classes/Comparable.html) mixin. You'll get the >, <, >=, <=, ==, etc. methods for free then.
One way of approaching this is to re-open the Date and Time classes to `include Comparable` and redefining their `<=>` methods to do the Date/Time conversions if necessary (falling back on the original `<=>` definition otherwise).
|
277,351 |
<p>What is a mathematical way of of saying 1 - 1 = 12 for a month calculation? Adding is easy, 12 + 1 % 12 = 1, but subtraction introduces 0, stuffing things up.</p>
<p>My actual requirement is x = x + d, where x must always be between 1 and 12 before and after the summing, and d any unsigned integer.</p>
|
[
{
"answer_id": 277355,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming x and y are both in the range 1-12:</p>\n\n<pre><code>((x - y + 11) % 12) + 1\n</code></pre>\n\n<p>To break this down:</p>\n\n<pre><code>// Range = [0, 22]\nx - y + 11\n\n// Range = [0, 11]\n(x - y + 11) % 12\n\n// Range = [1, 12]\n((x - y + 11) % 12) + 1\n</code></pre>\n"
},
{
"answer_id": 277359,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>You have to be careful with addition, too, since (11 + 1) % 12 = 0. Try this:</p>\n\n<pre><code>x % 12 + 1\n</code></pre>\n\n<p>This comes from using a normalisation function:</p>\n\n<pre><code>norm(x) = ((x - 1) % 12) + 1\n</code></pre>\n\n<p>Substituting,</p>\n\n<pre><code>norm(x + 1) = (((x + 1) - 1) % 12 + 1\n\nnorm(x + 1) = (x) % 12 + 1\n</code></pre>\n"
},
{
"answer_id": 277361,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>I'd work internally with a 0 based month (0-11), summing one for external consumption only (output, another calling method expecting 1-12, etc.), that way you can wrap around backwards just as easily as wrapping around forward.</p>\n\n<pre><code>>>> for i in range(15):\n... print '%d + 1 => %d' % (i, (i+1)%12)\n...\n0 + 1 => 1\n1 + 1 => 2\n2 + 1 => 3\n3 + 1 => 4\n4 + 1 => 5\n5 + 1 => 6\n6 + 1 => 7\n7 + 1 => 8\n8 + 1 => 9\n9 + 1 => 10\n10 + 1 => 11\n11 + 1 => 0\n12 + 1 => 1\n13 + 1 => 2\n14 + 1 => 3\n>>> for i in range(15):\n... print '%d - 1 => %d' % (i, (i-1)%12)\n...\n0 - 1 => 11\n1 - 1 => 0\n2 - 1 => 1\n3 - 1 => 2\n4 - 1 => 3\n5 - 1 => 4\n6 - 1 => 5\n7 - 1 => 6\n8 - 1 => 7\n9 - 1 => 8\n10 - 1 => 9\n11 - 1 => 10\n12 - 1 => 11\n13 - 1 => 0\n14 - 1 => 1\n</code></pre>\n"
},
{
"answer_id": 277370,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>The % (modulus) operator produces an answer in the range 0..(N-1) for x % N. Given that your inputs are in the range 1..N (for N = 12), the general adding code for adding a positive number y months to current month x should be:</p>\n\n<pre><code>(x + y - 1) % 12 + 1\n</code></pre>\n\n<p>When y is 1, this reduces to</p>\n\n<pre><code>x % 12 + 1\n</code></pre>\n\n<p>Subtracting is basically the same. However, there are complications with the answers produced by different implementations of the modulus operator when either (or both) of the operands is negative. If the number to be subtracted is known to be in in the range 1..N, then you can use the fact that subtracting y modulo N is the same as adding (N - y) modulo N. If y is unconstrained (but positive), then use:</p>\n\n<pre><code>(x + (12 - (y % 12) - 1) % 12 + 1\n</code></pre>\n\n<p>This double-modulo operation is a common part of the solution to problems like this when the range of the values is not under control.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
What is a mathematical way of of saying 1 - 1 = 12 for a month calculation? Adding is easy, 12 + 1 % 12 = 1, but subtraction introduces 0, stuffing things up.
My actual requirement is x = x + d, where x must always be between 1 and 12 before and after the summing, and d any unsigned integer.
|
I'd work internally with a 0 based month (0-11), summing one for external consumption only (output, another calling method expecting 1-12, etc.), that way you can wrap around backwards just as easily as wrapping around forward.
```
>>> for i in range(15):
... print '%d + 1 => %d' % (i, (i+1)%12)
...
0 + 1 => 1
1 + 1 => 2
2 + 1 => 3
3 + 1 => 4
4 + 1 => 5
5 + 1 => 6
6 + 1 => 7
7 + 1 => 8
8 + 1 => 9
9 + 1 => 10
10 + 1 => 11
11 + 1 => 0
12 + 1 => 1
13 + 1 => 2
14 + 1 => 3
>>> for i in range(15):
... print '%d - 1 => %d' % (i, (i-1)%12)
...
0 - 1 => 11
1 - 1 => 0
2 - 1 => 1
3 - 1 => 2
4 - 1 => 3
5 - 1 => 4
6 - 1 => 5
7 - 1 => 6
8 - 1 => 7
9 - 1 => 8
10 - 1 => 9
11 - 1 => 10
12 - 1 => 11
13 - 1 => 0
14 - 1 => 1
```
|
277,368 |
<p>I hate to have to ask, but I'm pretty stuck here.</p>
<p>I need to test a sequence of numbers to find the first which has over 500 factors:
<a href="http://projecteuler.net/index.php?section=problems&id=12" rel="nofollow noreferrer">http://projecteuler.net/index.php?section=problems&id=12</a></p>
<p>-At first I attempted to brute force the answer (finding a number with 480 after a LONG time)</p>
<p>-I am now looking at determining the prime factors of a number and then use them to find all other factors.</p>
<p>I am currently at the stage where I can get an array of prime factors for any number I input - i.e 300 has the prime factors 2 2 3 5 5</p>
<p>Using this array of prime factors I need to be able to calculate the remaining factors - This is the part I am stuck on. Basically, as I understand it, I need to calculate ALL possible combinations of the numbers in the array...</p>
<p>i.e
2 * 2 <br>
2 * 2 * 3 <br>
2 * 2 * 3 * 5 <br>
2 * 3 <br>
2 * 3 * 3 <br>
...and so forth - But where it gets interesting is with things like...<br>
2 * 5 <br>
2 * 3 * 5 <br>
...i.e Numbers which are not adjacent to each other in the array</p>
<p>I can't think of a way to code this in a generic fashion for any length array...</p>
<p>I need help! P.S - I am working in Java</p>
<p>EDIT: My brute force code - As it has been suggested brute forcing the problem will work and so there may be an error in my code :(</p>
<pre><code>package euler.problem12;
public class Solution {
public static void main(String[] args) {
int next = 1;
int triangle = 0;
int maxFactors = 0;
while(true) {
triangle = triangle + next;
int factors = 1;
int max = (int) triangle / 2;
for(int i = 1; i <= max; ++i) {
if(triangle % i == 0) {
factors ++;
}
}
if(factors > maxFactors) {
maxFactors = factors;
System.out.println(triangle + "\t" + factors);
}
next++;
}
}
}
</code></pre>
|
[
{
"answer_id": 277372,
"author": "Martin",
"author_id": 24364,
"author_profile": "https://Stackoverflow.com/users/24364",
"pm_score": 3,
"selected": true,
"text": "<p>As far as I can tell, question 12 doesn't mention anything about prime numbers? Is this the one you're looking at? </p>\n\n<blockquote>\n <p>The sequence of triangle numbers is generated by adding the natural numbers...</p>\n</blockquote>\n\n<p>If so, then perhaps not thinking about primes will help? ;)</p>\n"
},
{
"answer_id": 277483,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 3,
"selected": false,
"text": "<p>OK, second attempt as I was making things far too difficult.</p>\n<p>Answer is given here: <a href=\"https://web.archive.org/web/20171117010511/http://mathforum.org/library/drmath/view/57151.html\" rel=\"nofollow noreferrer\">Link</a></p>\n<blockquote>\n<p>If you factor a number into its prime\npower factors, then the total number\nof factors is found by adding one to\nall the exponents and multiplying\nthose results together. Example: 108 =\n2^2 * 3^3, so the total number of\nfactors is (2+1) * (3+1) = 3 * 4 = 12.\nSure enough, the factors of 108 are 1,\n2, 3, 4, 6, 9, 12, 18, 27, 36, 54, and\n108. This happens because to be a factor, a number must have the same\nprimes, and raised to the same or lower powers.</p>\n</blockquote>\n<p>So if you know the prime factors, you just need to count the repeated ones and use the above calculation to work out the number of factors.</p>\n"
},
{
"answer_id": 605796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Possibly 3 months too late, but here goes...</p>\n\n<p>I see that answer two has privided the function to give you the answer you require, but in answer to your original question on how you generate all the factors assuming you need to for some reason, then here's how you do it:</p>\n\n<p>Assuming that you have the factors in an array:</p>\n\n<p>int[] primeFactors = new int[] {2, 2, 3, 5, 5};</p>\n\n<p>What you need to do is recurse every in-order permutation for each possible depth, and then reduce the resulting result set to just the unique values.</p>\n\n<p>I'll explain what I mean:\n\"In-order permutation\": assuming you start at position 0 of the array, the next element must be 1, 2, 3 or 4, if you start from 1 then the next one must be 2, 3 or 4 and so on.</p>\n\n<p>\"Each possible depth\": each single factor, then any two factors, then any three factors and so on until you get to all five factors.</p>\n\n<p>\"Reduce the set\": If you take two elements, say 0&3, 0&4, 1&3 or 1&4 they all give you 2 * 5 = 10, they all provide the factor 10, so you need to winnow your set to just distinct values. (Phew, this is getting longer than I expected... :))</p>\n\n<p>The way to do this is to use two methods, one to select the maximum depth of recursion, kick off the recustion and the winnow the final results, and the other to recurse the values:</p>\n\n<pre><code>public static void main(String[] args) {\n int[] primeFactors = new int[] {2, 2, 3, 5, 5};\n List<Integer> allFactors = getAllFactors(primeFactors);\n for (int factor : allFactors) {\n System.out.println(\"Factor: \" + factor);\n }\n}\n\nprivate static List<Integer> getAllFactors(int[] primeFactors) {\n Set<Integer> distinctFactors = new HashSet<Integer>();\n for (int maxDepth = 0; maxDepth <= primeFactors.length; maxDepth++) {\n permutatPrimeFactors(0, maxDepth, 0, 1, primeFactors, distinctFactors);\n }\n List<Integer> result = new ArrayList<Integer>(distinctFactors);\n Collections.sort(result);\n return result;\n}\n\nprivate static void permutatPrimeFactors(int depth, int maxDepth, int minIndex, int valueSoFar, int[] primeFactors, Set<Integer> distinctFactors) {\n if (depth == maxDepth) {\n distinctFactors.add(valueSoFar);\n return;\n }\n\n for (int index = minIndex; index < primeFactors.length; index++) {\n permutatPrimeFactors(depth + 1, maxDepth, index + 1, valueSoFar * primeFactors[index], primeFactors, distinctFactors);\n }\n}\n</code></pre>\n\n<p>The getAllFactors uses a Set to make sure we only get distinct values, than adds them to a list and sorts that so that we can display the factors in order.</p>\n\n<p>While permutatPrimeFactors, generates from zero terms (factor = 1) though to all terms (factor = 1 * 2 * 2 *3 * 5 * 5 = 300).</p>\n\n<p>Hope that helps.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15075/"
] |
I hate to have to ask, but I'm pretty stuck here.
I need to test a sequence of numbers to find the first which has over 500 factors:
<http://projecteuler.net/index.php?section=problems&id=12>
-At first I attempted to brute force the answer (finding a number with 480 after a LONG time)
-I am now looking at determining the prime factors of a number and then use them to find all other factors.
I am currently at the stage where I can get an array of prime factors for any number I input - i.e 300 has the prime factors 2 2 3 5 5
Using this array of prime factors I need to be able to calculate the remaining factors - This is the part I am stuck on. Basically, as I understand it, I need to calculate ALL possible combinations of the numbers in the array...
i.e
2 \* 2
2 \* 2 \* 3
2 \* 2 \* 3 \* 5
2 \* 3
2 \* 3 \* 3
...and so forth - But where it gets interesting is with things like...
2 \* 5
2 \* 3 \* 5
...i.e Numbers which are not adjacent to each other in the array
I can't think of a way to code this in a generic fashion for any length array...
I need help! P.S - I am working in Java
EDIT: My brute force code - As it has been suggested brute forcing the problem will work and so there may be an error in my code :(
```
package euler.problem12;
public class Solution {
public static void main(String[] args) {
int next = 1;
int triangle = 0;
int maxFactors = 0;
while(true) {
triangle = triangle + next;
int factors = 1;
int max = (int) triangle / 2;
for(int i = 1; i <= max; ++i) {
if(triangle % i == 0) {
factors ++;
}
}
if(factors > maxFactors) {
maxFactors = factors;
System.out.println(triangle + "\t" + factors);
}
next++;
}
}
}
```
|
As far as I can tell, question 12 doesn't mention anything about prime numbers? Is this the one you're looking at?
>
> The sequence of triangle numbers is generated by adding the natural numbers...
>
>
>
If so, then perhaps not thinking about primes will help? ;)
|
277,384 |
<p>I have a little Perl script (On Windows) that checks some files for me as an aid to my day-to-day business. At the moment it prints out something like...</p>
<pre><code>0%
25%
50%
75%
Complete
</code></pre>
<p>But I can remember scripts I've used in the past that didn't print progress on a line-by-line basis, but which updated the output on the display, presumably by moving the cursor back and over-printing what was there.</p>
<p>Anyone know what magic is required? Portability isn't important to me, the script is quite disposable.</p>
|
[
{
"answer_id": 277389,
"author": "Jarod Elliott",
"author_id": 1061,
"author_profile": "https://Stackoverflow.com/users/1061",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to print a backspace character '\\b' to move the cursor back so you can overwrite what you printed previously.</p>\n"
},
{
"answer_id": 277393,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if this works in Perl, but in C/C++ you can use <pre>\\b</pre> for a backspace. Using several of those, you can move the cursor to overwrite old values.</p>\n"
},
{
"answer_id": 277398,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": true,
"text": "<p>In addition to the other answers, \\r will go back to the beginning of the current line</p>\n"
},
{
"answer_id": 277407,
"author": "daniels",
"author_id": 9789,
"author_profile": "https://Stackoverflow.com/users/9789",
"pm_score": 3,
"selected": false,
"text": "<p>You could use <a href=\"http://search.cpan.org/~mdxi/Curses-UI/lib/Curses/UI/Dialog/Progress.pm\" rel=\"nofollow noreferrer\">curses</a> and make a nice progress bar.</p>\n\n<p><strong>EDIT</strong>:\nOr do something like this:</p>\n\n<pre><code>print \"##### [ 10%]\\r\";\n# Do something\nprint \"########## [ 20%]\\r\";\n# Do something else\nprint \"############### [ 30%]\\r\";\n# Do some more\n# ...\n# ...\n# ...\nprint \"##################################### [100%]\\n\";\nprint \"Done.\\n\";\n</code></pre>\n"
},
{
"answer_id": 277689,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "<p>If you ever need to do something in Perl, it's very likely that someone has done it and uploaded it to CPAN. Look at some of the modules with <a href=\"http://search.cpan.org/search?query=progress&mode=all\" rel=\"noreferrer\">\"progress\" in their name</a>.</p>\n"
},
{
"answer_id": 277692,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 3,
"selected": false,
"text": "<p>You might be interested in <a href=\"http://metacpan.org/pod/Smart::Comments\" rel=\"nofollow noreferrer\">Smart Comments</a>. This would be probably easier than coding Your own progress bars.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
] |
I have a little Perl script (On Windows) that checks some files for me as an aid to my day-to-day business. At the moment it prints out something like...
```
0%
25%
50%
75%
Complete
```
But I can remember scripts I've used in the past that didn't print progress on a line-by-line basis, but which updated the output on the display, presumably by moving the cursor back and over-printing what was there.
Anyone know what magic is required? Portability isn't important to me, the script is quite disposable.
|
In addition to the other answers, \r will go back to the beginning of the current line
|
277,409 |
<p>I want to store a list of the following tuples in a compressed format and I was wondering which algorithm gives me</p>
<ul>
<li>smallest compressed size</li>
<li>fastest de/compression</li>
<li>tradeoff optimum ("knee" of the tradeoff curve)</li>
</ul>
<p>My data looks like this:</p>
<pre><code>(<int>, <int>, <double>),
(<int>, <int>, <double>),
...
(<int>, <int>, <double>)
</code></pre>
<p>One of the two ints refers to a point in time and it's very likely that the numbers ending up in one list are close to each other. The other int represents an abstract id and the values are less likely to be close, although they aren't going to be completely random, either. The double is representing a sensor reading and while there is some correlation between the values, it's probably not of much use.</p>
|
[
{
"answer_id": 277434,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 3,
"selected": true,
"text": "<p>Since the \"time\" ints can be close to each other, try to only store the first and after that save the difference to the int before (delta-coding). You can try the same for the second int, too.</p>\n\n<p>Another thing you can try is to reorganize the data from [int1, int2, double], [int1, int2, double]... to [int1, int1...], [int2, int2...], [double, double...].</p>\n\n<p>To find out the compression range your result will be in, you can write your data into a file and download the compressor CCM from Christian Martelock <a href=\"http://lovepimple.110mb.com/compressors/ccm130c.zip\" rel=\"nofollow noreferrer\">here</a>. I found out that it performs very well for such data collections. It uses a quite fast <a href=\"http://en.wikipedia.org/wiki/Context_mixing\" rel=\"nofollow noreferrer\">context mixing</a> algorithm. You can also compare it to other compressors like WinZIP or use a compression library like zLib to see if it is worth the effort.</p>\n"
},
{
"answer_id": 277441,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading the question correctly, you simply want to store the data efficiently. Obviously simple options like compressed xml are simple, but there are more direct binary serialization methods. One the leaps to mind is Google's <a href=\"http://code.google.com/p/protobuf/\" rel=\"nofollow noreferrer\">protocol buffers</a>.</p>\n\n<p>For example, in C# with <a href=\"http://code.google.com/p/protobuf-net/\" rel=\"nofollow noreferrer\">protobuf-net</a>, you can simply create a class to hold the data:</p>\n\n<pre><code>[ProtoContract]\npublic class Foo {\n [ProtoMember(1)]\n public int Value1 {get;set;}\n [ProtoMember(2)]\n public int Value2 {get;set;}\n [ProtoMember(3)]\n public double Value3 {get;set;}\n}\n</code></pre>\n\n<p>Then just [de]serialize a List or Foo[] etc, via the ProtoBuf.Serializer class.</p>\n\n<p>I'm not claiming it will be <em>quite</em> as space-efficient as rolling your own, but it'll be pretty darned close. The protocol buffer spec makes fairly good use of space (for example, using base-128 for integers, such that small numbers take less space). But it would be simple to try it out, without having to write all the serialization code yourself.</p>\n\n<p>This approach, as well as being simple to implement, also has the advantage of being simple to use from other architectures, since there are protocol buffers implementations for <a href=\"http://code.google.com/p/protobuf/wiki/OtherLanguages\" rel=\"nofollow noreferrer\">various languages</a>. It also uses much less CPU than regular [de]compression (GZip/DEFLATE/etc), and/or xml-based serialization.</p>\n"
},
{
"answer_id": 277450,
"author": "Stephan Leclercq",
"author_id": 34838,
"author_profile": "https://Stackoverflow.com/users/34838",
"pm_score": 2,
"selected": false,
"text": "<p>Most compression algorithms will work equally bad on such data. However, there are a few things (\"preprocessing\") that you can do to increase the compressibility of the data before feeding it to a gzip or deflate like algorithm. Try the following:</p>\n\n<p>First, if possible, sort the tuples in ascending order. Use the abstract ID first, then the timestamp. Assuming you have many readings from the same sensor, similar ids will be placed close together.</p>\n\n<p>Next, if the measures are taken at regular intervals, replace the timestamp with the difference from the previous timestamp (except for the very first tuple for a sensor, of course.) For example, if all measures are taken at 5 minutes intervals, the delta between two timestamps will usually be close to 300 seconds. The timestamp field will therefore be much more compressible, as most values are equal.</p>\n\n<p>Then, assuming that the measured values are stable in time, replace all readings with a delta from the previous reading for the same sensor. Again, most values will be close to zero, and thus more compressible.</p>\n\n<p>Also, floating point values are very bad candidates for compression, due to their internal representation. Try to convert them to an integer. For example, temperature readings most likely do not require more than two decimal digits. Multiply values by 100 and round to the nearest integer.</p>\n"
},
{
"answer_id": 277460,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a common scheme used in most search engines: store deltas of values and encode the delta using a variable byte encoding scheme, i.e. if the delta is less than 128, it can be encoded with only 1 byte. See vint in Lucene and Protocol buffers for details.</p>\n\n<p>This will not give you the best compression ratio but usually the fastest for encoding/decoding throughput. </p>\n"
},
{
"answer_id": 277545,
"author": "Gilles",
"author_id": 36141,
"author_profile": "https://Stackoverflow.com/users/36141",
"pm_score": 2,
"selected": false,
"text": "<p>Sort as already proposed, then store</p>\n\n<p>(first ints)\n(second ints)\n(doubles)</p>\n\n<p>transposed matrix. Then compressed</p>\n"
},
{
"answer_id": 277559,
"author": "Hanno Fietz",
"author_id": 2077,
"author_profile": "https://Stackoverflow.com/users/2077",
"pm_score": 0,
"selected": false,
"text": "<p>Great answers, for the record, I'm going to merge those I upvoted into the approach I'm finally using:</p>\n\n<ol>\n<li><p>Sort and reorganize the data so that similar numbers are next to each other, i. e. sort by id first, then by timestamp and rearrange from <code>(<int1>, <int2>, <double>), ...</code> to <code>([<int1>, <int1> ...], [<int2>, <int2> ... ], [<double>, <double> ...])</code> (as suggested by \n<a href=\"https://stackoverflow.com/questions/277409/best-compression-algorithm-see-below-for-definition-of-best#277434\">schnaader</a> and <a href=\"https://stackoverflow.com/questions/277409/best-compression-algorithm-see-below-for-definition-of-best#277450\">Stephan Leclercq</a></p></li>\n<li><p>Use delta-encoding on the timestamps (and maybe on the other values) as suggested by <a href=\"https://stackoverflow.com/questions/277409/best-compression-algorithm-see-below-for-definition-of-best#277434\">schnaader</a> and <a href=\"https://stackoverflow.com/questions/277409/best-compression-algorithm-see-below-for-definition-of-best#277460\">ididak</a></p></li>\n<li><p>Use protocol buffers to serialize (I'm going to use them anyway in the application, so that's not going to add dependencies or anything). Thanks to <a href=\"https://stackoverflow.com/questions/277409/best-compression-algorithm-see-below-for-definition-of-best#277441\">Marc Gravell</a> for pointing me to it.</p></li>\n</ol>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
I want to store a list of the following tuples in a compressed format and I was wondering which algorithm gives me
* smallest compressed size
* fastest de/compression
* tradeoff optimum ("knee" of the tradeoff curve)
My data looks like this:
```
(<int>, <int>, <double>),
(<int>, <int>, <double>),
...
(<int>, <int>, <double>)
```
One of the two ints refers to a point in time and it's very likely that the numbers ending up in one list are close to each other. The other int represents an abstract id and the values are less likely to be close, although they aren't going to be completely random, either. The double is representing a sensor reading and while there is some correlation between the values, it's probably not of much use.
|
Since the "time" ints can be close to each other, try to only store the first and after that save the difference to the int before (delta-coding). You can try the same for the second int, too.
Another thing you can try is to reorganize the data from [int1, int2, double], [int1, int2, double]... to [int1, int1...], [int2, int2...], [double, double...].
To find out the compression range your result will be in, you can write your data into a file and download the compressor CCM from Christian Martelock [here](http://lovepimple.110mb.com/compressors/ccm130c.zip). I found out that it performs very well for such data collections. It uses a quite fast [context mixing](http://en.wikipedia.org/wiki/Context_mixing) algorithm. You can also compare it to other compressors like WinZIP or use a compression library like zLib to see if it is worth the effort.
|
277,423 |
<p>Does anybody know how I can see the actual machine code that <a href="http://code.google.com/p/v8/" rel="noreferrer">v8</a> generates from Javascript? I've gotten as far as <code>Script::Compile()</code> in <code>src/api.cc</code> but I can't figure out where to go from there.</p>
|
[
{
"answer_id": 277807,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 1,
"selected": false,
"text": "<p>You're on the right track, I think.</p>\n\n<p>It looks like you need to get from Script::Compile to Compiler::Compile, which will lead you to the code generators (codegen*.cc and .h).</p>\n\n<p>All of this to say that, looking at codegen-ia32.cc, if you define ENABLE_DISASSEMBLER\nwhen you build, your disassembly should get printed, I think.</p>\n\n<p>Of course, all of this is just from a quick browse of an old copy of the source I have here, so YMMV, but I think this should work.</p>\n\n<p>(Looking at your post again, I see you're looking for the machine language, not the assembler -- I'm not sure, but you might have to modify the logic if you want the assembled code output rather than its disassembly)</p>\n"
},
{
"answer_id": 1197559,
"author": "sstock",
"author_id": 58926,
"author_profile": "https://Stackoverflow.com/users/58926",
"pm_score": 4,
"selected": false,
"text": "<p>I don't know how to invoke the disassembler from C++ code, but there is a quick-and-dirty way to get a disassembly from the shell.</p>\n\n<p>First, compile v8 with disassembler support:</p>\n\n<pre><code>scons [your v8 build options here] disassembler=on sample=shell\n</code></pre>\n\n<p>Now you can invoke the shell with the \"--print_code\" option:</p>\n\n<pre><code>./shell --print_code hello.js\n</code></pre>\n\n<p>Which should give you something like this:</p>\n\n<pre><code>--- Raw source ---\nprint(\"hello world\");\n\n--- Code ---\nkind = FUNCTION\nInstructions (size = 134)\n0x2ad0a77ceea0 0 55 push rbp\n0x2ad0a77ceea1 1 488bec REX.W movq rbp,rsp\n0x2ad0a77ceea4 4 56 push rsi\n0x2ad0a77ceea5 5 57 push rdi\n0x2ad0a77ceea6 6 49ba59c13da9d02a0000 REX.W movq r10,0x2ad0a93dc159 ;; object: 0xa93dc159 <undefined>\n0x2ad0a77ceeb0 16 4952 REX.W push r10\n0x2ad0a77ceeb2 18 49ba688b700000000000 REX.W movq r10,0x708b68\n0x2ad0a77ceebc 28 493b22 REX.W cmpq rsp,[r10]\n0x2ad0a77ceebf 31 0f824e000000 jc 115 (0x2ad0a77cef13)\n0x2ad0a77ceec5 37 488b462f REX.W movq rax,[rsi+0x2f]\n0x2ad0a77ceec9 41 4883ec18 REX.W subq rsp,0xlx\n0x2ad0a77ceecd 45 49ba094b3ea9d02a0000 REX.W movq r10,0x2ad0a93e4b09 ;; object: 0xa93e4b09 <String[5]: print>\n0x2ad0a77ceed7 55 4c8955e0 REX.W movq [rbp-0x20],r10\n0x2ad0a77ceedb 59 488945d8 REX.W movq [rbp-0x28],rax\n0x2ad0a77ceedf 63 49ba014d3ea9d02a0000 REX.W movq r10,0x2ad0a93e4d01 ;; object: 0xa93e4d01 <String[11]: hello world>\n0x2ad0a77ceee9 73 4c8955d0 REX.W movq [rbp-0x30],r10\n0x2ad0a77ceeed 77 49baa06c7ba7d02a0000 REX.W movq r10,0x2ad0a77b6ca0 ;; debug: statement 0\n ;; code: contextual, CALL_IC, UNINITIALIZED, argc = 1\n0x2ad0a77ceef7 87 49ffd2 REX.W call r10\n0x2ad0a77ceefa 90 488b75f8 REX.W movq rsi,[rbp-0x8]\n0x2ad0a77ceefe 94 4883c408 REX.W addq rsp,0xlx\n0x2ad0a77cef02 98 488945e8 REX.W movq [rbp-0x18],rax\n0x2ad0a77cef06 102 488be5 REX.W movq rsp,rbp ;; js return\n0x2ad0a77cef09 105 5d pop rbp\n0x2ad0a77cef0a 106 c20800 ret 0x8\n0x2ad0a77cef0d 109 cc int3\n0x2ad0a77cef0e 110 cc int3\n0x2ad0a77cef0f 111 cc int3\n0x2ad0a77cef10 112 cc int3\n0x2ad0a77cef11 113 cc int3\n0x2ad0a77cef12 114 cc int3\n0x2ad0a77cef13 115 49ba60657ba7d02a0000 REX.W movq r10,0x2ad0a77b6560 ;; code: STUB, StackCheck, minor: 0\n0x2ad0a77cef1d 125 49ffd2 REX.W call r10\n0x2ad0a77cef20 128 488b7df0 REX.W movq rdi,[rbp-0x10]\n0x2ad0a77cef24 132 eb9f jmp 37 (0x2ad0a77ceec5)\n\nRelocInfo (size = 10)\n0x2ad0a77ceea8 embedded object (0xa93dc159 <undefined>)\n0x2ad0a77ceecf embedded object (0xa93e4b09 <String[5]: print>)\n0x2ad0a77ceee1 embedded object (0xa93e4d01 <String[11]: hello world>)\n0x2ad0a77ceeed statement position (0)\n0x2ad0a77ceeef code target (context) (CALL_IC) (0x2ad0a77b6ca0)\n0x2ad0a77cef06 js return\n0x2ad0a77cef15 code target (STUB) (0x2ad0a77b6560)\n\nhello world\n</code></pre>\n\n<p>Your output will vary, of course. The above is from the v8 trunk compiled for Linux x64.</p>\n"
},
{
"answer_id": 22960151,
"author": "Diego Pino",
"author_id": 134758,
"author_profile": "https://Stackoverflow.com/users/134758",
"pm_score": 3,
"selected": false,
"text": "<p>You need to build v8 with disassembler support.</p>\n\n<p>Download v8 source code.</p>\n\n<pre><code>git clone https://chromium.googlesource.com/v8/v8.git\n</code></pre>\n\n<p>Build with disassembler support.</p>\n\n<pre><code>make dependencies\nmake ia32.release objectprint=on disassembler=on\n</code></pre>\n\n<p>Call d8 (v8 shell) using certain flags, depending on what you want.</p>\n\n<pre><code>out/ia32.release/d8 --code-comments --print-code <app.js>\n</code></pre>\n\n<p>For reference:</p>\n\n<ul>\n<li><em>--code-comments</em>: includes code comments.</li>\n<li><em>--print-code</em>: prints out code to <em>stdout</em>.</li>\n<li><em>--print-code-stubs</em>: prints code stubs.</li>\n<li><em>--print-opt-code</em>: prints optimized code.</li>\n<li><em>--trace-hydrogen</em>: prints IR (intermediate representation) code to hydrogen.cfg. This file can be opened with <a href=\"https://java.net/projects/c1visualizer/downloads\" rel=\"noreferrer\">Java's C1Visualizer</a>.</li>\n</ul>\n"
},
{
"answer_id": 29607938,
"author": "coder23",
"author_id": 2167962,
"author_profile": "https://Stackoverflow.com/users/2167962",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at <code>v8_root/build/features.gypi</code>, and you will find disassembler related and many other compile time feature switches for V8.</p>\n"
},
{
"answer_id": 46511251,
"author": "Manjeet",
"author_id": 1513779,
"author_profile": "https://Stackoverflow.com/users/1513779",
"pm_score": 3,
"selected": false,
"text": "<p>Try with NodeJS or Chrome:</p>\n<ol>\n<li><code>-print-opt-code</code>: Code generated by optimizing compiler.</li>\n<li><code>-print-bytecode</code>: Byte code generated by interpreter.</li>\n<li><code>-trace-opt</code> and <code>-trace-deopt</code> : which functions are (de)optimized.</li>\n</ol>\n<p>Check this article by @Franziska Hinkelmann :</p>\n<p><a href=\"https://medium.com/dailyjs/understanding-v8s-bytecode-317d46c94775\" rel=\"nofollow noreferrer\">https://medium.com/dailyjs/understanding-v8s-bytecode-317d46c94775</a></p>\n<p>Additionally you can also try</p>\n<p><code>D8</code>: It will help you compile <code>V8</code> and view the assembly code generated from JavaScript.</p>\n<p>For usage and details:</p>\n<p><a href=\"http://www.mattzeunert.com/2015/08/19/viewing-assembly-code-generated-by-v8.html\" rel=\"nofollow noreferrer\">http://www.mattzeunert.com/2015/08/19/viewing-assembly-code-generated-by-v8.html</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36128/"
] |
Does anybody know how I can see the actual machine code that [v8](http://code.google.com/p/v8/) generates from Javascript? I've gotten as far as `Script::Compile()` in `src/api.cc` but I can't figure out where to go from there.
|
I don't know how to invoke the disassembler from C++ code, but there is a quick-and-dirty way to get a disassembly from the shell.
First, compile v8 with disassembler support:
```
scons [your v8 build options here] disassembler=on sample=shell
```
Now you can invoke the shell with the "--print\_code" option:
```
./shell --print_code hello.js
```
Which should give you something like this:
```
--- Raw source ---
print("hello world");
--- Code ---
kind = FUNCTION
Instructions (size = 134)
0x2ad0a77ceea0 0 55 push rbp
0x2ad0a77ceea1 1 488bec REX.W movq rbp,rsp
0x2ad0a77ceea4 4 56 push rsi
0x2ad0a77ceea5 5 57 push rdi
0x2ad0a77ceea6 6 49ba59c13da9d02a0000 REX.W movq r10,0x2ad0a93dc159 ;; object: 0xa93dc159 <undefined>
0x2ad0a77ceeb0 16 4952 REX.W push r10
0x2ad0a77ceeb2 18 49ba688b700000000000 REX.W movq r10,0x708b68
0x2ad0a77ceebc 28 493b22 REX.W cmpq rsp,[r10]
0x2ad0a77ceebf 31 0f824e000000 jc 115 (0x2ad0a77cef13)
0x2ad0a77ceec5 37 488b462f REX.W movq rax,[rsi+0x2f]
0x2ad0a77ceec9 41 4883ec18 REX.W subq rsp,0xlx
0x2ad0a77ceecd 45 49ba094b3ea9d02a0000 REX.W movq r10,0x2ad0a93e4b09 ;; object: 0xa93e4b09 <String[5]: print>
0x2ad0a77ceed7 55 4c8955e0 REX.W movq [rbp-0x20],r10
0x2ad0a77ceedb 59 488945d8 REX.W movq [rbp-0x28],rax
0x2ad0a77ceedf 63 49ba014d3ea9d02a0000 REX.W movq r10,0x2ad0a93e4d01 ;; object: 0xa93e4d01 <String[11]: hello world>
0x2ad0a77ceee9 73 4c8955d0 REX.W movq [rbp-0x30],r10
0x2ad0a77ceeed 77 49baa06c7ba7d02a0000 REX.W movq r10,0x2ad0a77b6ca0 ;; debug: statement 0
;; code: contextual, CALL_IC, UNINITIALIZED, argc = 1
0x2ad0a77ceef7 87 49ffd2 REX.W call r10
0x2ad0a77ceefa 90 488b75f8 REX.W movq rsi,[rbp-0x8]
0x2ad0a77ceefe 94 4883c408 REX.W addq rsp,0xlx
0x2ad0a77cef02 98 488945e8 REX.W movq [rbp-0x18],rax
0x2ad0a77cef06 102 488be5 REX.W movq rsp,rbp ;; js return
0x2ad0a77cef09 105 5d pop rbp
0x2ad0a77cef0a 106 c20800 ret 0x8
0x2ad0a77cef0d 109 cc int3
0x2ad0a77cef0e 110 cc int3
0x2ad0a77cef0f 111 cc int3
0x2ad0a77cef10 112 cc int3
0x2ad0a77cef11 113 cc int3
0x2ad0a77cef12 114 cc int3
0x2ad0a77cef13 115 49ba60657ba7d02a0000 REX.W movq r10,0x2ad0a77b6560 ;; code: STUB, StackCheck, minor: 0
0x2ad0a77cef1d 125 49ffd2 REX.W call r10
0x2ad0a77cef20 128 488b7df0 REX.W movq rdi,[rbp-0x10]
0x2ad0a77cef24 132 eb9f jmp 37 (0x2ad0a77ceec5)
RelocInfo (size = 10)
0x2ad0a77ceea8 embedded object (0xa93dc159 <undefined>)
0x2ad0a77ceecf embedded object (0xa93e4b09 <String[5]: print>)
0x2ad0a77ceee1 embedded object (0xa93e4d01 <String[11]: hello world>)
0x2ad0a77ceeed statement position (0)
0x2ad0a77ceeef code target (context) (CALL_IC) (0x2ad0a77b6ca0)
0x2ad0a77cef06 js return
0x2ad0a77cef15 code target (STUB) (0x2ad0a77b6560)
hello world
```
Your output will vary, of course. The above is from the v8 trunk compiled for Linux x64.
|
277,431 |
<p>I have huge number of Word files I need to merge (join) into one file, and will be time consuming to use the Word merger (one by one). Have you experienced any tool that can handle this job?</p>
|
[
{
"answer_id": 277433,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using the Word COM api? You can automate lots of things - maybe you can automate a merge.</p>\n\n<p>Do you really need to do an actual merge, or do you want to join the files together. The two things are quite different.</p>\n\n<p>Merging is used when you have two versions of an original file with (potentially conflicting) changes. I can't really see how you would have a \"huge number\" of files that you needed to merge all together. This would be an absolute nightmare of conflicts. Do you mean to merge sets of them into individual files?</p>\n\n<p>Joining would be when you want to concatenate them one after the other. This would be a lot easier to do. This is quite possible using the COM api.</p>\n"
},
{
"answer_id": 277449,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": "<p>I came across a post by Graham Skan a while back. It might get you started:</p>\n\n<pre><code>Sub InsertFiles()\n Dim strFileName As String\n Dim rng As Range\n Dim Doc As Document\n Const strPath = \"C:\\Documents and Settings\\Graham Skan\\My Documents\\Allwork\\\" 'adjust as necessary '\"\n\n Set Doc = Documents.Add\n strFileName = Dir$(strPath & \"\\*.doc\")\n Do\n Set rng = Doc.Bookmarks(\"\\EndOfDoc\").Range\n If rng.End > 0 Then 'section break not necessary before first document.'\n rng.InsertBreak wdSectionBreakNextPage\n rng.Collapse wdCollapseEnd\n End If\n rng.InsertFile strPath & \"\\\" & strFileName\n strFileName = Dir$()\n Loop Until strFileName = \"\"\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 277470,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "<pre class=\"lang-vb prettyprint-override\"><code>Sub MergeAllDocuments(AllDocumentsPath as String, MasterDocumentPath as String)\n Dim MasterDocument As Document\n\n Set MasterDocument = Documents.Open(FileName:=MasterDocumentPath)\n\n TheDocumentPath = Dir(AllDocumentsPath , vbNormal)\n While TheDocumentPath <> \"\"\n ' Append the next doc to the end of the master doc. (The \n ' special \"\\EndOfDoc\" bookmark is always available!)\n MasterDocument.Bookmarks(\"\\EndOfDoc\").Range.InsertFile TheDocumentPath\n TheDocumentPath = Dir\n Wend\n\n MasterDocument.Save\nEnd Sub\n\nMergeAllDocuments \"C:\\MySeparateDocuments\\*.doc\", \"C:\\MasterDocument.doc\"\n</code></pre>\n\n<p>I have one question - why do you want do do such a thing (with a \"huge number\" of documents, at least)?</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1233512/"
] |
I have huge number of Word files I need to merge (join) into one file, and will be time consuming to use the Word merger (one by one). Have you experienced any tool that can handle this job?
|
```vb
Sub MergeAllDocuments(AllDocumentsPath as String, MasterDocumentPath as String)
Dim MasterDocument As Document
Set MasterDocument = Documents.Open(FileName:=MasterDocumentPath)
TheDocumentPath = Dir(AllDocumentsPath , vbNormal)
While TheDocumentPath <> ""
' Append the next doc to the end of the master doc. (The
' special "\EndOfDoc" bookmark is always available!)
MasterDocument.Bookmarks("\EndOfDoc").Range.InsertFile TheDocumentPath
TheDocumentPath = Dir
Wend
MasterDocument.Save
End Sub
MergeAllDocuments "C:\MySeparateDocuments\*.doc", "C:\MasterDocument.doc"
```
I have one question - why do you want do do such a thing (with a "huge number" of documents, at least)?
|
277,437 |
<p>This has got to be something simple: I set up a frames page with two possible sources for the target frame based on a form with two options. I used the OnClick event to trap the user's click to show the appropriate page. It works fine in Internet Explorer 7, swapping the two source pages. FireFox 3 and Chrome show only the default source.</p>
<p>HEAD Script section:</p>
<pre><code>function SwapInlineFrameSource()
{
var rsRadio, rsiFrame;
rsRadio=document.getElementById('County');
rsiFrame=document.getElementById('RatesFrame')
if (rsRadio.checked===true) {
rsiFrame.src="SantaCruzRates.htm";
}
else {
rsiFrame.src="DelNorteRates.htm";
}
}
</code></pre>
<p>BODY Form section (commented to show up here):</p>
<pre><code><input type="radio" value="SC" checked name="County" onclick="SwapInlineFrameSource()">
Santa Cruz
<input type="radio" value="DN" name="County" onclick="SwapInlineFrameSource()" >
Del Norte
</code></pre>
<p>What am I missing? (Live example: <a href="http://www.raintrees.com/rates.html" rel="nofollow noreferrer">http://www.raintrees.com/rates.html</a>)</p>
<p>Thanks!</p>
<p>mr</p>
|
[
{
"answer_id": 277451,
"author": "Jack Ryan",
"author_id": 28882,
"author_profile": "https://Stackoverflow.com/users/28882",
"pm_score": 0,
"selected": false,
"text": "<p>I don't believe that getElementById works on frames in firefox. I have always used the frames[\"frameID\"], which seems to work more consistently.</p>\n"
},
{
"answer_id": 277456,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 2,
"selected": false,
"text": "<p>Your code is wrong....</p>\n\n<pre><code>var rsRadio, rsiFrame;\nrsRadio=document.getElementById('County');\nrsiFrame=document.getElementById('RatesFrame')\nif (rsRadio.checked===true) {\n</code></pre>\n\n<p>I assume you mean getElementsByName and not ID becasue you don't have an ID of county on those radio buttons.</p>\n\n<p>In fact you need to determine which radio button is checked so you could some thing like (assuming there are only ever the 2 options)</p>\n\n<pre><code>if(document.getElementsByName()[0].checked){\n // show Santa Cruz Rates\n}else{\n // show other rates\n}\n</code></pre>\n"
},
{
"answer_id": 277458,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 4,
"selected": true,
"text": "<p>You are using getElementByID, but you aren't specifying IDs for your inputs. Perhaps consider this instead:</p>\n\n<pre><code>function SwapInlineFrameSource(rdoButton)\n{\n rsiFrame = document.getElementById(\"RatesFrame\");\n rsiFrame.src = rdoButton.value;\n}\n\n<input type=\"radio\" value=\"SantaCruzRates.htm\" checked=\"checked\" name=\"County\" onClick=\"SwapInlineFrameSource(this);\">Santa Cruz</input>\n<input type=\"radio\" value=\"DelNorteRates.htm\" name=\"County\" onClick=\"SwapInlineFrameSource(this);\">Del Norte</input>\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3125/"
] |
This has got to be something simple: I set up a frames page with two possible sources for the target frame based on a form with two options. I used the OnClick event to trap the user's click to show the appropriate page. It works fine in Internet Explorer 7, swapping the two source pages. FireFox 3 and Chrome show only the default source.
HEAD Script section:
```
function SwapInlineFrameSource()
{
var rsRadio, rsiFrame;
rsRadio=document.getElementById('County');
rsiFrame=document.getElementById('RatesFrame')
if (rsRadio.checked===true) {
rsiFrame.src="SantaCruzRates.htm";
}
else {
rsiFrame.src="DelNorteRates.htm";
}
}
```
BODY Form section (commented to show up here):
```
<input type="radio" value="SC" checked name="County" onclick="SwapInlineFrameSource()">
Santa Cruz
<input type="radio" value="DN" name="County" onclick="SwapInlineFrameSource()" >
Del Norte
```
What am I missing? (Live example: <http://www.raintrees.com/rates.html>)
Thanks!
mr
|
You are using getElementByID, but you aren't specifying IDs for your inputs. Perhaps consider this instead:
```
function SwapInlineFrameSource(rdoButton)
{
rsiFrame = document.getElementById("RatesFrame");
rsiFrame.src = rdoButton.value;
}
<input type="radio" value="SantaCruzRates.htm" checked="checked" name="County" onClick="SwapInlineFrameSource(this);">Santa Cruz</input>
<input type="radio" value="DelNorteRates.htm" name="County" onClick="SwapInlineFrameSource(this);">Del Norte</input>
```
|
277,438 |
<p>Generally, I like to keep an application completely ignorant of the IoC container. However I have ran into problems where I needed to access it. To abstract away the pain I use a basic Singleton. Before you run for the hills or pull out the shotgun, let me go over my solution. Basically, the IoC singleton does absolutly nothing, it simply delegates to an internal interface that must be passed in. I've found this makes working with the Singleton less painful.</p>
<p>Below is the IoC wrapper:</p>
<pre><code>public static class IoC
{
private static IDependencyResolver inner;
public static void InitWith(IDependencyResolver container)
{
inner = container;
}
/// <exception cref="InvalidOperationException">Container has not been initialized. Please supply an instance if IWindsorContainer.</exception>
public static T Resolve<T>()
{
if ( inner == null)
throw new InvalidOperationException("Container has not been initialized. Please supply an instance if IWindsorContainer.");
return inner.Resolve<T>();
}
public static T[] ResolveAll<T>()
{
return inner.ResolveAll<T>();
}
}
</code></pre>
<p>IDependencyResolver:</p>
<pre><code>public interface IDependencyResolver
{
T Resolve<T>();
T[] ResolveAll<T>();
}
</code></pre>
<p>I've had great success so far with the few times I've used it (maybe once every few projects, I really prefer not having to use this at all) as I can inject anything I want: Castle, a Stub, fakes, etc.</p>
<p>Is this a slippery road? Am I going to run into potential issues down the road? </p>
|
[
{
"answer_id": 277554,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 2,
"selected": false,
"text": "<p>That's not really a singleton class. That's a static class with static members. And yes that seems a good approach. </p>\n\n<p>I think JP Boodhoo even has a name for this pattern. <a href=\"http://codebetter.com/jpboodhoo/2007/10/15/the-static-gateway-pattern\" rel=\"nofollow noreferrer\">The Static Gateway pattern</a>.</p>\n"
},
{
"answer_id": 279663,
"author": "Craig Wilson",
"author_id": 25333,
"author_profile": "https://Stackoverflow.com/users/25333",
"pm_score": 2,
"selected": false,
"text": "<p>Just a note: Microsoft Patterns and Practices has created a common service locator (<a href=\"http://www.codeplex.com/CommonServiceLocator\" rel=\"nofollow noreferrer\">http://www.codeplex.com/CommonServiceLocator</a>) that most of the major IoC containers will be implementing in the near future. You can begin to use it instead of your IDependencyResolver.</p>\n\n<p>BTW: this is the common way to solve your problem and it works quite well.</p>\n"
},
{
"answer_id": 286702,
"author": "Julian Birch",
"author_id": 29408,
"author_profile": "https://Stackoverflow.com/users/29408",
"pm_score": 3,
"selected": true,
"text": "<p>I've seen that even Ayende implements this pattern in the Rhino Commons code, but I'd advise against using it wherever possible. There's a reason Castle Windsor doesn't have this code by default. StructureMap does, but Jeremy Miller has been moving away from it. Ideally, you should regard the container itself with as much suspicion as any global variable.</p>\n\n<p>However, as an alternative, you could always configure your container to resolve IDependencyResolver as a reference to your container. This may sound crazy, but it's significantly more flexible. Just remember the rule of thumb that an object should call \"new\" or perform processing, but not both. For \"call new\" replace with \"resolve a reference\".</p>\n"
},
{
"answer_id": 17361858,
"author": "jgauffin",
"author_id": 70386,
"author_profile": "https://Stackoverflow.com/users/70386",
"pm_score": 1,
"selected": false,
"text": "<p>It all depends on the usage. Using the container like that is called the Service Locator Pattern. There are cases where it's not a good fit and cases where it do apply.</p>\n\n<p>If you google \"service locator pattern\" you'll see a lot of blog posts saying that it's an anti-pattern, which it's not. The pattern has simply been overused (/abused).</p>\n\n<p>For typical line of business applications you should not use SL as you hide the dependencies. You also got another problem: You can not manage state/lifetime if you use the root container (instead of one of it's lifetimes).</p>\n\n<p>Service locator is a good fit when it comes to infrastructure. For instance ASP.NET MVC uses Service Locator to be able to resolve all dependencies for each controller.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
] |
Generally, I like to keep an application completely ignorant of the IoC container. However I have ran into problems where I needed to access it. To abstract away the pain I use a basic Singleton. Before you run for the hills or pull out the shotgun, let me go over my solution. Basically, the IoC singleton does absolutly nothing, it simply delegates to an internal interface that must be passed in. I've found this makes working with the Singleton less painful.
Below is the IoC wrapper:
```
public static class IoC
{
private static IDependencyResolver inner;
public static void InitWith(IDependencyResolver container)
{
inner = container;
}
/// <exception cref="InvalidOperationException">Container has not been initialized. Please supply an instance if IWindsorContainer.</exception>
public static T Resolve<T>()
{
if ( inner == null)
throw new InvalidOperationException("Container has not been initialized. Please supply an instance if IWindsorContainer.");
return inner.Resolve<T>();
}
public static T[] ResolveAll<T>()
{
return inner.ResolveAll<T>();
}
}
```
IDependencyResolver:
```
public interface IDependencyResolver
{
T Resolve<T>();
T[] ResolveAll<T>();
}
```
I've had great success so far with the few times I've used it (maybe once every few projects, I really prefer not having to use this at all) as I can inject anything I want: Castle, a Stub, fakes, etc.
Is this a slippery road? Am I going to run into potential issues down the road?
|
I've seen that even Ayende implements this pattern in the Rhino Commons code, but I'd advise against using it wherever possible. There's a reason Castle Windsor doesn't have this code by default. StructureMap does, but Jeremy Miller has been moving away from it. Ideally, you should regard the container itself with as much suspicion as any global variable.
However, as an alternative, you could always configure your container to resolve IDependencyResolver as a reference to your container. This may sound crazy, but it's significantly more flexible. Just remember the rule of thumb that an object should call "new" or perform processing, but not both. For "call new" replace with "resolve a reference".
|
277,485 |
<p>In Python, if I do this:</p>
<pre><code>print "4" * 4
</code></pre>
<p>I get</p>
<pre><code>> "4444"
</code></pre>
<p>In Perl, I'd get</p>
<pre><code>> 16
</code></pre>
<p>Is there an easy way to do the former in Perl?</p>
|
[
{
"answer_id": 277489,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 8,
"selected": true,
"text": "<pre><code>$ perl -e 'print "4" x 4; print "\\n"'\n4444\n</code></pre>\n<p>The x operator is documented in perldoc <a href=\"http://perldoc.perl.org/perlop.html\" rel=\"noreferrer\">perlop</a>. Here binary means an operator taking two arguments, not composed of bits, by the way.</p>\n<blockquote>\n<p>Binary "x" is the repetition operator. In scalar context or if the\nleft operand is not enclosed in parentheses, it returns a string consisting\nof the left operand repeated the number of times specified by the right\noperand. In list context, if the left operand is enclosed in parentheses\nor is a list formed by "<code>qw/STRING/</code>", it repeats the list. If the right\noperand is zero or negative, it returns an empty string or an empty\nlist, depending on the context.</p>\n</blockquote>\n<pre><code> print '-' x 80; # Print row of dashes\n\n print "\\t" x ($tab/8), ' ' x ($tab%8); # Tab over\n\n @ones = (1) x 80; # A list of 80 1’s\n @ones = (5) x @ones; # Set all elements to 5\n</code></pre>\n<p><code>perl -e</code> is meant to execute Perl code from the command line:</p>\n<pre>\n$ perl --help\nUsage: perl [switches] [--] [programfile] [arguments]\n \n -e program one line of program (several -e's allowed, omit programfile)\n</pre>\n"
},
{
"answer_id": 277496,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 4,
"selected": false,
"text": "<p>It's very similar in Perl</p>\n\n<pre><code>print \"4\" x 4;\n</code></pre>\n"
},
{
"answer_id": 277662,
"author": "bart",
"author_id": 19966,
"author_profile": "https://Stackoverflow.com/users/19966",
"pm_score": 6,
"selected": false,
"text": "<p>In Perl, you want to use the \"x\" operator.</p>\n\n<p>Note the difference between</p>\n\n<pre><code>\"4\" x 4\n</code></pre>\n\n<p>and</p>\n\n<pre><code>(\"4\") x 4\n</code></pre>\n\n<p>The former produces a repeated string:</p>\n\n<pre><code>\"4444\"\n</code></pre>\n\n<p>the latter a repeated list:</p>\n\n<pre><code>(\"4\", \"4\", \"4\", \"4\")\n</code></pre>\n"
},
{
"answer_id": 277831,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 4,
"selected": false,
"text": "<p>FWIW, it’s also <code>print 4 x 4</code> in Perl.</p>\n\n<p>In general, in Perl, operators are monomorphic, ie. you have different sets of operators for string semantics, for numeric semantics, for bitwise semantics, etc., where it makes sense, and the type of the operands largely doesn’t matter. When you apply a numeric operator to a string, the string is converted to a number first and you get the operation you asked for (eg. multiplication), and when you apply a string operator to a number, it’s turned into a string and you get the operation you asked for (eg. repetition). Perl pays attention to the operator first and the types of the operands only second – if indeed it pays them any mind at all.</p>\n\n<p>This is the opposite of Python and most other languages, where you use one set of operators, and the types of the operands determine which semantics you’ll actually get – ie. operators are polymorphic.</p>\n"
},
{
"answer_id": 30100928,
"author": "Wolf",
"author_id": 2932052,
"author_profile": "https://Stackoverflow.com/users/2932052",
"pm_score": 2,
"selected": false,
"text": "<p>All answers, given so far, missed mentioning that the operator <code>x</code> does not only work on string <em>literals</em>, but also on variables that <em>are</em> strings or expressions that <em>evaluate</em> to strings like</p>\n<pre><code>use feature 'say';\n\nmy $msg = "hello ";\nsay $msg x 2;\nsay chr(33) x 3;\n</code></pre>\n<p>like this</p>\n<pre class=\"lang-none prettyprint-override\"><code>hello hello\n!!!\n</code></pre>\n<p>and, <strong>even more important</strong>, <code>x</code> does an <strong>automatic conversion</strong> of expressions into strings if they aren't already (thanks to <a href=\"https://stackoverflow.com/posts/30100928/timeline#comment_125504067\">ggorlen</a> for pointing me into that direction!). So for example</p>\n<pre><code>say 4 x 2;\nsay [$msg] x 2;\n</code></pre>\n<p>will result in something like the following as output</p>\n<pre class=\"lang-none prettyprint-override\"><code>44\nARRAY(0x30ca10)ARRAY(0x30ca10)\n</code></pre>\n"
},
{
"answer_id": 44756518,
"author": "Charlotte Russell",
"author_id": 7949710,
"author_profile": "https://Stackoverflow.com/users/7949710",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to print 10 character \"A\"s, you can also do this</p>\n\n<pre><code>perl -e 'print \"A\" x 10'; echo\n</code></pre>\n\n<p>Example with output</p>\n\n<pre><code>user@linux:~$ perl -e 'print \"A\" x 10'; echo\nAAAAAAAAAA\nuser@linux:~$ \n</code></pre>\n"
},
{
"answer_id": 74252643,
"author": "Clarius",
"author_id": 4470510,
"author_profile": "https://Stackoverflow.com/users/4470510",
"pm_score": 0,
"selected": false,
"text": "<p>Came this way looking for an answer. Didn't quite find what I was looking for so I thought I'd share my learning. I wanted to compose dynamic SQL CRUD statements with the appropriate number of placeholders.</p>\n<pre><code>$table = "ORDERS";\n\n@fields = ("ORDER_ID", "SALESMAN_ID", "CUSTOMER_ID", "ORDER_DATE", "STATUS");\n\n$sql = "INSERT INTO $table (" . join(',', @fields) . ') VALUES (' . '?,' x (@fields - 1) . '?)';\n\nprint $sql;\n</code></pre>\n<p>The output looks like this...</p>\n<pre><code>INSERT INTO ORDERS (ORDER_ID,SALESMAN_ID,CUSTOMER_ID,ORDER_DATE,STATUS) VALUES (?,?,?,?,?)\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
] |
In Python, if I do this:
```
print "4" * 4
```
I get
```
> "4444"
```
In Perl, I'd get
```
> 16
```
Is there an easy way to do the former in Perl?
|
```
$ perl -e 'print "4" x 4; print "\n"'
4444
```
The x operator is documented in perldoc [perlop](http://perldoc.perl.org/perlop.html). Here binary means an operator taking two arguments, not composed of bits, by the way.
>
> Binary "x" is the repetition operator. In scalar context or if the
> left operand is not enclosed in parentheses, it returns a string consisting
> of the left operand repeated the number of times specified by the right
> operand. In list context, if the left operand is enclosed in parentheses
> or is a list formed by "`qw/STRING/`", it repeats the list. If the right
> operand is zero or negative, it returns an empty string or an empty
> list, depending on the context.
>
>
>
```
print '-' x 80; # Print row of dashes
print "\t" x ($tab/8), ' ' x ($tab%8); # Tab over
@ones = (1) x 80; # A list of 80 1’s
@ones = (5) x @ones; # Set all elements to 5
```
`perl -e` is meant to execute Perl code from the command line:
```
$ perl --help
Usage: perl [switches] [--] [programfile] [arguments]
-e program one line of program (several -e's allowed, omit programfile)
```
|
277,492 |
<p>In a database, I have a string that contains "default" written in it. I just want to replace that default with 0. I have something like: </p>
<pre><code>select * from tblname where test = 'default'
</code></pre>
<p>I do not want quotes in the replacement for "default".</p>
<p>I want </p>
<pre><code>select * from tblname where test = 0
</code></pre>
<p>is there any way to do this?</p>
|
[
{
"answer_id": 277503,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 0,
"selected": false,
"text": "<p>I think you would be better using format strings</p>\n\n<pre><code>string myVar = \"0\";\nstring sql = String.Format(@\"select * from tblname where test = \\\"{0}\\\"\", myVar);\n</code></pre>\n\n<p>You should also ask yourself why you are generating inline SQL on the fly and not using stored procedures as this is how SQL injection attacks can occur unless you sanitize the input.</p>\n"
},
{
"answer_id": 277507,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming the field <code>test</code> is of a text type (varchar, char, or the like).</p>\n\n<p>First: Update the table to contain '0' where it contains 'default'.</p>\n\n<pre><code>UPDATE tblname SET test = '0' WHERE test = 'default'\n</code></pre>\n\n<p>Then: Select all rows with '0' in them. You can't leave off the quotes, because they are part of the SQL syntax.</p>\n\n<pre><code>SELECT * FROM tblname WHERE test = '0'\n</code></pre>\n\n<p>To be able to leave off the quotes, you must turn the field into a numeric one (int, float or the like).</p>\n"
},
{
"answer_id": 277535,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>There are a number of things you can do in order to effect a simple string replacement;, however, I strongly suggest that you look into parameterization, to provide both injection safety and query-plan re-use.</p>\n\n<p>Parameters also benefit by avoiding the quote issue - so just replace <code>'default'</code> with (for example) <code>@p1</code> and you're sorted. This replace can be:</p>\n\n<pre><code>-- TSQL\nREPLACE(@cmd, '''default''', '@p1')\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// C#\n.Replace(@\"'default'\", @\"@p1\")\n</code></pre>\n\n<p>From C#, this would a <code>DbCommand</code> with parameters; from T-SQL you might consider <code>sp_ExecuteSQL</code>. Either way, you'd want to end up with:</p>\n\n<pre><code>select * from tblname where test = @p1\n</code></pre>\n\n<p>And supply @p1 as the parameter. So from C#:</p>\n\n<pre><code>DbParameter param = cmd.CreateParameter();\nparam.Value = 0; // etc\ncmd.Parameters.Add(param);\n</code></pre>\n\n<p>Or from TSQL:</p>\n\n<pre><code>EXEC sp_ExecuteSQL @cmd, N'@p1 varchar(50)', 0\n</code></pre>\n\n<p>(replace <code>varchar(50)</code> with the correct type)</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In a database, I have a string that contains "default" written in it. I just want to replace that default with 0. I have something like:
```
select * from tblname where test = 'default'
```
I do not want quotes in the replacement for "default".
I want
```
select * from tblname where test = 0
```
is there any way to do this?
|
I'm assuming the field `test` is of a text type (varchar, char, or the like).
First: Update the table to contain '0' where it contains 'default'.
```
UPDATE tblname SET test = '0' WHERE test = 'default'
```
Then: Select all rows with '0' in them. You can't leave off the quotes, because they are part of the SQL syntax.
```
SELECT * FROM tblname WHERE test = '0'
```
To be able to leave off the quotes, you must turn the field into a numeric one (int, float or the like).
|
277,494 |
<p>I am trying to let a piece of runtime state decide WHICH implementation of an interface to use, preferably solely by autowiring. </p>
<p>I have tried making an object factory for the interface thet uses dynamic proxies, and I used qualifiers to coerce the @Autowired injections to use the factory. The qualifiers are necessary because both the factory and the implementations respond to the same interface.</p>
<p>The problem with this is that I end up annotating every @Autowired reference with the @Qualifier. What I'd really want to do is annotate the non-factory implementations with something like @NotCandidateForAutowiringByInterface (my fantasy annotation), or even better make spring prefer the single un-qualified bean when injecting to an un-qualified field </p>
<p>I may thinking along the totally wrong lines here, so alternate suggestions are welcome.
Anyone know how to make this happen ?</p>
|
[
{
"answer_id": 277503,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 0,
"selected": false,
"text": "<p>I think you would be better using format strings</p>\n\n<pre><code>string myVar = \"0\";\nstring sql = String.Format(@\"select * from tblname where test = \\\"{0}\\\"\", myVar);\n</code></pre>\n\n<p>You should also ask yourself why you are generating inline SQL on the fly and not using stored procedures as this is how SQL injection attacks can occur unless you sanitize the input.</p>\n"
},
{
"answer_id": 277507,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming the field <code>test</code> is of a text type (varchar, char, or the like).</p>\n\n<p>First: Update the table to contain '0' where it contains 'default'.</p>\n\n<pre><code>UPDATE tblname SET test = '0' WHERE test = 'default'\n</code></pre>\n\n<p>Then: Select all rows with '0' in them. You can't leave off the quotes, because they are part of the SQL syntax.</p>\n\n<pre><code>SELECT * FROM tblname WHERE test = '0'\n</code></pre>\n\n<p>To be able to leave off the quotes, you must turn the field into a numeric one (int, float or the like).</p>\n"
},
{
"answer_id": 277535,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>There are a number of things you can do in order to effect a simple string replacement;, however, I strongly suggest that you look into parameterization, to provide both injection safety and query-plan re-use.</p>\n\n<p>Parameters also benefit by avoiding the quote issue - so just replace <code>'default'</code> with (for example) <code>@p1</code> and you're sorted. This replace can be:</p>\n\n<pre><code>-- TSQL\nREPLACE(@cmd, '''default''', '@p1')\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// C#\n.Replace(@\"'default'\", @\"@p1\")\n</code></pre>\n\n<p>From C#, this would a <code>DbCommand</code> with parameters; from T-SQL you might consider <code>sp_ExecuteSQL</code>. Either way, you'd want to end up with:</p>\n\n<pre><code>select * from tblname where test = @p1\n</code></pre>\n\n<p>And supply @p1 as the parameter. So from C#:</p>\n\n<pre><code>DbParameter param = cmd.CreateParameter();\nparam.Value = 0; // etc\ncmd.Parameters.Add(param);\n</code></pre>\n\n<p>Or from TSQL:</p>\n\n<pre><code>EXEC sp_ExecuteSQL @cmd, N'@p1 varchar(50)', 0\n</code></pre>\n\n<p>(replace <code>varchar(50)</code> with the correct type)</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
I am trying to let a piece of runtime state decide WHICH implementation of an interface to use, preferably solely by autowiring.
I have tried making an object factory for the interface thet uses dynamic proxies, and I used qualifiers to coerce the @Autowired injections to use the factory. The qualifiers are necessary because both the factory and the implementations respond to the same interface.
The problem with this is that I end up annotating every @Autowired reference with the @Qualifier. What I'd really want to do is annotate the non-factory implementations with something like @NotCandidateForAutowiringByInterface (my fantasy annotation), or even better make spring prefer the single un-qualified bean when injecting to an un-qualified field
I may thinking along the totally wrong lines here, so alternate suggestions are welcome.
Anyone know how to make this happen ?
|
I'm assuming the field `test` is of a text type (varchar, char, or the like).
First: Update the table to contain '0' where it contains 'default'.
```
UPDATE tblname SET test = '0' WHERE test = 'default'
```
Then: Select all rows with '0' in them. You can't leave off the quotes, because they are part of the SQL syntax.
```
SELECT * FROM tblname WHERE test = '0'
```
To be able to leave off the quotes, you must turn the field into a numeric one (int, float or the like).
|
277,502 |
<p>My schema specifies a namespace, but the documents don't. What's the simplest way to ignore namespace during JAXB unmarshalling (XML -> object)?</p>
<p>In other words, I have</p>
<pre><code><foo><bar></bar></foo>
</code></pre>
<p>instead of,</p>
<pre><code><foo xmlns="http://tempuri.org/"><bar></bar></foo>
</code></pre>
|
[
{
"answer_id": 277512,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "<p>I believe you must <a href=\"https://download.oracle.com/javaee-archive/jaxb.java.net/users/2008/05/7860.html\" rel=\"nofollow noreferrer\">add the namespace</a> to your xml document, with, for example, the use of a <a href=\"https://web.archive.org/web/20090113211510/http://www.digitalkarate.net/?p=63\" rel=\"nofollow noreferrer\">SAX filter</a>.</p>\n\n<p>That means:</p>\n\n<ul>\n<li>Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.</li>\n<li>Define a XMLReader which will set the content handler</li>\n</ul>\n\n<p>then link the two together:</p>\n\n<pre><code>public static Object unmarshallWithFilter(Unmarshaller unmarshaller,\njava.io.File source) throws FileNotFoundException, JAXBException \n{\n FileReader fr = null;\n try {\n fr = new FileReader(source);\n XMLReader reader = new NamespaceFilterXMLReader();\n InputSource is = new InputSource(fr);\n SAXSource ss = new SAXSource(reader, is);\n return unmarshaller.unmarshal(ss);\n } catch (SAXException e) {\n //not technically a jaxb exception, but close enough\n throw new JAXBException(e);\n } catch (ParserConfigurationException e) {\n //not technically a jaxb exception, but close enough\n throw new JAXBException(e);\n } finally {\n FileUtil.close(fr); //replace with this some safe close method you have\n }\n}\n</code></pre>\n"
},
{
"answer_id": 326140,
"author": "mafro",
"author_id": 1562,
"author_profile": "https://Stackoverflow.com/users/1562",
"pm_score": 1,
"selected": false,
"text": "<p>Another way to add a default namespace to an XML Document before feeding it to JAXB is to use <a href=\"http://jdom.org\" rel=\"nofollow noreferrer\">JDom</a>:</p>\n\n<ol>\n<li>Parse XML to a Document</li>\n<li>Iterate through and set namespace on all Elements</li>\n<li>Unmarshall using a JDOMSource</li>\n</ol>\n\n<p>Like this:</p>\n\n<pre><code>public class XMLObjectFactory {\n private static Namespace DEFAULT_NS = Namespace.getNamespace(\"http://tempuri.org/\");\n\n public static Object createObject(InputStream in) {\n try {\n SAXBuilder sb = new SAXBuilder(false);\n Document doc = sb.build(in);\n setNamespace(doc.getRootElement(), DEFAULT_NS, true);\n Source src = new JDOMSource(doc);\n JAXBContext context = JAXBContext.newInstance(\"org.tempuri\");\n Unmarshaller unmarshaller = context.createUnmarshaller();\n JAXBElement root = unmarshaller.unmarshal(src);\n return root.getValue();\n } catch (Exception e) {\n throw new RuntimeException(\"Failed to create Object\", e);\n }\n }\n\n private static void setNamespace(Element elem, Namespace ns, boolean recurse) {\n elem.setNamespace(ns);\n if (recurse) {\n for (Object o : elem.getChildren()) {\n setNamespace((Element) o, ns, recurse);\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 2148541,
"author": "Kristofer",
"author_id": 259485,
"author_profile": "https://Stackoverflow.com/users/259485",
"pm_score": 7,
"selected": false,
"text": "<p>Here is an extension/edit of VonCs solution just in case someone doesn´t want to go through the hassle of implementing their own filter to do this. It also shows how to output a JAXB element without the namespace present. This is all accomplished using a SAX Filter.</p>\n\n<p>Filter implementation:</p>\n\n<pre><code>import org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport org.xml.sax.helpers.XMLFilterImpl;\n\npublic class NamespaceFilter extends XMLFilterImpl {\n\n private String usedNamespaceUri;\n private boolean addNamespace;\n\n //State variable\n private boolean addedNamespace = false;\n\n public NamespaceFilter(String namespaceUri,\n boolean addNamespace) {\n super();\n\n if (addNamespace)\n this.usedNamespaceUri = namespaceUri;\n else \n this.usedNamespaceUri = \"\";\n this.addNamespace = addNamespace;\n }\n\n\n\n @Override\n public void startDocument() throws SAXException {\n super.startDocument();\n if (addNamespace) {\n startControlledPrefixMapping();\n }\n }\n\n\n\n @Override\n public void startElement(String arg0, String arg1, String arg2,\n Attributes arg3) throws SAXException {\n\n super.startElement(this.usedNamespaceUri, arg1, arg2, arg3);\n }\n\n @Override\n public void endElement(String arg0, String arg1, String arg2)\n throws SAXException {\n\n super.endElement(this.usedNamespaceUri, arg1, arg2);\n }\n\n @Override\n public void startPrefixMapping(String prefix, String url)\n throws SAXException {\n\n\n if (addNamespace) {\n this.startControlledPrefixMapping();\n } else {\n //Remove the namespace, i.e. don´t call startPrefixMapping for parent!\n }\n\n }\n\n private void startControlledPrefixMapping() throws SAXException {\n\n if (this.addNamespace && !this.addedNamespace) {\n //We should add namespace since it is set and has not yet been done.\n super.startPrefixMapping(\"\", this.usedNamespaceUri);\n\n //Make sure we dont do it twice\n this.addedNamespace = true;\n }\n }\n\n}\n</code></pre>\n\n<p>This filter is designed to both be able to add the namespace if it is not present:</p>\n\n<pre><code>new NamespaceFilter(\"http://www.example.com/namespaceurl\", true);\n</code></pre>\n\n<p>and to remove any present namespace:</p>\n\n<pre><code>new NamespaceFilter(null, false);\n</code></pre>\n\n<p>The filter can be used during parsing as follows:</p>\n\n<pre><code>//Prepare JAXB objects\nJAXBContext jc = JAXBContext.newInstance(\"jaxb.package\");\nUnmarshaller u = jc.createUnmarshaller();\n\n//Create an XMLReader to use with our filter\nXMLReader reader = XMLReaderFactory.createXMLReader();\n\n//Create the filter (to add namespace) and set the xmlReader as its parent.\nNamespaceFilter inFilter = new NamespaceFilter(\"http://www.example.com/namespaceurl\", true);\ninFilter.setParent(reader);\n\n//Prepare the input, in this case a java.io.File (output)\nInputSource is = new InputSource(new FileInputStream(output));\n\n//Create a SAXSource specifying the filter\nSAXSource source = new SAXSource(inFilter, is);\n\n//Do unmarshalling\nObject myJaxbObject = u.unmarshal(source);\n</code></pre>\n\n<p>To use this filter to output XML from a JAXB object, have a look at the code below.</p>\n\n<pre><code>//Prepare JAXB objects\nJAXBContext jc = JAXBContext.newInstance(\"jaxb.package\");\nMarshaller m = jc.createMarshaller();\n\n//Define an output file\nFile output = new File(\"test.xml\");\n\n//Create a filter that will remove the xmlns attribute \nNamespaceFilter outFilter = new NamespaceFilter(null, false);\n\n//Do some formatting, this is obviously optional and may effect performance\nOutputFormat format = new OutputFormat();\nformat.setIndent(true);\nformat.setNewlines(true);\n\n//Create a new org.dom4j.io.XMLWriter that will serve as the \n//ContentHandler for our filter.\nXMLWriter writer = new XMLWriter(new FileOutputStream(output), format);\n\n//Attach the writer to the filter \noutFilter.setContentHandler(writer);\n\n//Tell JAXB to marshall to the filter which in turn will call the writer\nm.marshal(myJaxbObject, outFilter);\n</code></pre>\n\n<p>This will hopefully help someone since I spent a day doing this and almost gave up twice ;)</p>\n"
},
{
"answer_id": 13762119,
"author": "Henrique",
"author_id": 1620589,
"author_profile": "https://Stackoverflow.com/users/1620589",
"pm_score": 2,
"selected": false,
"text": "<p>In my situation, I have many namespaces and after some debug I find another solution just changing the NamespaceFitler class. For my situation (just unmarshall) this work fine.</p>\n\n<pre><code> import javax.xml.namespace.QName;\n import org.xml.sax.Attributes;\n import org.xml.sax.ContentHandler;\n import org.xml.sax.SAXException;\n import org.xml.sax.helpers.XMLFilterImpl;\n import com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector;\n\n public class NamespaceFilter extends XMLFilterImpl {\n private SAXConnector saxConnector;\n\n @Override\n public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {\n if(saxConnector != null) {\n Collection<QName> expected = saxConnector.getContext().getCurrentExpectedElements();\n for(QName expectedQname : expected) {\n if(localName.equals(expectedQname.getLocalPart())) {\n super.startElement(expectedQname.getNamespaceURI(), localName, qName, atts);\n return;\n }\n }\n }\n super.startElement(uri, localName, qName, atts);\n }\n\n @Override\n public void setContentHandler(ContentHandler handler) {\n super.setContentHandler(handler);\n if(handler instanceof SAXConnector) {\n saxConnector = (SAXConnector) handler;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24387115,
"author": "lunicon",
"author_id": 602719,
"author_profile": "https://Stackoverflow.com/users/602719",
"pm_score": 5,
"selected": false,
"text": "<p>I have encoding problems with XMLFilter solution, so I made XMLStreamReader to ignore namespaces:</p>\n\n<pre><code>class XMLReaderWithoutNamespace extends StreamReaderDelegate {\n public XMLReaderWithoutNamespace(XMLStreamReader reader) {\n super(reader);\n }\n @Override\n public String getAttributeNamespace(int arg0) {\n return \"\";\n }\n @Override\n public String getNamespaceURI() {\n return \"\";\n }\n}\n\nInputStream is = new FileInputStream(name);\nXMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);\nXMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);\nUnmarshaller um = jc.createUnmarshaller();\nObject res = um.unmarshal(xr);\n</code></pre>\n"
},
{
"answer_id": 64441436,
"author": "tomorrow",
"author_id": 3519572,
"author_profile": "https://Stackoverflow.com/users/3519572",
"pm_score": 0,
"selected": false,
"text": "<p>This is just a modification of lunicon's answer (<a href=\"https://stackoverflow.com/a/24387115/3519572\">https://stackoverflow.com/a/24387115/3519572</a>) if you want to replace one namespace for another during parsing. And if you want to see what exactly is going on, just uncomment the output lines and set a breakpoint.</p>\n<pre><code>public class XMLReaderWithNamespaceCorrection extends StreamReaderDelegate {\n\n private final String wrongNamespace;\n private final String correctNamespace;\n\n public XMLReaderWithNamespaceCorrection(XMLStreamReader reader, String wrongNamespace, String correctNamespace) {\n super(reader);\n\n this.wrongNamespace = wrongNamespace;\n this.correctNamespace = correctNamespace;\n }\n\n @Override\n public String getAttributeNamespace(int arg0) {\n// System.out.println("--------------------------\\n");\n// System.out.println("arg0: " + arg0);\n// System.out.println("getAttributeName: " + getAttributeName(arg0));\n// System.out.println("super.getAttributeNamespace: " + super.getAttributeNamespace(arg0));\n// System.out.println("getAttributeLocalName: " + getAttributeLocalName(arg0));\n// System.out.println("getAttributeType: " + getAttributeType(arg0));\n// System.out.println("getAttributeValue: " + getAttributeValue(arg0));\n// System.out.println("getAttributeValue(correctNamespace, LN):"\n// + getAttributeValue(correctNamespace, getAttributeLocalName(arg0)));\n// System.out.println("getAttributeValue(wrongNamespace, LN):"\n// + getAttributeValue(wrongNamespace, getAttributeLocalName(arg0)));\n\n String origNamespace = super.getAttributeNamespace(arg0);\n\n boolean replace = (((wrongNamespace == null) && (origNamespace == null))\n || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));\n return replace ? correctNamespace : origNamespace;\n }\n\n @Override\n public String getNamespaceURI() {\n// System.out.println("getNamespaceCount(): " + getNamespaceCount());\n// for (int i = 0; i < getNamespaceCount(); i++) {\n// System.out.println(i + ": " + getNamespacePrefix(i));\n// }\n//\n// System.out.println("super.getNamespaceURI: " + super.getNamespaceURI());\n\n String origNamespace = super.getNamespaceURI();\n\n boolean replace = (((wrongNamespace == null) && (origNamespace == null))\n || ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));\n return replace ? correctNamespace : origNamespace;\n }\n}\n</code></pre>\n<p>usage:</p>\n<pre><code>InputStream is = new FileInputStream(xmlFile);\nXMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);\nXMLReaderWithNamespaceCorrection xr =\n new XMLReaderWithNamespaceCorrection(xsr, "http://wrong.namespace.uri", "http://correct.namespace.uri");\nrootJaxbElem = (JAXBElement<SqgRootType>) um.unmarshal(xr);\nhandleSchemaError(rootJaxbElem, pmRes);\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
My schema specifies a namespace, but the documents don't. What's the simplest way to ignore namespace during JAXB unmarshalling (XML -> object)?
In other words, I have
```
<foo><bar></bar></foo>
```
instead of,
```
<foo xmlns="http://tempuri.org/"><bar></bar></foo>
```
|
I believe you must [add the namespace](https://download.oracle.com/javaee-archive/jaxb.java.net/users/2008/05/7860.html) to your xml document, with, for example, the use of a [SAX filter](https://web.archive.org/web/20090113211510/http://www.digitalkarate.net/?p=63).
That means:
* Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
* Define a XMLReader which will set the content handler
then link the two together:
```
public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException
{
FileReader fr = null;
try {
fr = new FileReader(source);
XMLReader reader = new NamespaceFilterXMLReader();
InputSource is = new InputSource(fr);
SAXSource ss = new SAXSource(reader, is);
return unmarshaller.unmarshal(ss);
} catch (SAXException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} catch (ParserConfigurationException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} finally {
FileUtil.close(fr); //replace with this some safe close method you have
}
}
```
|
277,529 |
<p>I’m currently using the OpenNETCF.Desktop.Communication.dll to copy files from my desktop to a CE device, but I keep getting an error:</p>
<p>‘Could not create remote file’ </p>
<p>My development environment is VS2005 (VB.NET)</p>
<p>My code:</p>
<pre><code>ObjRapi.Connect()
ObjRapi.CopyFileToDevice("C:\results.txt", "\results.txt")
ObjRapi.Dispose()
ObjRapi.Disconnect()
</code></pre>
<p>Has anyone run into this and did you manage to get around it. </p>
<p>Thanks</p>
|
[
{
"answer_id": 277548,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 2,
"selected": true,
"text": "<p>I have run into this once before but I can't really remember what was causing it.</p>\n\n<p>The only thing I can think of from looking at your code is this line:</p>\n\n<pre><code>ObjRapi.CopyFileToDevice(\"C:\\results.txt\", \"\\ \\results.txt\") \n</code></pre>\n\n<p>I'm not sure but you could try and change the destination path to something different. Something like this:</p>\n\n<pre><code>ObjRapi.CopyFileToDevice(\"C:\\results.txt\", \"\\My Documents\\results.txt\")\n</code></pre>\n\n<p>I can't really test this at the moment but I really don't see why it wouldn't work.</p>\n\n<p>EDIT: I just had a look at some code that I have writen using the RAPI,when I do any copying my line looks like this:</p>\n\n<pre><code>ObjRapi.CopyFileToDevice(\"C:\\results.txt\", \"\\My Documents\\results.txt\",True)\n</code></pre>\n\n<p>The boolean on the end is an overwrite switch, setting that to true may work.</p>\n"
},
{
"answer_id": 313401,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>try this</p>\n\n<p>Dim myrapi As New RAPI</p>\n\n<pre><code> If myrapi.DevicePresent = True Then\n myrapi.Connect()\n\n If myrapi.Connected = True Then\n Windows.Forms.Cursor.Current = Cursors.WaitCursor\n If myrapi.DeviceFileExists(\"\\Backup\\stock.txt\") Then\n myrapi.CopyFileFromDevice(Application.StartupPath \n\n Windows.Forms.Cursor.Current = Cursors.Default\n MessageBox.Show(\"File Copied Successfully\", \"Success\", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)\n\n Else\n MessageBox.Show(\"Please Connect to the Mobile Device\", \"Connection Failed\", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)\n End If\n\n Else\n MessageBox.Show(\"Please Connect to the Mobile Device\", \"Connection Failed\", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)\n End If\n\n Catch ex As Exception\n MsgBox(ex.Message)\n End Try\n</code></pre>\n"
},
{
"answer_id": 2498533,
"author": "Suraj Namdeo",
"author_id": 299733,
"author_profile": "https://Stackoverflow.com/users/299733",
"pm_score": -1,
"selected": false,
"text": "<p>You have to use the following code:</p>\n\n<pre><code>op.CopyFileToDevice(@\"C:\\results.txt\", @\"\\Temp\\results.txt\");\n</code></pre>\n\n<p>In your code you are not mentioning the path where you want to copy the file.</p>\n\n<p>Hope this will help you.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731/"
] |
I’m currently using the OpenNETCF.Desktop.Communication.dll to copy files from my desktop to a CE device, but I keep getting an error:
‘Could not create remote file’
My development environment is VS2005 (VB.NET)
My code:
```
ObjRapi.Connect()
ObjRapi.CopyFileToDevice("C:\results.txt", "\results.txt")
ObjRapi.Dispose()
ObjRapi.Disconnect()
```
Has anyone run into this and did you manage to get around it.
Thanks
|
I have run into this once before but I can't really remember what was causing it.
The only thing I can think of from looking at your code is this line:
```
ObjRapi.CopyFileToDevice("C:\results.txt", "\ \results.txt")
```
I'm not sure but you could try and change the destination path to something different. Something like this:
```
ObjRapi.CopyFileToDevice("C:\results.txt", "\My Documents\results.txt")
```
I can't really test this at the moment but I really don't see why it wouldn't work.
EDIT: I just had a look at some code that I have writen using the RAPI,when I do any copying my line looks like this:
```
ObjRapi.CopyFileToDevice("C:\results.txt", "\My Documents\results.txt",True)
```
The boolean on the end is an overwrite switch, setting that to true may work.
|
277,544 |
<p>Is there a simple way to <strong>set the focus</strong> (input cursor) of a web page <strong>on the first input element</strong> (textbox, dropdownlist, ...) on loading the page without having to know the id of the element?</p>
<p>I would like to implement it as a common script for all my pages/forms of my web application.</p>
|
[
{
"answer_id": 277555,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 3,
"selected": false,
"text": "<p>There's a write-up here that may be of use: <a href=\"http://www.codeproject.com/KB/scripting/FocusFirstInput.aspx\" rel=\"noreferrer\">Set Focus to First Input on Web Page</a></p>\n"
},
{
"answer_id": 277561,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 5,
"selected": false,
"text": "<pre><code>document.forms[0].elements[0].focus();\n</code></pre>\n\n<p>This can be refined using a loop to eg. not focus certain types of field, disabled fields and so on. Better may be to add a class=\"autofocus\" to the field you actually <em>do</em> want focused, and loop over forms[i].elements[j] looking for that className.</p>\n\n<p>Anyhow: it's not normally a good idea to do this on every page. When you focus an input the user loses the ability to eg. scroll the page from the keyboard. If unexpected, this can be annoying, so only auto-focus when you're pretty sure that using the form field is going to be what the user wants to do. ie. if you're Google.</p>\n"
},
{
"answer_id": 277615,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 3,
"selected": false,
"text": "<p>You also need to skip any hidden inputs.</p>\n\n<pre><code>for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);\ndocument.forms[0].elements[i].focus();\n</code></pre>\n"
},
{
"answer_id": 277642,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using the <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototype</a> JavaScript framework then you can use the <a href=\"http://prototypejs.org/doc/latest/dom/Form/focusFirstElement/\" rel=\"nofollow noreferrer\">focusFirstElement</a> method:</p>\n\n<pre><code>Form.focusFirstElement(document.forms[0]);\n</code></pre>\n"
},
{
"answer_id": 277802,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 2,
"selected": false,
"text": "<p>Putting this code at the end of your <code>body</code> tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.</p>\n\n<pre><code><script>\n (function(){\n var forms = document.forms || [];\n for(var i = 0; i < forms.length; i++){\n for(var j = 0; j < forms[i].length; j++){\n if(!forms[i][j].readonly != undefined && forms[i][j].type != \"hidden\" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){\n forms[i][j].focus();\n return;\n }\n }\n }\n })();\n</script>\n</code></pre>\n"
},
{
"answer_id": 279153,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 8,
"selected": true,
"text": "<p>You can also try jQuery based method:</p>\n\n<pre><code>$(document).ready(function() {\n $('form:first *:input[type!=hidden]:first').focus();\n});\n</code></pre>\n"
},
{
"answer_id": 2744824,
"author": "ngeek",
"author_id": 267001,
"author_profile": "https://Stackoverflow.com/users/267001",
"pm_score": 4,
"selected": false,
"text": "<p>The most comprehensive jQuery expression I found working is (through the help of over <a href=\"http://www.gerd-riesselmann.net/development/focus-first-form-field-with-jquery\" rel=\"noreferrer\">here</a>)</p>\n\n<pre><code>$(document).ready(function() {\n $('input:visible:enabled:first').focus();\n});\n</code></pre>\n"
},
{
"answer_id": 6446374,
"author": "Jacob Stanley",
"author_id": 72821,
"author_profile": "https://Stackoverflow.com/users/72821",
"pm_score": 7,
"selected": false,
"text": "<p>Although this doesn't answer the question (requiring a common script), I though it might be useful for others to know that HTML5 introduces the 'autofocus' attribute:</p>\n\n<pre><code><form>\n <input type=\"text\" name=\"username\" autofocus>\n <input type=\"password\" name=\"password\">\n <input type=\"submit\" value=\"Login\">\n</form>\n</code></pre>\n\n<p><a href=\"http://fortuito.us/diveintohtml5/forms.html#autofocus\" rel=\"noreferrer\">Dive in to HTML5</a> has more information.</p>\n"
},
{
"answer_id": 13022713,
"author": "Dave K",
"author_id": 172278,
"author_profile": "https://Stackoverflow.com/users/172278",
"pm_score": 2,
"selected": false,
"text": "<p>This gets the first of any visible common input, including textareas and select boxes. This also makes sure they aren't hidden, disabled or readonly. it also allows for a target div, which I use in my software (ie, first input inside of this form).</p>\n\n<pre><code>$(\"input:visible:enabled:not([readonly]),textarea:visible:enabled:not([readonly]),select:visible:enabled:not([readonly])\", \n target).first().focus();\n</code></pre>\n"
},
{
"answer_id": 14515475,
"author": "Max West",
"author_id": 1441180,
"author_profile": "https://Stackoverflow.com/users/1441180",
"pm_score": 2,
"selected": false,
"text": "<p>Tried lots of the answers above and they weren't working. Found this one at: <a href=\"http://www.kolodvor.net/2008/01/17/set-focus-on-first-field-with-jquery/#comment-1317\" rel=\"nofollow\">http://www.kolodvor.net/2008/01/17/set-focus-on-first-field-with-jquery/#comment-1317</a>\nThank you Kolodvor. </p>\n\n<pre><code>$(\"input:text:visible:first\").focus();\n</code></pre>\n"
},
{
"answer_id": 18348284,
"author": "Robert Brooker",
"author_id": 654654,
"author_profile": "https://Stackoverflow.com/users/654654",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using this:</p>\n\n<pre><code>$(\"form:first *:input,select,textarea\").filter(\":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])\").first().focus();\n</code></pre>\n"
},
{
"answer_id": 23541183,
"author": "EpokK",
"author_id": 1875004,
"author_profile": "https://Stackoverflow.com/users/1875004",
"pm_score": 0,
"selected": false,
"text": "<p>With <code>AngularJS</code> :</p>\n\n<pre><code>angular.element('#Element')[0].focus();\n</code></pre>\n"
},
{
"answer_id": 23993495,
"author": "HectorPerez",
"author_id": 2140139,
"author_profile": "https://Stackoverflow.com/users/2140139",
"pm_score": 0,
"selected": false,
"text": "<p>This includes textareas and excludes radio buttons</p>\n\n<pre><code>$(document).ready(function() {\n var first_input = $('input[type=text]:visible:enabled:first, textarea:visible:enabled:first')[0];\n if(first_input != undefined){ first_input.focus(); }\n});\n</code></pre>\n"
},
{
"answer_id": 26459634,
"author": "feder",
"author_id": 2815264,
"author_profile": "https://Stackoverflow.com/users/2815264",
"pm_score": 1,
"selected": false,
"text": "<p>For those who use JSF2.2+ and cannot pass autofocus as an attribute without value to it, use this:</p>\n\n<pre><code> p:autofocus=\"true\"\n</code></pre>\n\n<p>And add it to the namespace p (Also often used pt. Whatever you like).</p>\n\n<pre><code><html ... xmlns:p=\"http://java.sun.com/jsf/passthrough\">\n</code></pre>\n"
},
{
"answer_id": 47677689,
"author": "thecoolmacdude",
"author_id": 1410728,
"author_profile": "https://Stackoverflow.com/users/1410728",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to use clientHeight instead of checking for the display attribute, since a parent could be hiding this element:</p>\n\n<pre><code>function setFocus() {\n var forms = document.forms || [];\n for (var i = 0; i < forms.length; i++) {\n for (var j = 0; j < forms[i].length; j++) {\n var widget = forms[i][j];\n if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === \"function\")\n && (typeof widget.disabled === \"undefined\" || widget.disabled === false)\n && (typeof widget.readOnly === \"undefined\" || widget.readOnly === false)) {\n widget.focus();\n break;\n }\n }\n }\n } \n}\n</code></pre>\n"
},
{
"answer_id": 54752436,
"author": "cghislai",
"author_id": 3074381,
"author_profile": "https://Stackoverflow.com/users/3074381",
"pm_score": 0,
"selected": false,
"text": "<p>Without third party libs, use something like</p>\n\n<pre><code> const inputElements = parentElement.getElementsByTagName('input')\n if (inputChilds.length > 0) {\n inputChilds.item(0).focus();\n }\n</code></pre>\n\n<p>Make sure you consider all form element tags, rule out hidden/disabled ones like in other answers and so on..</p>\n"
},
{
"answer_id": 55761872,
"author": "localhostdotdev",
"author_id": 10993539,
"author_profile": "https://Stackoverflow.com/users/10993539",
"pm_score": 1,
"selected": false,
"text": "<p>without jquery, e.g. with regular javascript:</p>\n\n<pre><code>document.querySelector('form input:not([type=hidden])').focus()\n</code></pre>\n\n<p>works on Safari but not Chrome 75 (april 2019)</p>\n"
},
{
"answer_id": 65936624,
"author": "Scott Means",
"author_id": 149407,
"author_profile": "https://Stackoverflow.com/users/149407",
"pm_score": 4,
"selected": false,
"text": "<p>I needed to solve this problem for a form that is being displayed dynamically in a modal div on my page, and unfortunately <code>autofocus</code> isn't honored when the containing div is shown by changing the <code>display</code> property (at least not in Chrome). I don't like any of the solutions that require my code to infer which control I should set the focus to, because of the complications of hidden or zero-sized inputs, etc. My solution was to set the <code>autofocus</code> attribute on my input anyway, then set the focus in my code when I show the div:</p>\n<pre><code>form.querySelector('*[autofocus]').focus();\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
Is there a simple way to **set the focus** (input cursor) of a web page **on the first input element** (textbox, dropdownlist, ...) on loading the page without having to know the id of the element?
I would like to implement it as a common script for all my pages/forms of my web application.
|
You can also try jQuery based method:
```
$(document).ready(function() {
$('form:first *:input[type!=hidden]:first').focus();
});
```
|
277,546 |
<p>Just say I have a file: "HelloWorld.pm" in multiple subdirectories within a Git repository.</p>
<p>I would like to issue a command to find the full paths of all the files matching "HelloWorld.pm":</p>
<p>For example:</p>
<pre><code>/path/to/repository/HelloWorld.pm
/path/to/repository/but/much/deeper/down/HelloWorld.pm
/path/to/repository/please/dont/make/me/search/through/the/lot/HelloWorld.pm
</code></pre>
<p>How can I use Git to efficiently find all the full paths that match a given filename?</p>
<p>I realise I can do this with the Linux/Unix find command but I was hoping to avoid scanning all subdirectories looking for instances of the filename.</p>
|
[
{
"answer_id": 277557,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>git ls-tree -r HEAD | grep HelloWorld.pm\n</code></pre>\n"
},
{
"answer_id": 5681657,
"author": "Brian Campbell",
"author_id": 69755,
"author_profile": "https://Stackoverflow.com/users/69755",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html\" rel=\"noreferrer\"><code>git ls-files</code></a> will give you a listing of all files in current state of the repository (the cache or index). You can pass a pattern in to get files matching that pattern.</p>\n\n<pre><code>git ls-files HelloWorld.pm '**/HelloWorld.pm'\n</code></pre>\n\n<p>If you would like to find a set of files and grep through their contents, you can do that with <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-grep.html\" rel=\"noreferrer\"><code>git grep</code></a>:</p>\n\n<pre><code>git grep some-string -- HelloWorld.pm '**/HelloWorld.pm'\n</code></pre>\n"
},
{
"answer_id": 6960138,
"author": "Uwe Geuder",
"author_id": 880945,
"author_profile": "https://Stackoverflow.com/users/880945",
"pm_score": 6,
"selected": false,
"text": "<p>Hmm, the original question was about the repository. A repository contains more than 1 commit (in the general case at least), but the answers given before search only through one commit.</p>\n\n<p>Because I could not find an answer that really searches the whole commit history I wrote a quick brute force script git-find-by-name that takes (nearly) all commits into consideration.</p>\n\n<pre><code>#! /bin/sh\ntmpdir=$(mktemp -td git-find.XXXX)\ntrap \"rm -r $tmpdir\" EXIT INT TERM\n\nallrevs=$(git rev-list --all)\n# well, nearly all revs, we could still check the log if we have\n# dangling commits and we could include the index to be perfect...\n\nfor rev in $allrevs\ndo\n git ls-tree --full-tree -r $rev >$tmpdir/$rev \ndone\n\ncd $tmpdir\ngrep $1 * \n</code></pre>\n\n<p>Maybe there is a more elegant way.</p>\n\n<p>Please note the trivial way the parameter is passed into grep, so it will match parts of filename. If that is not desired anchor your search expression and/or add suitable grep options.</p>\n\n<p>For deep histories the output might be too noisy, I thought about a script that converts\na list of revisions into a range, like the opposite of what git rev-list can do. But so far it has remained a thought.</p>\n"
},
{
"answer_id": 16492352,
"author": "Dean Hall",
"author_id": 299525,
"author_profile": "https://Stackoverflow.com/users/299525",
"pm_score": 2,
"selected": false,
"text": "<p>[It's a bit of comment abuse, I admit, but I can't comment yet and thought I would improve @uwe-geuder's answer.]</p>\n\n<pre><code>#!/bin/bash\n#\n#\n\n# I'm using a fixed string here, not a regular expression, but you can easily\n# use a regular expression by altering the call to grep below.\nname=\"$1\"\n\n# Verify usage.\nif [[ -z \"$name\" ]]\nthen\n echo \"Usage: $(basename \"$0\") <file name>\" 1>&2\n exit 100\nfi \n\n# Search all revisions; get unique results.\nwhile IFS= read rev\ndo\n # Find $name in $rev's tree and only use its path.\n grep -F -- \"$name\" \\\n <(git ls-tree --full-tree -r \"$rev\" | awk '{ print $4 }')\ndone < \\\n <(git rev-list --all) \\\n | sort -u\n</code></pre>\n\n<p>Again, +1 to @uwe-geuder for a great answer.</p>\n\n<p>If you're interested in the BASH itself:</p>\n\n<p>Unless you're guaranteed of the word-splitting in a for loop (as when using an array like this: <code>for item in \"${array[@]}\"</code>), I highly recommend using <code>while IFS= read var ; do ... ; done < <(command)</code> when the command output you're looping over is separated by newlines (or <code>read -d''</code> when output is separated by the null string <code>$'\\0'</code>). While <code>git rev-list --all</code> is guaranteed to use 40-byte hexadecimal strings (without spaces), I never like to take chances. I can now easily change the command from <code>git rev-list --all</code> to any command that produces lines </p>\n\n<p>I also recommend using built-in BASH mechanisms to inject input and filter output instead of temporary files.</p>\n"
},
{
"answer_id": 24289481,
"author": "Bull",
"author_id": 1143433,
"author_profile": "https://Stackoverflow.com/users/1143433",
"pm_score": 3,
"selected": false,
"text": "<pre><code>git ls-files | grep -i HelloWorld.pm\n</code></pre>\n\n<p>The grep -i makes grep case insensitive.</p>\n"
},
{
"answer_id": 34100574,
"author": "dirkjot",
"author_id": 230446,
"author_profile": "https://Stackoverflow.com/users/230446",
"pm_score": 1,
"selected": false,
"text": "<p>The script by Uwe Geuder (@uwe-geuder) is great but there really is no need to dump each of the ls-tree outputs in its own directory, unfiltered. </p>\n\n<p>Much faster and using less storage: Run the grep on the output and then store it, as shown in this <a href=\"https://gist.github.com/dirkjot/073ffac502567e32f7ad\" rel=\"nofollow\">gist</a> </p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36142/"
] |
Just say I have a file: "HelloWorld.pm" in multiple subdirectories within a Git repository.
I would like to issue a command to find the full paths of all the files matching "HelloWorld.pm":
For example:
```
/path/to/repository/HelloWorld.pm
/path/to/repository/but/much/deeper/down/HelloWorld.pm
/path/to/repository/please/dont/make/me/search/through/the/lot/HelloWorld.pm
```
How can I use Git to efficiently find all the full paths that match a given filename?
I realise I can do this with the Linux/Unix find command but I was hoping to avoid scanning all subdirectories looking for instances of the filename.
|
[`git ls-files`](http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html) will give you a listing of all files in current state of the repository (the cache or index). You can pass a pattern in to get files matching that pattern.
```
git ls-files HelloWorld.pm '**/HelloWorld.pm'
```
If you would like to find a set of files and grep through their contents, you can do that with [`git grep`](http://www.kernel.org/pub/software/scm/git/docs/git-grep.html):
```
git grep some-string -- HelloWorld.pm '**/HelloWorld.pm'
```
|
277,551 |
<p>It looks like all the methods for loading SQLite involve loading from a named file using a string. I would like to load SQlite database from memory.</p>
<p>The database is already loaded into memory.</p>
|
[
{
"answer_id": 277558,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 5,
"selected": true,
"text": "<p>Use a special file name, <code>:memory:</code></p>\n\n<pre><code>sqlite3_open(\":memory:\", &db);\n</code></pre>\n\n<p><code>libsqlite</code> must have been compiled <strong>without</strong> <code>SQLITE_OMIT_MEMORYDB</code> defined, as pointed out in <a href=\"http://www.sqlite.org/compile.html\" rel=\"noreferrer\">SQLite documentation</a>:</p>\n\n<blockquote>\n <p><strong><code>SQLITE_OMIT_MEMORYDB</code></strong></p>\n \n <blockquote>\n <p>When this is defined, the library does not respect the special database name <code>\":memory:\"</code> (normally used to create an in-memory database). If <code>\":memory:\"</code> is passed to <code>sqlite3_open()</code>, <code>sqlite3_open16()</code>, or <code>sqlite3_open_v2()</code>, a file with this name will be opened or created. </p>\n </blockquote>\n</blockquote>\n\n<p>If you want to read the database that is <em>already</em> fully loaded into memory however, it will be more work. You will have to implement a custom VFS layer to operate on memory files and register it with your SQLite context.</p>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"http://sqlite.org/c3ref/vfs.html\" rel=\"noreferrer\"><code>sqlite3_vfs</code></a></li>\n<li><a href=\"http://sqlite.org/c3ref/io_methods.html\" rel=\"noreferrer\"><code>sqlite3_io_methods</code></a></li>\n</ul>\n\n<p>I have not implemented it myself, so I can't reliably tell whether you have to implement the entire new VFS layer, or you can get away with substituting some functions in the default one (latter is unlikely).</p>\n"
},
{
"answer_id": 811014,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>There is a memvfs implementation at</p>\n\n<p><a href=\"http://article.gmane.org/gmane.comp.db.sqlite.general/46450\" rel=\"nofollow noreferrer\">article.gmane.org/gmane.comp.db.sqlite.general/46450</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35223/"
] |
It looks like all the methods for loading SQLite involve loading from a named file using a string. I would like to load SQlite database from memory.
The database is already loaded into memory.
|
Use a special file name, `:memory:`
```
sqlite3_open(":memory:", &db);
```
`libsqlite` must have been compiled **without** `SQLITE_OMIT_MEMORYDB` defined, as pointed out in [SQLite documentation](http://www.sqlite.org/compile.html):
>
> **`SQLITE_OMIT_MEMORYDB`**
>
>
>
> >
> > When this is defined, the library does not respect the special database name `":memory:"` (normally used to create an in-memory database). If `":memory:"` is passed to `sqlite3_open()`, `sqlite3_open16()`, or `sqlite3_open_v2()`, a file with this name will be opened or created.
> >
> >
> >
>
>
>
If you want to read the database that is *already* fully loaded into memory however, it will be more work. You will have to implement a custom VFS layer to operate on memory files and register it with your SQLite context.
See:
* [`sqlite3_vfs`](http://sqlite.org/c3ref/vfs.html)
* [`sqlite3_io_methods`](http://sqlite.org/c3ref/io_methods.html)
I have not implemented it myself, so I can't reliably tell whether you have to implement the entire new VFS layer, or you can get away with substituting some functions in the default one (latter is unlikely).
|
277,569 |
<p>In PHP, is there an easy way to convert a number to a word? For instance, <em>27</em> to <em>twenty-seven</em>.</p>
|
[
{
"answer_id": 277586,
"author": "Chris",
"author_id": 4742,
"author_profile": "https://Stackoverflow.com/users/4742",
"pm_score": 6,
"selected": true,
"text": "<p>I <a href=\"http://bloople.net/num2text/cnumlib.txt\" rel=\"noreferrer\">found</a> some (2007/2008) source-code online and as it is copyright but I can use it freely and modify it however I want, so I place it here and re-license under CC-Wiki:</p>\n\n<pre><code><?php\n/**\n * English Number Converter - Collection of PHP functions to convert a number\n * into English text.\n *\n * This exact code is licensed under CC-Wiki on Stackoverflow.\n * http://creativecommons.org/licenses/by-sa/3.0/\n *\n * @link http://stackoverflow.com/q/277569/367456\n * @question Is there an easy way to convert a number to a word in PHP?\n *\n * This file incorporates work covered by the following copyright and\n * permission notice:\n *\n * Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text\n * You can use this freely and modify it however you want.\n */\n\nfunction convertNumber($number)\n{\n list($integer, $fraction) = explode(\".\", (string) $number);\n\n $output = \"\";\n\n if ($integer{0} == \"-\")\n {\n $output = \"negative \";\n $integer = ltrim($integer, \"-\");\n }\n else if ($integer{0} == \"+\")\n {\n $output = \"positive \";\n $integer = ltrim($integer, \"+\");\n }\n\n if ($integer{0} == \"0\")\n {\n $output .= \"zero\";\n }\n else\n {\n $integer = str_pad($integer, 36, \"0\", STR_PAD_LEFT);\n $group = rtrim(chunk_split($integer, 3, \" \"), \" \");\n $groups = explode(\" \", $group);\n\n $groups2 = array();\n foreach ($groups as $g)\n {\n $groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2});\n }\n\n for ($z = 0; $z < count($groups2); $z++)\n {\n if ($groups2[$z] != \"\")\n {\n $output .= $groups2[$z] . convertGroup(11 - $z) . (\n $z < 11\n && !array_search('', array_slice($groups2, $z + 1, -1))\n && $groups2[11] != ''\n && $groups[11]{0} == '0'\n ? \" and \"\n : \", \"\n );\n }\n }\n\n $output = rtrim($output, \", \");\n }\n\n if ($fraction > 0)\n {\n $output .= \" point\";\n for ($i = 0; $i < strlen($fraction); $i++)\n {\n $output .= \" \" . convertDigit($fraction{$i});\n }\n }\n\n return $output;\n}\n\nfunction convertGroup($index)\n{\n switch ($index)\n {\n case 11:\n return \" decillion\";\n case 10:\n return \" nonillion\";\n case 9:\n return \" octillion\";\n case 8:\n return \" septillion\";\n case 7:\n return \" sextillion\";\n case 6:\n return \" quintrillion\";\n case 5:\n return \" quadrillion\";\n case 4:\n return \" trillion\";\n case 3:\n return \" billion\";\n case 2:\n return \" million\";\n case 1:\n return \" thousand\";\n case 0:\n return \"\";\n }\n}\n\nfunction convertThreeDigit($digit1, $digit2, $digit3)\n{\n $buffer = \"\";\n\n if ($digit1 == \"0\" && $digit2 == \"0\" && $digit3 == \"0\")\n {\n return \"\";\n }\n\n if ($digit1 != \"0\")\n {\n $buffer .= convertDigit($digit1) . \" hundred\";\n if ($digit2 != \"0\" || $digit3 != \"0\")\n {\n $buffer .= \" and \";\n }\n }\n\n if ($digit2 != \"0\")\n {\n $buffer .= convertTwoDigit($digit2, $digit3);\n }\n else if ($digit3 != \"0\")\n {\n $buffer .= convertDigit($digit3);\n }\n\n return $buffer;\n}\n\nfunction convertTwoDigit($digit1, $digit2)\n{\n if ($digit2 == \"0\")\n {\n switch ($digit1)\n {\n case \"1\":\n return \"ten\";\n case \"2\":\n return \"twenty\";\n case \"3\":\n return \"thirty\";\n case \"4\":\n return \"forty\";\n case \"5\":\n return \"fifty\";\n case \"6\":\n return \"sixty\";\n case \"7\":\n return \"seventy\";\n case \"8\":\n return \"eighty\";\n case \"9\":\n return \"ninety\";\n }\n } else if ($digit1 == \"1\")\n {\n switch ($digit2)\n {\n case \"1\":\n return \"eleven\";\n case \"2\":\n return \"twelve\";\n case \"3\":\n return \"thirteen\";\n case \"4\":\n return \"fourteen\";\n case \"5\":\n return \"fifteen\";\n case \"6\":\n return \"sixteen\";\n case \"7\":\n return \"seventeen\";\n case \"8\":\n return \"eighteen\";\n case \"9\":\n return \"nineteen\";\n }\n } else\n {\n $temp = convertDigit($digit2);\n switch ($digit1)\n {\n case \"2\":\n return \"twenty-$temp\";\n case \"3\":\n return \"thirty-$temp\";\n case \"4\":\n return \"forty-$temp\";\n case \"5\":\n return \"fifty-$temp\";\n case \"6\":\n return \"sixty-$temp\";\n case \"7\":\n return \"seventy-$temp\";\n case \"8\":\n return \"eighty-$temp\";\n case \"9\":\n return \"ninety-$temp\";\n }\n }\n}\n\nfunction convertDigit($digit)\n{\n switch ($digit)\n {\n case \"0\":\n return \"zero\";\n case \"1\":\n return \"one\";\n case \"2\":\n return \"two\";\n case \"3\":\n return \"three\";\n case \"4\":\n return \"four\";\n case \"5\":\n return \"five\";\n case \"6\":\n return \"six\";\n case \"7\":\n return \"seven\";\n case \"8\":\n return \"eight\";\n case \"9\":\n return \"nine\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 278054,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 3,
"selected": false,
"text": "<p>There is the <a href=\"http://pear.php.net/package/Numbers_Words\" rel=\"nofollow noreferrer\"><code>Numbers_Words</code> package</a> in PECL. It does exactly what you ask for. The following languages are supported:</p>\n\n<ul>\n<li>bg (Bulgarian) by Kouber Saparev</li>\n<li>cs (Czech) by Petr 'PePa' Pavel</li>\n<li>de (German) by Piotr Klaban</li>\n<li>dk (Danish) by Jesper Veggerby</li>\n<li>en_100 (Donald Knuth system, English) by Piotr Klaban</li>\n<li>en_GB (British English) by Piotr Klaban</li>\n<li>en_US (American English) by Piotr Klaban</li>\n<li>es (Spanish Castellano) by Xavier Noguer</li>\n<li>es_AR (Argentinian Spanish) by Martin Marrese</li>\n<li>et (Estonian) by Erkki Saarniit</li>\n<li>fr (French) by Kouber Saparev</li>\n<li>fr_BE (French Belgium) by Kouber Saparev and Philippe Bajoit</li>\n<li>he (Hebrew) by Hadar Porat</li>\n<li>hu_HU (Hungarian) by Nils Homp</li>\n<li>id (Indonesian) by Ernas M. Jamil and Arif Rifai Dwiyanto</li>\n<li>it_IT (Italian) by Filippo Beltramini and Davide Caironi</li>\n<li>lt (Lithuanian) by Laurynas Butkus</li>\n<li>nl (Dutch) by WHAM van Dinter</li>\n<li>pl (Polish) by Piotr Klaban</li>\n<li>pt_BR (Brazilian Portuguese) by Marcelo Subtil Marcal and Mario H.C.T.</li>\n<li>ru (Russian) by Andrey Demenev</li>\n<li>sv (Swedish) by Robin Ericsson</li>\n</ul>\n"
},
{
"answer_id": 1107274,
"author": "user132513",
"author_id": 132513,
"author_profile": "https://Stackoverflow.com/users/132513",
"pm_score": 5,
"selected": false,
"text": "<p>Alternatively, you can use the NumberFormatter class from <a href=\"http://www.php.net/manual/en/intl.setup.php\" rel=\"noreferrer\"><code>intl</code></a> package in PHP . Here's a sample code to get you started (for commandline):</p>\n\n<pre><code><?php\nif ($argc < 3) \n {\n echo \"usage: php {$argv[0]} lang-tag number ...\\n\";\n exit;\n }\n\narray_shift($argv);\n$lang_tag = array_shift($argv);\n\n$nf1 = new NumberFormatter($lang_tag, NumberFormatter::DECIMAL);\n$nf2 = new NumberFormatter($lang_tag, NumberFormatter::SPELLOUT);\n\nforeach ($argv as $num) \n {\n echo $nf1->format($num).' is '.$nf2->format($num).\"\\n\"; \n }\n</code></pre>\n"
},
{
"answer_id": 12411682,
"author": "Coder4web",
"author_id": 787253,
"author_profile": "https://Stackoverflow.com/users/787253",
"pm_score": -1,
"selected": false,
"text": "<p>I have generated this using a recursive function,.</p>\n\n<pre><code>$wordnum = numberToWord($number);\necho $wordnum.\"<BR>\";\n\nfunction singledigit($number){\n switch($number){\n case 0:$word = \"zero\";break;\n case 1:$word = \"One\";break;\n case 2:$word = \"two\";break;\n case 3:$word = \"three\";break;\n case 4:$word = \"Four\";break;\n case 5:$word = \"Five\";break;\n case 6:$word = \"Six\";break;\n case 7:$word = \"Seven\";break;\n case 8:$word = \"Eight\";break;\n case 9:$word = \"Nine\";break;\n }\n return $word;\n }\n\n function doubledigitnumber($number){\n if($number == 0){\n $word = \"\";\n }\n else{\n $word = singledigit($number);\n } \n return $word;\n }\n\n function doubledigit($number){\n switch($number[0]){\n case 0:$word = doubledigitnumber($number[1]);break;\n case 1:\n switch($number[1]){\n case 0:$word = \"Ten\";break;\n case 1:$word = \"Eleven\";break;\n case 2:$word = \"Twelve\";break;\n case 3:$word = \"Thirteen\";break;\n case 4:$word = \"Fourteen\";break;\n case 5:$word = \"Fifteen\";break;\n case 6:$word = \"Sixteen\";break;\n case 7:$word = \"Seventeen\";break;\n case 8:$word = \"Eighteen\";break;\n case 9:$word = \"Ninteen\";break;\n }break;\n case 2:$word = \"Twenty\".doubledigitnumber($number[1]);break; \n case 3:$word = \"Thirty\".doubledigitnumber($number[1]);break;\n case 4:$word = \"Forty\".doubledigitnumber($number[1]);break;\n case 5:$word = \"Fifty\".doubledigitnumber($number[1]);break;\n case 6:$word = \"Sixty\".doubledigitnumber($number[1]);break;\n case 7:$word = \"Seventy\".doubledigitnumber($number[1]);break;\n case 8:$word = \"Eighty\".doubledigitnumber($number[1]);break;\n case 9:$word = \"Ninety\".doubledigitnumber($number[1]);break;\n\n }\n return $word;\n }\n\n function unitdigit($numberlen,$number){\n switch($numberlen){ \n case 3:$word = \"Hundred\";break;\n case 4:$word = \"Thousand\";break;\n case 5:$word = \"Thousand\";break;\n case 6:$word = \"Lakh\";break;\n case 7:$word = \"Lakh\";break;\n case 8:$word = \"Crore\";break;\n case 9:$word = \"Crore\";break;\n\n }\n return $word;\n }\n\n function numberToWord($number){\n\n $numberlength = strlen($number);\n if ($numberlength == 1) { \n return singledigit($number);\n }elseif ($numberlength == 2) {\n return doubledigit($number);\n }\n else {\n\n $word = \"\";\n $wordin = \"\";\n\n if($numberlength == 9){\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n }\n\n if($numberlength == 7){\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n\n }\n\n if($numberlength == 5){\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n\n\n }\n else{\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = singledigit($number[0]) .\" \".$unitdigit.\" \";\n } \n return $word.\" \".numberToWord(substr($number,1));\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 15594551,
"author": "wolfe",
"author_id": 2203697,
"author_profile": "https://Stackoverflow.com/users/2203697",
"pm_score": 2,
"selected": false,
"text": "<p>I rewrote the code above to fit the standard U.S. written word number format.</p>\n\n<pre><code>function singledigit($number){\n switch($number){\n case 0:$word = \"zero\";break;\n case 1:$word = \"one\";break;\n case 2:$word = \"two\";break;\n case 3:$word = \"three\";break;\n case 4:$word = \"four\";break;\n case 5:$word = \"five\";break;\n case 6:$word = \"six\";break;\n case 7:$word = \"seven\";break;\n case 8:$word = \"eight\";break;\n case 9:$word = \"nine\";break;\n }\n return $word;\n}\n\nfunction doubledigitnumber($number){\n if($number == 0){\n $word = \"\";\n }\n else{\n $word = \"-\".singledigit($number);\n } \n return $word;\n}\n\nfunction doubledigit($number){\n switch($number[0]){\n case 0:$word = doubledigitnumber($number[1]);break;\n case 1:\n switch($number[1]){\n case 0:$word = \"ten\";break;\n case 1:$word = \"eleven\";break;\n case 2:$word = \"twelve\";break;\n case 3:$word = \"thirteen\";break;\n case 4:$word = \"fourteen\";break;\n case 5:$word = \"fifteen\";break;\n case 6:$word = \"sixteen\";break;\n case 7:$word = \"seventeen\";break;\n case 8:$word = \"eighteen\";break;\n case 9:$word = \"ninteen\";break;\n }break;\n case 2:$word = \"twenty\".doubledigitnumber($number[1]);break; \n case 3:$word = \"thirty\".doubledigitnumber($number[1]);break;\n case 4:$word = \"forty\".doubledigitnumber($number[1]);break;\n case 5:$word = \"fifty\".doubledigitnumber($number[1]);break;\n case 6:$word = \"sixty\".doubledigitnumber($number[1]);break;\n case 7:$word = \"seventy\".doubledigitnumber($number[1]);break;\n case 8:$word = \"eighty\".doubledigitnumber($number[1]);break;\n case 9:$word = \"ninety\".doubledigitnumber($number[1]);break;\n\n }\n return $word;\n}\n\nfunction unitdigit($numberlen,$number){\n switch($numberlen){ \n case 3:case 6:case 9:case 12:$word = \"hundred\";break;\n case 4:case 5:$word = \"thousand\";break;\n case 7:case 8:$word = \"million\";break;\n case 10:case 11:$word = \"billion\";break;\n }\n return $word;\n}\n\nfunction numberToWord($number){\n\n $numberlength = strlen($number);\n if ($numberlength == 1) { \n return singledigit($number);\n }elseif ($numberlength == 2) {\n return doubledigit($number);\n }\n else {\n\n $word = \"\";\n $wordin = \"\";\n switch ($numberlength ) {\n case 5:case 8: case 11:\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n break;\n default:\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = singledigit($number[0]) .\" \".$unitdigit.\" \";\n } \n return $word.\" \".numberToWord(substr($number,1));\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40739003,
"author": "Works for a Living",
"author_id": 2634948,
"author_profile": "https://Stackoverflow.com/users/2634948",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a small class I wrote tonight. Caveats:</p>\n\n<ol>\n<li>Only in English.</li>\n<li>Only handles American/French definitions of billions, etc.</li>\n<li>The <code>longform</code> method doesn't handle decimals. It just erases them. Feel free to modify this and add that functionality if you wish. </li>\n<li>The <code>numberformat</code> method does do decimals, but doesn't do any rounding. I had to create a new <code>numberformat</code> function because of PHP's inherent limitations with integer sizes. I was translating numbers so big that when I used <code>number_format()</code> to check my translations, it took me 30 minutes to realize my translations weren't wrong, <code>number_format</code> was. </li>\n<li>This isn't a caveat about the class, but about PHP. 32-bit versions of PHP will not handle integers bigger than <code>2,147,483,647</code> (2 billion and change). 64-bit versions will handle up to like <code>9 quintillion</code> or something. BUT that's irrelevant here as long as you feed the numbers to the <code>longform</code> method as a <code>string</code>. I did a 306-digit number over <code>ajax</code> from a webform just fine, as long as I passed it to the server as <code>''+number</code>. </li>\n</ol>\n\n<p>So, this class will translate numbers up to <code>999 Centillion, 999 etc.</code> (e.g., a string of 9s 306 characters long). Any number bigger than that and the function just returns a dumb message. </p>\n\n<p>Usage: </p>\n\n<pre><code>$number = '999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999';\nreallyBig::longform($number);\n</code></pre>\n\n<p>The optional second boolean parameter defaults to true, which adds commas as best it can in the right places, to make the number more readable. </p>\n\n<p>By the way, you can put a <code>-</code> at the front if you want it to be negative, but any other characters included in the inputted string will be stripped out. For instance:</p>\n\n<p><code>reallyBig::longform('-C55LL-M5-4-a-9u7-71m3-M8');</code> will output: <code>negative five billion, five hundred fifty-four million, nine hundred seventy-seven thousand, one hundred thirty-eight</code></p>\n\n<p>The <code>numberformat</code> method isn't necessary for any other method. It's just there if you want to check a really long translated number. Since all these functions handle numbers as strings, they don't run up against PHP's limitations. </p>\n\n<p>The only reason I stopped at a 999 centillion is because centillion was the last number on the website I was looking at when I couldn't remember what came after a decillion. </p>\n\n<pre><code>class reallyBig\n{\n private static $map, $strings;\n private static function map()\n {\n $map = array();\n $num = 1;\n $count = 1;\n while($num < 307)\n {\n if($count == 1) $map[$num] = $num+2;\n elseif($count == 2) $map[$num] = $num+1;\n else \n {\n $map[$num] = $num;\n $count = 0;\n }\n $count++;\n $num++;\n }\n return $map;\n }\n private static function strings()\n {\n return array \n (\n 6 => 'thousand',\n 9 => 'million',\n 12 => 'billion',\n 15 => 'trillion',\n 18 => 'quadrillion',\n 21 => 'quintillion',\n 24 => 'sextillion',\n 27 => 'septillion',\n 30 => 'octillion',\n 33 => 'nonillion',\n 36 => 'decillion',\n 39 => 'undecillion',\n 42 => 'duodecillion',\n 45 => 'tredecillion',\n 48 => 'quattuordecillion',\n 51 => 'quindecillion',\n 54 => 'sexdecillion',\n 57 => 'septendecillion',\n 60 => 'octodecillion',\n 63 => 'novemdecillion',\n 66 => 'vigintillion',\n 69 => 'unvigintillion',\n 72 => 'duovigintillion',\n 75 => 'trevigintillion',\n 78 => 'quattuorvigintillion',\n 81 => 'quinvigintillion',\n 84 => 'sexvigintillion',\n 87 => 'septenvigintillion',\n 90 => 'octovigintillion',\n 93 => 'novemvigintillion',\n 96 => 'trigintillion',\n 99 => 'untrigintillion',\n 102 => 'duotrigintillion',\n 105 => 'tretrigintillion',\n 108 => 'quattuortrigintillion',\n 111 => 'quintrigintillion',\n 114 => 'sextrigintillion',\n 117 => 'septentrigintillion',\n 120 => 'octotrigintillion',\n 123 => 'novemtrigintillion',\n 126 => 'quadragintillion',\n 129 => 'unquadragintillion',\n 132 => 'duoquadragintillion',\n 135 => 'trequadragintillion',\n 138 => 'quattuorquadragintillion',\n 141 => 'quinquadragintillion',\n 144 => 'sexquadragintillion',\n 147 => 'septenquadragintillion',\n 150 => 'octoquadragintillion',\n 153 => 'novemquadragintillion',\n 156 => 'quinquagintillion',\n 159 => 'unquinquagintillion',\n 162 => 'duoquinquagintillion',\n 165 => 'trequinquagintillion',\n 168 => 'quattuorquinquagintillion',\n 171 => 'quinquinquagintillion',\n 174 => 'sexquinquagintillion',\n 177 => 'septenquinquagintillion',\n 180 => 'octoquinquagintillion',\n 183 => 'novemquinquagintillion',\n 186 => 'sexagintillion',\n 189 => 'unsexagintillion',\n 192 => 'duosexagintillion',\n 195 => 'tresexagintillion',\n 198 => 'quattuorsexagintillion',\n 201 => 'quinsexagintillion',\n 204 => 'sexsexagintillion',\n 207 => 'septensexagintillion',\n 210 => 'octosexagintillion',\n 213 => 'novemsexagintillion',\n 216 => 'septuagintillion',\n 219 => 'unseptuagintillion',\n 222 => 'duoseptuagintillion',\n 225 => 'treseptuagintillion',\n 228 => 'quattuorseptuagintillion',\n 231 => 'quinseptuagintillion',\n 234 => 'sexseptuagintillion',\n 237 => 'septenseptuagintillion',\n 240 => 'octoseptuagintillion',\n 243 => 'novemseptuagintillion',\n 246 => 'octogintillion',\n 249 => 'unoctogintillion',\n 252 => 'duooctogintillion',\n 255 => 'treoctogintillion',\n 258 => 'quattuoroctogintillion',\n 261 => 'quinoctogintillion',\n 264 => 'sexoctogintillion',\n 267 => 'septenoctogintillion',\n 270 => 'octooctogintillion',\n 273 => 'novemoctogintillion',\n 276 => 'nonagintillion',\n 279 => 'unnonagintillion',\n 282 => 'duononagintillion',\n 285 => 'trenonagintillion',\n 288 => 'quattuornonagintillion',\n 291 => 'quinnonagintillion',\n 294 => 'sexnonagintillion',\n 297 => 'septennonagintillion',\n 300 => 'octononagintillion',\n 303 => 'novemnonagintillion',\n 306 => 'centillion',\n );\n }\n public static function longform($number = string, $commas = true)\n {\n $negative = substr($number, 0, 1) == '-' ? 'negative ' : '';\n list($number) = explode('.', $number); \n $number = trim(preg_replace(\"/[^0-9]/u\", \"\", $number));\n $number = (string)(ltrim($number,'0'));\n if(empty($number)) return 'zero';\n $length = strlen($number);\n if($length < 2) return $negative.self::ones($number);\n if($length < 3) return $negative.self::tens($number);\n if($length < 4) return $commas ? $negative.str_replace('hundred ', 'hundred and ', self::hundreds($number)) : $negative.self::hundreds($number);\n if($length < 307) \n {\n self::$map = self::map();\n self::$strings = self::strings();\n $result = self::beyond($number, self::$map[$length]);\n if(!$commas) return $negative.$result;\n $strings = self::$strings;\n $thousand = array_shift($strings);\n foreach($strings as $string) $result = str_replace($string.' ', $string.', ', $result);\n if(strpos($result, 'thousand') !== false) list($junk,$remainder) = explode('thousand', $result);\n else $remainder = $result;\n return strpos($remainder, 'hundred') !== false ? $negative.str_replace('thousand ', 'thousand, ', $result) : $negative.str_replace('thousand ', 'thousand and ', $result);\n }\n return 'a '.$negative.'number too big for your britches';\n }\n private static function ones($number)\n {\n $ones = array('zero','one','two','three','four','five','six','seven','eight','nine');\n return $ones[$number];\n }\n private static function tens($number)\n {\n $number = (string)(ltrim($number,'0'));\n if(strlen($number) < 2) return self::ones($number);\n if($number < 20)\n {\n $teens = array('ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen');\n return $teens[($number-10)];\n }\n else\n {\n $tens = array('','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety');\n $word = $tens[$number[0]];\n return empty($number[1]) ? $word : $word.'-'.self::ones($number[1]);\n }\n }\n private static function hundreds($number)\n {\n $number = (string)(ltrim($number,'0'));\n if(strlen($number) < 3) return self::tens($number);\n $word = self::ones($number[0]).' hundred';\n $remainder = substr($number, -2);\n if(ltrim($remainder,'0') != '') $word .= ' '.self::tens($remainder);\n return $word;\n }\n private static function beyond($number, $limit)\n {\n $number = (string)(ltrim($number,'0'));\n $length = strlen($number);\n if($length < 4) return self::hundreds($number);\n if($length < ($limit-2)) return self::beyond($number, self::$map[($limit-3)]);\n if($length == $limit) $word = self::hundreds(substr($number, 0, 3), true);\n elseif($length == ($limit-1)) $word = self::tens(substr($number, 0, 2));\n else $word = self::ones($number[0]);\n $word .= ' '.self::$strings[$limit];\n $sub = ($limit-3);\n $remainder = substr($number, -$sub);\n if(ltrim($remainder,'0') != '') $word .= ' '.self::beyond($remainder, self::$map[$sub]);\n return $word;\n }\n public static function numberformat($number, $fixed = 0, $dec = '.', $thou = ',')\n {\n $negative = substr($number, 0, 1) == '-' ? '-' : '';\n $number = trim(preg_replace(\"/[^0-9\\.]/u\", \"\", $number));\n $number = (string)(ltrim($number,'0'));\n $fixed = (int)$fixed;\n if(!is_numeric($fixed)) $fixed = 0;\n if(strpos($number, $dec) !== false) list($number,$decimals) = explode($dec, $number); \n else $decimals = '0';\n if($fixed) $decimals = '.'.str_pad(substr($decimals, 0, $fixed), $fixed, 0, STR_PAD_RIGHT);\n else $decimals = '';\n $thousands = array_map('strrev', array_reverse(str_split(strrev($number), 3)));\n return $negative.implode($thou,$thousands).$decimals;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45125817,
"author": "prikkles",
"author_id": 5605952,
"author_profile": "https://Stackoverflow.com/users/5605952",
"pm_score": 3,
"selected": false,
"text": "<p>I needed a solution that put 'and' into the returned string and formatted it into a sentence - typically as a human would say it. So I adapted a different solution slightly - posted as I thought this could be useful for someone.</p>\n\n<pre><code>4,835,301 returns \"Four million eight hundred and thirty five thousand three hundred and one.\"\n</code></pre>\n\n<p>Code</p>\n\n<pre><code>function convertNumber($num = false)\n{\n $num = str_replace(array(',', ''), '' , trim($num));\n if(! $num) {\n return false;\n }\n $num = (int) $num;\n $words = array();\n $list1 = array('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',\n 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'\n );\n $list2 = array('', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred');\n $list3 = array('', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion',\n 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion',\n 'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion'\n );\n $num_length = strlen($num);\n $levels = (int) (($num_length + 2) / 3);\n $max_length = $levels * 3;\n $num = substr('00' . $num, -$max_length);\n $num_levels = str_split($num, 3);\n for ($i = 0; $i < count($num_levels); $i++) {\n $levels--;\n $hundreds = (int) ($num_levels[$i] / 100);\n $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ( $hundreds == 1 ? '' : '' ) . ' ' : '');\n $tens = (int) ($num_levels[$i] % 100);\n $singles = '';\n if ( $tens < 20 ) {\n $tens = ($tens ? ' and ' . $list1[$tens] . ' ' : '' );\n } elseif ($tens >= 20) {\n $tens = (int)($tens / 10);\n $tens = ' and ' . $list2[$tens] . ' ';\n $singles = (int) ($num_levels[$i] % 10);\n $singles = ' ' . $list1[$singles] . ' ';\n }\n $words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' );\n } //end for loop\n $commas = count($words);\n if ($commas > 1) {\n $commas = $commas - 1;\n }\n $words = implode(' ', $words);\n $words = preg_replace('/^\\s\\b(and)/', '', $words );\n $words = trim($words);\n $words = ucfirst($words);\n $words = $words . \".\";\n return $words;\n}\n</code></pre>\n"
},
{
"answer_id": 46253129,
"author": "Mukhpal Singh",
"author_id": 8608666,
"author_profile": "https://Stackoverflow.com/users/8608666",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Amount in Words:</b><?=no_to_words($number)?>\n</code></pre>\n\n<p>Very simple way to convert number to words using PHP function.</p>\n"
},
{
"answer_id": 49507047,
"author": "Shamshid",
"author_id": 4574432,
"author_profile": "https://Stackoverflow.com/users/4574432",
"pm_score": 3,
"selected": false,
"text": "<p>Using NumberFormatter class it is simple to get convert to words.</p>\n\n<pre><code><?php\n\n$number = '12345';\n$locale = 'en_US';\n$fmt = numfmt_create($locale, NumberFormatter::SPELLOUT);\n$in_words = numfmt_format($fmt, $number);\n\nprint_r($in_words);\n// twelve thousand three hundred forty-five\n\n?>\n</code></pre>\n"
},
{
"answer_id": 52483632,
"author": "Rk dev tech",
"author_id": 8744309,
"author_profile": "https://Stackoverflow.com/users/8744309",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://php.net/manual/en/class.numberformatter.php\" rel=\"nofollow noreferrer\">NumberFormatter Class</a>:</p>\n\n<pre><code>$f = new NumberFormatter(\"en\", NumberFormatter::SPELLOUT);\necho $f->format($myNumber);\n</code></pre>\n"
},
{
"answer_id": 53075499,
"author": "curiosity",
"author_id": 9671602,
"author_profile": "https://Stackoverflow.com/users/9671602",
"pm_score": 1,
"selected": false,
"text": "<p>Yes there is. without using a library you just need to follow this..</p>\n\n<p>First you need to check in your server if <code>;extension=php_intl.dll</code> is enabled in your <strong>php.ini</strong> if still not work you need to see this answer.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/16372888/intl-extension-php-intl-dll-with-wamp/16372984#16372984\">intl extension php_intl.dll with wamp</a></p>\n\n<p>after successfully moving all the files starts with <strong>icu</strong>.</p>\n\n<p>from: <code><wamp_installation_path>/bin/php/php5.4.3/</code></p>\n\n<p>to: <code><wamp_installation_path>/bin/apache/apache2.2.22/bin/</code></p>\n\n<p>and restart your server.</p>\n\n<p>try to run this code:</p>\n\n<pre><code>$f = new NumberFormatter(\"en\", NumberFormatter::SPELLOUT);\necho $f->format(123456);\n</code></pre>\n\n<p>it will show the output of <strong><em>one hundred twenty-three thousand four hundred fifty-six</em></strong>. </p>\n\n<p>hope that helps everyone :).</p>\n"
},
{
"answer_id": 68241616,
"author": "Mohammad Ali Abdullah",
"author_id": 12650566,
"author_profile": "https://Stackoverflow.com/users/12650566",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n$grandTotalAmount = 700000000;\necho ($grandTotalAmount == round($grandTotalAmount)) ? convert_number_to_words(floatval($grandTotalAmount)) . ' Only' : convert_number_to_words(floatval($grandTotalAmount)) . ' Only';\n\nfunction convert_number_to_words($number) {\n $hyphen = ' ';\n $conjunction = ' and ';\n $separator = ', ';\n $negative = 'negative ';\n $decimal = ' Thai Baht And ';\n $dictionary = array(\n 0 => 'zero',\n 1 => 'one',\n 2 => 'two',\n 3 => 'three',\n 4 => 'four',\n 5 => 'five',\n 6 => 'six',\n 7 => 'seven',\n 8 => 'eight',\n 9 => 'nine',\n 10 => 'ten',\n 11 => 'eleven',\n 12 => 'twelve',\n 13 => 'thirteen',\n 14 => 'fourteen',\n 15 => 'fifteen',\n 16 => 'sixteen',\n 17 => 'seventeen',\n 18 => 'eighteen',\n 19 => 'nineteen',\n 20 => 'twenty',\n 30 => 'thirty',\n 40 => 'fourty',\n 50 => 'fifty',\n 60 => 'sixty',\n 70 => 'seventy',\n 80 => 'eighty',\n 90 => 'ninety',\n 100 => 'hundred',\n 1000 => 'thousand',\n 1000000 => 'million',\n 1000000000 => 'billion',\n 1000000000000 => 'trillion',\n 1000000000000000 => 'quadrillion',\n 1000000000000000000 => 'quintillion'\n );\n\n if (!is_numeric($number)) {\n return false;\n }\n\n if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {\n // overflow\n trigger_error(\n 'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX, E_USER_WARNING\n );\n return false;\n }\n\n if ($number < 0) {\n return $negative . convert_number_to_words(abs($number));\n }\n\n $string = $fraction = null;\n\n\n if (strpos($number, '.') !== false) {\n list($number, $fraction) = explode('.', $number);\n }\n\n switch (true) {\n case $number < 21:\n $string = $dictionary[$number];\n break;\n case $number < 100:\n $tens = ((int) ($number / 10)) * 10;\n $units = $number % 10;\n $string = $dictionary[$tens];\n if ($units) {\n $string .= $hyphen . $dictionary[$units];\n }\n break;\n case $number < 1000:\n $hundreds = $number / 100;\n $remainder = $number % 100;\n $string = $dictionary[$hundreds] . ' ' . $dictionary[100];\n if ($remainder) {\n $string .= $conjunction . convert_number_to_words($remainder);\n }\n break;\n default:\n $baseUnit = pow(1000, floor(log($number, 1000)));\n $numBaseUnits = (int) ($number / $baseUnit);\n $remainder = $number % $baseUnit;\n $string = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];\n if ($remainder) {\n $string .= $remainder < 100 ? $conjunction : $separator;\n $string .= convert_number_to_words($remainder);\n }\n break;\n }\n\n if (null !== $fraction && is_numeric($fraction)) {\n $string .= $decimal;\n $words = array();\n foreach (str_split((string) $fraction) as $number) {\n $words[] = $dictionary[$number];\n }\n $string .= implode(' ', $words);\n }\n\n return $string;\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 68280471,
"author": "Nazmul Haque",
"author_id": 5689349,
"author_profile": "https://Stackoverflow.com/users/5689349",
"pm_score": 0,
"selected": false,
"text": "<p>The below code is working fine</p>\n<pre><code>$test = 1000025.05;\n\n$f = new \\NumberFormatter( locale_get_default(), \\NumberFormatter::SPELLOUT );\n\n$word = $f->format($test);\n\necho $word;\n</code></pre>\n"
},
{
"answer_id": 68815108,
"author": "Stergios Zg.",
"author_id": 1891386,
"author_profile": "https://Stackoverflow.com/users/1891386",
"pm_score": 0,
"selected": false,
"text": "<pre><code>protected function numberTextHelper($number)\n{\n if (($number < 0) || ($number > 999999999)) \n {\n throw new Exception("Number is out of range");\n }\n \n $ones = array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", "Nineteen");\n $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eigthy", "Ninety");\n \n $giga = floor($number / 1000000);\n // Millions (giga)\n $number -= $giga * 1000000;\n\n $thousands = floor($number / 1000);\n \n // Thousands (kilo)\n $number -= $thousands * 1000;\n \n $hecto = floor($number / 100);\n \n // Hundreds (hecto)\n $number -= $hecto * 100;\n \n $deca = floor($number / 10);\n \n // Tens (deca)\n $n = $number % 10;\n \n $frac = round($number - (int)$number,2); \n\n // Ones\n $result = array();\n if ($giga) \n {\n $result[]= $this->numberTextHelper($giga).' '.($giga>1?'MILLIONS':'MILLION');\n }\n \n if ($thousands) \n {\n $result[]= $thousands>1?$this->numberTextHelper($thousands).' THOUSANDS':'THOUSAND';\n }\n \n if ($hecto) \n {\n $result[]= $this->numberTextHelper($hecto).'HUNDRED';\n }\n \n if ($deca) \n {\n if($deca<2)\n {\n $result[]= $ones[$deca * 10 + $n];\n $n=0;\n }\n else\n {\n $result[]= $tens[$deca];\n }\n }\n \n\n if ($n) \n {\n $result[]= $ones[$n];\n }\n\n if($frac) \n {\n $result[]= 'and';\n $result[]= $this->numberTextHelper($frac*100);\n $result[]= 'cents';\n }\n \n if(empty($result)) \n {\n $result[]= 'zero';\n }\n \n return implode(' ',$result);\n} \n</code></pre>\n<p>And you can translate it</p>\n<pre><code>function numberText($number)\n{\n $result=$this->numberTextHelper($number);\n $result=$this->strtoupper($result);\n $text=array_filter(explode(' ',$result));\n $translated=array_map(array($this,'getLang'),$text);\n return implode(' ',$translated);\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
In PHP, is there an easy way to convert a number to a word? For instance, *27* to *twenty-seven*.
|
I [found](http://bloople.net/num2text/cnumlib.txt) some (2007/2008) source-code online and as it is copyright but I can use it freely and modify it however I want, so I place it here and re-license under CC-Wiki:
```
<?php
/**
* English Number Converter - Collection of PHP functions to convert a number
* into English text.
*
* This exact code is licensed under CC-Wiki on Stackoverflow.
* http://creativecommons.org/licenses/by-sa/3.0/
*
* @link http://stackoverflow.com/q/277569/367456
* @question Is there an easy way to convert a number to a word in PHP?
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text
* You can use this freely and modify it however you want.
*/
function convertNumber($number)
{
list($integer, $fraction) = explode(".", (string) $number);
$output = "";
if ($integer{0} == "-")
{
$output = "negative ";
$integer = ltrim($integer, "-");
}
else if ($integer{0} == "+")
{
$output = "positive ";
$integer = ltrim($integer, "+");
}
if ($integer{0} == "0")
{
$output .= "zero";
}
else
{
$integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
$group = rtrim(chunk_split($integer, 3, " "), " ");
$groups = explode(" ", $group);
$groups2 = array();
foreach ($groups as $g)
{
$groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2});
}
for ($z = 0; $z < count($groups2); $z++)
{
if ($groups2[$z] != "")
{
$output .= $groups2[$z] . convertGroup(11 - $z) . (
$z < 11
&& !array_search('', array_slice($groups2, $z + 1, -1))
&& $groups2[11] != ''
&& $groups[11]{0} == '0'
? " and "
: ", "
);
}
}
$output = rtrim($output, ", ");
}
if ($fraction > 0)
{
$output .= " point";
for ($i = 0; $i < strlen($fraction); $i++)
{
$output .= " " . convertDigit($fraction{$i});
}
}
return $output;
}
function convertGroup($index)
{
switch ($index)
{
case 11:
return " decillion";
case 10:
return " nonillion";
case 9:
return " octillion";
case 8:
return " septillion";
case 7:
return " sextillion";
case 6:
return " quintrillion";
case 5:
return " quadrillion";
case 4:
return " trillion";
case 3:
return " billion";
case 2:
return " million";
case 1:
return " thousand";
case 0:
return "";
}
}
function convertThreeDigit($digit1, $digit2, $digit3)
{
$buffer = "";
if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0")
{
return "";
}
if ($digit1 != "0")
{
$buffer .= convertDigit($digit1) . " hundred";
if ($digit2 != "0" || $digit3 != "0")
{
$buffer .= " and ";
}
}
if ($digit2 != "0")
{
$buffer .= convertTwoDigit($digit2, $digit3);
}
else if ($digit3 != "0")
{
$buffer .= convertDigit($digit3);
}
return $buffer;
}
function convertTwoDigit($digit1, $digit2)
{
if ($digit2 == "0")
{
switch ($digit1)
{
case "1":
return "ten";
case "2":
return "twenty";
case "3":
return "thirty";
case "4":
return "forty";
case "5":
return "fifty";
case "6":
return "sixty";
case "7":
return "seventy";
case "8":
return "eighty";
case "9":
return "ninety";
}
} else if ($digit1 == "1")
{
switch ($digit2)
{
case "1":
return "eleven";
case "2":
return "twelve";
case "3":
return "thirteen";
case "4":
return "fourteen";
case "5":
return "fifteen";
case "6":
return "sixteen";
case "7":
return "seventeen";
case "8":
return "eighteen";
case "9":
return "nineteen";
}
} else
{
$temp = convertDigit($digit2);
switch ($digit1)
{
case "2":
return "twenty-$temp";
case "3":
return "thirty-$temp";
case "4":
return "forty-$temp";
case "5":
return "fifty-$temp";
case "6":
return "sixty-$temp";
case "7":
return "seventy-$temp";
case "8":
return "eighty-$temp";
case "9":
return "ninety-$temp";
}
}
}
function convertDigit($digit)
{
switch ($digit)
{
case "0":
return "zero";
case "1":
return "one";
case "2":
return "two";
case "3":
return "three";
case "4":
return "four";
case "5":
return "five";
case "6":
return "six";
case "7":
return "seven";
case "8":
return "eight";
case "9":
return "nine";
}
}
```
|
277,589 |
<p>How to perform validation for a radio button group (one radio button should be selected) using jQuery validation plugin?</p>
|
[
{
"answer_id": 1843196,
"author": "Mahes",
"author_id": 301960,
"author_profile": "https://Stackoverflow.com/users/301960",
"pm_score": 5,
"selected": false,
"text": "<p>use the following rule for validating radio button group selection</p>\n\n<pre><code>myRadioGroupName : {required :true}\n</code></pre>\n\n<p>myRadioGroupName is the value you have given to name attribute</p>\n"
},
{
"answer_id": 3347969,
"author": "Brandon Rome",
"author_id": 403864,
"author_profile": "https://Stackoverflow.com/users/403864",
"pm_score": 7,
"selected": false,
"text": "<p>With newer releases of jquery (1.3+ I think), all you have to do is set one of the members of the radio set to be required and jquery will take care of the rest:</p>\n\n<pre><code><input type=\"radio\" name=\"myoptions\" value=\"blue\" class=\"required\"> Blue<br />\n<input type=\"radio\" name=\"myoptions\" value=\"red\"> Red<br />\n<input type=\"radio\" name=\"myoptions\" value=\"green\"> Green\n</code></pre>\n\n<p>The above would require at least 1 of the 3 radio options w/ the name of \"my options\" to be selected before proceeding.</p>\n\n<p>The label suggestion by Mahes, btw, works wonderfully!</p>\n"
},
{
"answer_id": 3540045,
"author": "Haider Abbas",
"author_id": 422262,
"author_profile": "https://Stackoverflow.com/users/422262",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use this:</p>\n\n<pre><code><fieldset>\n<input type=\"radio\" name=\"myoptions[]\" value=\"blue\"> Blue<br />\n<input type=\"radio\" name=\"myoptions[]\" value=\"red\"> Red<br />\n<input type=\"radio\" name=\"myoptions[]\" value=\"green\"> Green<br />\n<label for=\"myoptions[]\" class=\"error\" style=\"display:none;\">Please choose one.</label>\n</fieldset>\n</code></pre>\n\n<p>and simply add this rule</p>\n\n<pre><code>rules: {\n 'myoptions[]':{ required:true }\n}\n</code></pre>\n\n<p>Mention how to add rules. </p>\n"
},
{
"answer_id": 5984371,
"author": "Cin",
"author_id": 165963,
"author_profile": "https://Stackoverflow.com/users/165963",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem. Wound up just writing a custom highlight and unhighlight function for the validator. Adding this to the validaton options should add the error class to the element and its respective label:</p>\n\n<pre><code> 'highlight': function (element, errorClass, validClass) {\n if($(element).attr('type') == 'radio'){\n $(element.form).find(\"input[type=radio]\").each(function(which){\n $(element.form).find(\"label[for=\" + this.id + \"]\").addClass(errorClass);\n $(this).addClass(errorClass);\n });\n } else {\n $(element.form).find(\"label[for=\" + element.id + \"]\").addClass(errorClass);\n $(element).addClass(errorClass);\n }\n },\n 'unhighlight': function (element, errorClass, validClass) {\n if($(element).attr('type') == 'radio'){\n $(element.form).find(\"input[type=radio]\").each(function(which){\n $(element.form).find(\"label[for=\" + this.id + \"]\").removeClass(errorClass);\n $(this).removeClass(errorClass);\n });\n }else {\n $(element.form).find(\"label[for=\" + element.id + \"]\").removeClass(errorClass);\n $(element).removeClass(errorClass);\n }\n },\n</code></pre>\n"
},
{
"answer_id": 12411759,
"author": "strudeltercero",
"author_id": 1614519,
"author_profile": "https://Stackoverflow.com/users/1614519",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to validate is like this.</p>\n\n<pre><code>var $radio = $('input:radio[name=\"nameRadioButton\"]');\n$radio.addClass(\"validate[required]\");\n</code></pre>\n\n<p>I hope my example will help you</p>\n"
},
{
"answer_id": 13293266,
"author": "Matt Frear",
"author_id": 32598,
"author_profile": "https://Stackoverflow.com/users/32598",
"pm_score": 3,
"selected": false,
"text": "<p>As per Brandon's answer. But if you're using ASP.NET MVC which uses unobtrusive validation, you can add the data-val attribute to the first one. I also like to have labels for each radio button for usability.</p>\n\n<pre><code><span class=\"field-validation-valid\" data-valmsg-for=\"color\" data-valmsg-replace=\"true\"></span>\n<p><input type=\"radio\" name=\"color\" id=\"red\" value=\"R\" data-val=\"true\" data-val-required=\"Please choose one of these options:\"/> <label for=\"red\">Red</label></p>\n<p><input type=\"radio\" name=\"color\" id=\"green\" value=\"G\"/> <label for=\"green\">Green</label></p>\n<p><input type=\"radio\" name=\"color\" id=\"blue\" value=\"B\"/> <label for=\"blue\">Blue</label></p>\n</code></pre>\n"
},
{
"answer_id": 22778329,
"author": "Sayli Vaidya",
"author_id": 3340684,
"author_profile": "https://Stackoverflow.com/users/3340684",
"pm_score": 2,
"selected": false,
"text": "<p>code for radio button -</p>\n<pre class=\"lang-html prettyprint-override\"><code><div>\n <span class="radio inline" style="margin-right: 10px;">@Html.RadioButton("Gender", "Female",false) Female</span>\n <span class="radio inline" style="margin-right: 10px;">@Html.RadioButton("Gender", "Male",false) Male</span>\n <div class='GenderValidation' style="color:#ee8929;"></div>\n</div>\n\n<input class="btn btn-primary" type="submit" value="Create" id="create"/>\n</code></pre>\n<p>and jQuery code-</p>\n<pre class=\"lang-js prettyprint-override\"><code>$(document).ready(function () {\n $('#create').click(function(){\n var gender=$('#Gender').val();\n\n if ($("#Gender:checked").length == 0) {\n $('.GenderValidation').text("Gender is required.");\n return false;\n }\n });\n});\n</code></pre>\n"
},
{
"answer_id": 55928886,
"author": "Sonobor",
"author_id": 2066416,
"author_profile": "https://Stackoverflow.com/users/2066416",
"pm_score": 0,
"selected": false,
"text": "<p>Puts the error message on top.</p>\n<pre class=\"lang-css prettyprint-override\"><code>.radio-group {\n position: relative;\n margin-top: 40px;\n} \n\n#myoptions-error {\n position: absolute; \n top: -25px;\n}\n</code></pre>\n<pre class=\"lang-html prettyprint-override\"><code><div class="radio-group"> \n <input type="radio" name="myoptions" value="blue" class="required"> Blue<br /> \n <input type="radio" name="myoptions" value="red"> Red<br /> \n <input type="radio" name="myoptions" value="green"> Green\n</div><!-- end radio-group -->\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27052/"
] |
How to perform validation for a radio button group (one radio button should be selected) using jQuery validation plugin?
|
With newer releases of jquery (1.3+ I think), all you have to do is set one of the members of the radio set to be required and jquery will take care of the rest:
```
<input type="radio" name="myoptions" value="blue" class="required"> Blue<br />
<input type="radio" name="myoptions" value="red"> Red<br />
<input type="radio" name="myoptions" value="green"> Green
```
The above would require at least 1 of the 3 radio options w/ the name of "my options" to be selected before proceeding.
The label suggestion by Mahes, btw, works wonderfully!
|
277,607 |
<p>After tinkering around to solve [this][1] problem, I think the core of the problem is the following:</p>
<p>When you use the Html.RadioButton() html helper with an Enum as value field, you can only choose your option once. AFter reposting the page, the helpers will ignore the value set in the call and set all radio buttons to the same value, being the value you selected the previous post back.
Am I doing something wrong?</p>
<p><em>Example (watch the <strong>value</strong> of the buttons)</em></p>
<pre><code><fieldset>
<legend>Test</legend>
<div>
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Any" , ViewData.Model.SearchBag.EffectIndicatorIsAny, new { @id = "SearchBag.EffectIndicatorAny" })%>
</div>
<div>
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Solid", ViewData.Model.SearchBag.EffectIndicatorIsSolid, new { @id = "SearchBag.EffectIndicatorSolid" })%>
</div>
<div>
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Effect", ViewData.Model.SearchBag.EffectIndicatorIsEffect, new { @id = "SearchBag.EffectIndicatorEffect" })%>
</div>
</fieldset>
</code></pre>
<p>Will generate </p>
<pre><code><fieldset>
<legend>Effect</legend>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<input checked="checked" id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Any" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<input id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Effect" />
</div>
</fieldset>
</code></pre>
<p>And will generate the second time:</p>
<pre><code><fieldset>
<legend>Effect</legend>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<input id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<input checked="checked" id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
</fieldset>
</code></pre>
|
[
{
"answer_id": 277671,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 0,
"selected": false,
"text": "<p>One thing to check. Are you using the updated model to render your view? I.e. is the same model data that was updated from the post passed to the view the second time it's displayed?</p>\n"
},
{
"answer_id": 279563,
"author": "Sia",
"author_id": 20168,
"author_profile": "https://Stackoverflow.com/users/20168",
"pm_score": 3,
"selected": true,
"text": "<p>This is due to a bug in the ASP.NET MVC Beta code. I wrote a full explanation of the issue at asp.net MVC forum. Refer to this <a href=\"http://forums.asp.net/t/1338576.aspx\" rel=\"nofollow noreferrer\">link</a></p>\n"
},
{
"answer_id": 283605,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 1,
"selected": false,
"text": "<p>In case anybody cares here is a real quick and dirty work around in anticipation for the next update of the framework. It only regexreplaces the value with your value.\nIt's not unit tested, not guaranteed not whatever.</p>\n\n<p>Put it in your HtmlHelper class library or wherever you put HtmlHelper extentions.\nadd the following usings:</p>\n\n<ul>\n<li>System.Text.RegularExpressions;</li>\n<li><p>System.Web.Mvc.Html;</p>\n\n<pre><code>/*ToDo: remove when patched in framework*/\npublic static string MonkeyPatchedRadio(this HtmlHelper htmlHelper, string name, object value, bool isChecked, object htmlAttributes){\n string monkeyString = htmlHelper.RadioButton(name, value, isChecked, htmlAttributes);\n monkeyString = Regex.Replace(monkeyString, \"(?<=value=\\\").*(?=\\\".*)\", value.ToString()); \n return monkeyString;\n}\n</code></pre></li>\n</ul>\n\n<p>I know it can be done better and whatnot, but I really hope it will be fixed soon anyway.\nIf you feel like making it better, it's community wiki, so go ahead</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
After tinkering around to solve [this][1] problem, I think the core of the problem is the following:
When you use the Html.RadioButton() html helper with an Enum as value field, you can only choose your option once. AFter reposting the page, the helpers will ignore the value set in the call and set all radio buttons to the same value, being the value you selected the previous post back.
Am I doing something wrong?
*Example (watch the **value** of the buttons)*
```
<fieldset>
<legend>Test</legend>
<div>
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Any" , ViewData.Model.SearchBag.EffectIndicatorIsAny, new { @id = "SearchBag.EffectIndicatorAny" })%>
</div>
<div>
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Solid", ViewData.Model.SearchBag.EffectIndicatorIsSolid, new { @id = "SearchBag.EffectIndicatorSolid" })%>
</div>
<div>
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Effect", ViewData.Model.SearchBag.EffectIndicatorIsEffect, new { @id = "SearchBag.EffectIndicatorEffect" })%>
</div>
</fieldset>
```
Will generate
```
<fieldset>
<legend>Effect</legend>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<input checked="checked" id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Any" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<input id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Effect" />
</div>
</fieldset>
```
And will generate the second time:
```
<fieldset>
<legend>Effect</legend>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<input id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<input checked="checked" id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
</fieldset>
```
|
This is due to a bug in the ASP.NET MVC Beta code. I wrote a full explanation of the issue at asp.net MVC forum. Refer to this [link](http://forums.asp.net/t/1338576.aspx)
|
277,618 |
<ul>
<li>What exactly is a learning curve?</li>
<li>And why is it wrong to use the term "steep learning curve" for something which has high entry barriers and takes quite some time to get into?</li>
</ul>
<p>As to the why-ness of this question:</p>
<ul>
<li>The terms are used often and inconsistently on Stack Overflow</li>
<li>I myself have been confused by it</li>
<li>Mostly the newbies are confronted with these terms when they for example ask questions like "what's the best php development framework"</li>
</ul>
|
[
{
"answer_id": 277631,
"author": "markus",
"author_id": 11995,
"author_profile": "https://Stackoverflow.com/users/11995",
"pm_score": 3,
"selected": false,
"text": "<p>from Widipedia:</p>\n\n<blockquote>\n <p>The term learning curve refers to the\n graphical relation between the amount\n of learning and the time it takes to\n learn.</p>\n</blockquote>\n\n<p>The term \"steep learning curve\" is often <strong>wrongly</strong> used for things which need some time to wrap ones mind around. Also here on Stack Overflow I've seen it used wrongly many times and hence this Question and my own answer to it.</p>\n\n<p><strong>In fact a steep learning curve is given, when it is relatively easy to start of with a new skill/technique/...</strong></p>\n\n<p>it means that the relationship between \"learning progress (y)\" and \"time invested (x)\" is greater than 1.</p>\n"
},
{
"answer_id": 277632,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p>It's a curve of time versus proficiency.</p>\n\n<p>Steep for hard is wrong because it'd mean that you get very proficient in very little time</p>\n\n<pre>\n\nproficiency\n | __\n | |\n | | Proficient in little time (steep = easy)\n | |\n |_/____________\n time\n\nproficiency\n |\n | Proficient in lots of time (gentle = hard)\n | __ \n | /\n |__________/___\n time\n\n</pre>\n"
},
{
"answer_id": 277635,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "<p>See <a href=\"http://en.wikipedia.org/wiki/Learning_curve\" rel=\"noreferrer\">wikipedia</a>.</p>\n\n<p>\"steep learning curve\" is a buzz-phrase that doesn't have any actual meaning. It used to mean that you'd make quick progress. \"Over time, the misapprehension has emerged that a \"steep\" learning curve means that something requires a great deal of effort to learn...\"</p>\n\n<p>Conclusion: people who use the phrase don't know that it's unclear. You should get details from them on what specific things are hard to learn and get past the buzz-phrases and platitudes.</p>\n"
},
{
"answer_id": 277639,
"author": "Vatine",
"author_id": 34771,
"author_profile": "https://Stackoverflow.com/users/34771",
"pm_score": 2,
"selected": false,
"text": "<p>There are a few possible interpretation of \"learning curve\", but a fairly natural one would be \"time elapsed\" on the X axis and \"knowledge gained\" on the Y axis. A steep curve, in that mapping, would imply that you gain a lot of knowledge, fast.</p>\n\n<p>The only interpretation I can think of where \"steep\" is the same as \"hard\" is where you map \"knowledge gained\" on the X axis and \"effort expended\" on the Y axis and that is not a very natural mapping.</p>\n"
},
{
"answer_id": 277651,
"author": "Richard Dorman",
"author_id": 1199234,
"author_profile": "https://Stackoverflow.com/users/1199234",
"pm_score": 1,
"selected": false,
"text": "<p>Learning curve is the rate at which knowledge can can acquired. A new developer on a complex system will likely experience a steep learning curve as they will have a lot to learn before they can become productive. By implication an experienced developer may experience a shallow learning curve if they are familiar with a system.</p>\n\n<p>The acquisition of knowledge does not always imply understanding. In some cases a developer may not need to absorb a lot of system detail but may need to understand underlying designs before they can be productive. This can take time but does not imply a steep learning curve.</p>\n\n<p>In practise understanding and knowledge go hand in hand. Most developers will always be on a learning curve of some sort but will also be using new knowledge to forge a deeper understanding of the systems they are working as well as the tools and practises they are using.</p>\n"
},
{
"answer_id": 277657,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 3,
"selected": false,
"text": "<p>It's a battle of intuitiveness. On one hand, you've got \"steep=hard to climb\" association, on the other hand you have \"time on the horizontal axis\" convention (but \"proficiency on the horizontal axis\" isn't \"wrong\", just \"less popular\"). So, IMHO it's not a matter of \"right\" vs \"wrong\" but rather \"intuitive\" vs \"more intuitive\".</p>\n\n<p>I think that \"steep=hard to climb\" will win, because it appeals to anyone who at any point in their life has climbed a stair, as opposed to the x-y curve which even people trained in mathematics sometimes mix up.</p>\n"
},
{
"answer_id": 277659,
"author": "Adam Jaskiewicz",
"author_id": 35322,
"author_profile": "https://Stackoverflow.com/users/35322",
"pm_score": 3,
"selected": false,
"text": "<p>I've generally understood it to have more to do with the amount of time allotted to learning, and what you have to learn in that period of time. If you have only a short amount of time in which to learn something, your learning curve is going to be much steeper than if you had a longer amount of time to learn the same amount of material. So a steep learning curve IS difficult because it means you're trying to cram six months worth of learning into three weeks, or whatever.</p>\n\n<p>More material in the same amount of time would produce the same curve.</p>\n"
},
{
"answer_id": 277752,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "<p>It's true that <strong>\"steep learning curve\" <em>should</em> mean \"easy\"</strong> given the origin of the learning curve as a graph of measured performance as a function of time, and that the proper expression for a hard-to-learn-task should be \"gradual learning curve\". But it's perfectly natural that \"steep learning curve\" should have come to mean \"hard\" given that a) most people have never looked at an actual learning curve, and b) \"steep\" implies \"difficult\" whereas \"gradual\" implies \"easy\".</p>\n\n<p>This is how languages evolve, and it would be utterly futile to try and change the general usage of this term now. And, in any event, <strong>I could care less</strong> about the whole issue (see how you still knew exactly what I meant?).</p>\n"
},
{
"answer_id": 277794,
"author": "bendin",
"author_id": 33412,
"author_profile": "https://Stackoverflow.com/users/33412",
"pm_score": 4,
"selected": false,
"text": "<p>(from <code>unix.rulez.org/~calver</code>)</p>\n\n<p><a href=\"https://i.stack.imgur.com/EaXAn.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EaXAn.jpg\" alt=\"classical learning curves for some common editors\"></a><br>\n<sub>(source: <a href=\"http://unix.rulez.org/~calver/pictures/curves.jpg\" rel=\"nofollow noreferrer\">rulez.org</a>)</sub> </p>\n\n<p>This (very unserious) diagram subscribes to the steep == \"hard to climb\" interpretation, for anyone keeping score. Emacs. So true. ;-) </p>\n"
},
{
"answer_id": 4685968,
"author": "Steve",
"author_id": 574967,
"author_profile": "https://Stackoverflow.com/users/574967",
"pm_score": 1,
"selected": false,
"text": "<p>Level of difficulty is not a factor. A learning curve depicts the length of time to acquire a proficient skill set or high level of comprehension. The description will vary based on the test subject that the curve is applied to. While one can certainly say that the learning curve for acquiring proficiency of an application such as MS Notepad would be steep, another application for the curve would be the length of time individual test subject take to acquire such proficiency. The learning curve for acquiring proficiency of MS Notepad is generally steep, but it may be steeper for Mary than it is for John. </p>\n\n<p>I think the key is to first understand what the curve is being applied to </p>\n"
},
{
"answer_id": 4951254,
"author": "Curmudgeon",
"author_id": 610522,
"author_profile": "https://Stackoverflow.com/users/610522",
"pm_score": 2,
"selected": false,
"text": "<p>A \"learning curve\" originally had total elapsed time [or total cumulative units manufactured/learned] on the X axis and the time required to produce/learn a single unit on the y axis. Your first unit always takes more time than the 100th or 1,000th. The \"steepness\" of the curve depends on how fast you get good at producing/learning a thing. Learn quickly and you have a \"steep\" curve; slowly and you have a flat curve. </p>\n\n<p>I agree that the uninformed have morphed the original meaning of the term, but to be accurate <strong>steep is easy</strong>. People get upset because those of us who paid attention to using language correctly in school rarely get to take part in this type of evolution. </p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
* What exactly is a learning curve?
* And why is it wrong to use the term "steep learning curve" for something which has high entry barriers and takes quite some time to get into?
As to the why-ness of this question:
* The terms are used often and inconsistently on Stack Overflow
* I myself have been confused by it
* Mostly the newbies are confronted with these terms when they for example ask questions like "what's the best php development framework"
|
It's a curve of time versus proficiency.
Steep for hard is wrong because it'd mean that you get very proficient in very little time
```
proficiency
| __
| |
| | Proficient in little time (steep = easy)
| |
|_/____________
time
proficiency
|
| Proficient in lots of time (gentle = hard)
| __
| /
|__________/___
time
```
|
277,623 |
<p>I'm trying to get a Server application to expose some status information using WCF.
In particular I'm after using WCF services with RESTful "API".
I'm hitting somewhat of a wall when it comes to consuming the REST api from a silverlight
app/page that I want to have as an additional type of client...</p>
<p>So far I've been successful in defining a status interface:</p>
<pre><code>public static class StatusUriTemplates
{
public const string Status = "/current-status";
public const string StatusJson = "/current-status/json";
public const string StatusXml = "/current-status/xml";
}
[ServiceContract]
public interface IStatusService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = StatusUriTemplates.StatusJson)]
StatusResultSet GetProgressAsJson();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = StatusUriTemplates.StatusXml)]
StatusResultSet GetProgressAsXml();
[OperationContract]
[WebGet(UriTemplate = StatusUriTemplates.Status)]
StatusResultSet GetProgress();
}
</code></pre>
<p>Implementing it in the server:</p>
<pre><code> [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class ServerStatusService : IStatusService
{
public StatusResultSet GetProgressAsJson()
{ return GetProgress(); }
public StatusResultSet GetProgressAsXml()
{ return GetProgress(); }
public StatusResultSet GetProgress()
{
return StatusResultSet.Empty;
}
}
</code></pre>
<p>Exposing it from my code at runtime:</p>
<pre><code> var service = new ServerStatusService();
var binding = new WebHttpBinding();
var behavior = new WebHttpBehavior();
var host = new WebServiceHost(service, new Uri("http://localhost:8000/server"));
host.AddServiceEndpoint(typeof(IStatusService), binding, "status");
host.Open();
</code></pre>
<p>I've even been successful with consuming the service from a .NET console/winfoems/WPF application using something along the line of this:</p>
<pre><code> var cf = new WebChannelFactory<IStatusService>(new Uri("http://localhost:8000/server/status"));
var ss = cf.CreateChannel();
Console.WriteLine(ss.GetProgress().TimeStamp);
</code></pre>
<p>The "wall" I'm hitting is that there is NO WebChannelFactory for SliverLight.</p>
<p>Period.</p>
<p>This means that when it comes to silverlight code, my options are:</p>
<ul>
<li>Write ugly code using WebClient,
which ultimately means I will have
to update two sets of code whenever
I have a change to my API </li>
<li>Use SOAP/WS for the WebService and keep
updating the service reference from
Visual Studio</li>
</ul>
<p>Is there a way to keep the "clean" implementation with WebChannelFactory in SilverLight?
Perhaps a public domain / open source WebChannelFactory for SilverLight?</p>
<p>Any help with this will be greatly appreciated!</p>
|
[
{
"answer_id": 283260,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 1,
"selected": false,
"text": "<p>I almost hate to suggest it but would you feel comfortable with <a href=\"http://msdn.microsoft.com/en-us/library/ms405827(VS.95).aspx\" rel=\"nofollow noreferrer\" title=\"ChannelFactoryBase<TChannel>\">reimplementing the WebChannelFactory<T> class</a>?</p>\n\n<p>From a cursory glance through the Silverlight API it looks like you won't get much help from Microsoft out of the box. You'd need to reimplement a channel class and a factory for it.</p>\n\n<p>Perhaps another way to create the channel and to isolate yourself from the platform-specific code is to create a custom implementation of it? Specifically what I mean is, you create yet another factory class, and the factory class either calls to the WebChannelFactory when it's available, or goes through the hoops of setting it up for you.</p>\n\n<p>Sorry I don't have a more in-depth suggestion. :)</p>\n"
},
{
"answer_id": 314685,
"author": "Donn Felker",
"author_id": 5210,
"author_profile": "https://Stackoverflow.com/users/5210",
"pm_score": 1,
"selected": false,
"text": "<p>If this is a simple Xml REST service, why not use the WebClient in Silverlight to capture the XML using Linq to XML? I know you said its messy, but it all depends on how you look at it. if you change your service interface at anytime you're going to have to update your code in multiple places. Thats just the way it is. </p>\n\n<p>So to do this, you will need to capture the data in an async fashion from the WebClient and then parse it with LINQ to XML. </p>\n\n<p>Time Heuer has a good example on his site: <a href=\"http://timheuer.com/blog/archive/2008/03/14/calling-web-services-with-silverlight-2.aspx\" rel=\"nofollow noreferrer\">http://timheuer.com/blog/archive/2008/03/14/calling-web-services-with-silverlight-2.aspx</a></p>\n\n<p>Essentially, it looks like this: </p>\n\n<pre><code>WebClient rest = new WebClient();\nrest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(rest_DownloadStringCompleted);\nrest.DownloadStringAsync(new Uri(\"http://example.org/current-status/xml\"));\n</code></pre>\n\n<p>Then in your \"rest_DownloadStringCompleted\" you'd parse the string as XML. Like so: </p>\n\n<pre><code>string data = e.Result;\nstring url = string.Empty;\n\nXDocument doc = XDocument.Parse(e.Result);\nvar myResults = from results in doc.Descendants(\"myXmlElement\") ... blah blah blah \n</code></pre>\n\n<p>I've done the same thing with home grown REST Services from WCF and Silverlight and it worked great.</p>\n"
},
{
"answer_id": 5728193,
"author": "angularsen",
"author_id": 134761,
"author_profile": "https://Stackoverflow.com/users/134761",
"pm_score": 1,
"selected": false,
"text": "<p>So far I have found a few alternatives to WebChannelFactory for consuming REST services in Silverlight. They have all seen praise in forums and blogs, but I have yet to try any of them myself. I believe all three use generics to easily deserialize request responses into CLR objects.</p>\n\n<ul>\n<li><a href=\"https://github.com/johnsheehan/RestSharp/wiki/Recommended-Usage\" rel=\"nofollow\">RestSharp</a></li>\n<li><a href=\"http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight\" rel=\"nofollow\">REST Client for Silverlight</a>, ported from WCF REST Starter Kit</li>\n<li><a href=\"http://hammock.codeplex.com/documentation\" rel=\"nofollow\">Hammock</a></li>\n</ul>\n\n<p>I am leaning towards RestSharp, because its examples look both simple and extensible to me. </p>\n"
},
{
"answer_id": 5744346,
"author": "bbaia",
"author_id": 469114,
"author_profile": "https://Stackoverflow.com/users/469114",
"pm_score": 1,
"selected": false,
"text": "<p>You are missing Spring.Rest :\n<a href=\"http://springframework.net/index.html#spring-rest-1.0.0-released\" rel=\"nofollow\">http://springframework.net/index.html#spring-rest-1.0.0-released</a></p>\n"
},
{
"answer_id": 6319028,
"author": "T. Webster",
"author_id": 266457,
"author_profile": "https://Stackoverflow.com/users/266457",
"pm_score": 0,
"selected": false,
"text": "<p>I recently ran into the same problem and decided to create a class that has a simplified REST client interface for Silverlight, more or less like WebChannelFactory. Has synchronous-like behavior also.</p>\n\n<p><a href=\"http://regular-language.blogspot.com/2011/06/wcf-webhttp-rest-client-for-silverlight.html\" rel=\"nofollow\">http://regular-language.blogspot.com/2011/06/wcf-webhttp-rest-client-for-silverlight.html</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9172/"
] |
I'm trying to get a Server application to expose some status information using WCF.
In particular I'm after using WCF services with RESTful "API".
I'm hitting somewhat of a wall when it comes to consuming the REST api from a silverlight
app/page that I want to have as an additional type of client...
So far I've been successful in defining a status interface:
```
public static class StatusUriTemplates
{
public const string Status = "/current-status";
public const string StatusJson = "/current-status/json";
public const string StatusXml = "/current-status/xml";
}
[ServiceContract]
public interface IStatusService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = StatusUriTemplates.StatusJson)]
StatusResultSet GetProgressAsJson();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = StatusUriTemplates.StatusXml)]
StatusResultSet GetProgressAsXml();
[OperationContract]
[WebGet(UriTemplate = StatusUriTemplates.Status)]
StatusResultSet GetProgress();
}
```
Implementing it in the server:
```
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class ServerStatusService : IStatusService
{
public StatusResultSet GetProgressAsJson()
{ return GetProgress(); }
public StatusResultSet GetProgressAsXml()
{ return GetProgress(); }
public StatusResultSet GetProgress()
{
return StatusResultSet.Empty;
}
}
```
Exposing it from my code at runtime:
```
var service = new ServerStatusService();
var binding = new WebHttpBinding();
var behavior = new WebHttpBehavior();
var host = new WebServiceHost(service, new Uri("http://localhost:8000/server"));
host.AddServiceEndpoint(typeof(IStatusService), binding, "status");
host.Open();
```
I've even been successful with consuming the service from a .NET console/winfoems/WPF application using something along the line of this:
```
var cf = new WebChannelFactory<IStatusService>(new Uri("http://localhost:8000/server/status"));
var ss = cf.CreateChannel();
Console.WriteLine(ss.GetProgress().TimeStamp);
```
The "wall" I'm hitting is that there is NO WebChannelFactory for SliverLight.
Period.
This means that when it comes to silverlight code, my options are:
* Write ugly code using WebClient,
which ultimately means I will have
to update two sets of code whenever
I have a change to my API
* Use SOAP/WS for the WebService and keep
updating the service reference from
Visual Studio
Is there a way to keep the "clean" implementation with WebChannelFactory in SilverLight?
Perhaps a public domain / open source WebChannelFactory for SilverLight?
Any help with this will be greatly appreciated!
|
I almost hate to suggest it but would you feel comfortable with [reimplementing the WebChannelFactory<T> class](http://msdn.microsoft.com/en-us/library/ms405827(VS.95).aspx "ChannelFactoryBase<TChannel>")?
From a cursory glance through the Silverlight API it looks like you won't get much help from Microsoft out of the box. You'd need to reimplement a channel class and a factory for it.
Perhaps another way to create the channel and to isolate yourself from the platform-specific code is to create a custom implementation of it? Specifically what I mean is, you create yet another factory class, and the factory class either calls to the WebChannelFactory when it's available, or goes through the hoops of setting it up for you.
Sorry I don't have a more in-depth suggestion. :)
|
277,630 |
<p>Is it possible to use a DB sequence for some column that <strong>is not the identifier/is not part of a composite identifier</strong>? </p>
<p>I'm using hibernate as jpa provider, and I have a table that has some columns that are generated values (using a sequence), although they are not part of the identifier.</p>
<p>What I want is to use a sequence to create a new value for an entity, where the column for the sequence is <strong>NOT</strong> (part of) the primary key:</p>
<pre><code>@Entity
@Table(name = "MyTable")
public class MyEntity {
//...
@Id //... etc
public Long getId() {
return id;
}
//note NO @Id here! but this doesn't work...
@GeneratedValue(strategy = GenerationType.AUTO, generator = "myGen")
@SequenceGenerator(name = "myGen", sequenceName = "MY_SEQUENCE")
@Column(name = "SEQ_VAL", unique = false, nullable = false, insertable = true, updatable = true)
public Long getMySequencedValue(){
return myVal;
}
}
</code></pre>
<p>Then when I do this:</p>
<pre><code>em.persist(new MyEntity());
</code></pre>
<p>the id will be generated, but the <code>mySequenceVal</code> property will be also generated by my JPA provider.</p>
<p>Just to make things clear: I want <strong>Hibernate</strong> to generate the value for the <code>mySequencedValue</code> property. I know Hibernate can handle database-generated values, but I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property. If Hibernate can generate values for primary keys, why can't it generate for a simple property?</p>
|
[
{
"answer_id": 282774,
"author": "Frederic Morin",
"author_id": 4064,
"author_profile": "https://Stackoverflow.com/users/4064",
"pm_score": -1,
"selected": false,
"text": "<p>I've been in a situation like you (JPA/Hibernate sequence for non @Id field) and I ended up creating a trigger in my db schema that add a unique sequence number on insert. I just never got it to work with JPA/Hibernate</p>\n"
},
{
"answer_id": 283603,
"author": "alasdairg",
"author_id": 15768,
"author_profile": "https://Stackoverflow.com/users/15768",
"pm_score": 4,
"selected": false,
"text": "<p>Hibernate definitely supports this. From the docs:</p>\n\n<p>\"Generated properties are properties which have their values generated by the database. Typically, Hibernate applications needed to refresh objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. Essentially, whenever Hibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties, it immediately issues a select afterwards to retrieve the generated values.\"</p>\n\n<p>For properties generated on insert only, your property mapping (.hbm.xml) would look like:</p>\n\n<pre><code><property name=\"foo\" generated=\"insert\"/>\n</code></pre>\n\n<p>For properties generated on insert and update your property mapping (.hbm.xml) would look like:</p>\n\n<pre><code><property name=\"foo\" generated=\"always\"/>\n</code></pre>\n\n<p>Unfortunately, I don't know JPA, so I don't know if this feature is exposed via JPA (I suspect possibly not)</p>\n\n<p>Alternatively, you should be able to exclude the property from inserts and updates, and then \"manually\" call session.refresh( obj ); after you have inserted/updated it to load the generated value from the database.</p>\n\n<p>This is how you would exclude the property from being used in insert and update statements:</p>\n\n<pre><code><property name=\"foo\" update=\"false\" insert=\"false\"/>\n</code></pre>\n\n<p>Again, I don't know if JPA exposes these Hibernate features, but Hibernate does support them.</p>\n"
},
{
"answer_id": 296071,
"author": "alasdairg",
"author_id": 15768,
"author_profile": "https://Stackoverflow.com/users/15768",
"pm_score": 0,
"selected": false,
"text": "<p>\"I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property\"</p>\n\n<p>In that case, how about creating an implementation of UserType which generates the required value, and configuring the metadata to use that UserType for persistence of the mySequenceVal property?</p>\n"
},
{
"answer_id": 308918,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I run in the same situation like you and I also didn't find any serious answers if it is basically possible to generate non-id propertys with JPA or not.</p>\n\n<p>My solution is to call the sequence with a native JPA query to set the property by hand before persisiting it.</p>\n\n<p>This is not satisfying but it works as a workaround for the moment.</p>\n\n<p>Mario</p>\n"
},
{
"answer_id": 536102,
"author": "Morten Berg",
"author_id": 36120,
"author_profile": "https://Stackoverflow.com/users/36120",
"pm_score": 8,
"selected": true,
"text": "<p>Looking for answers to this problem, I stumbled upon <a href=\"http://forum.hibernate.org/viewtopic.php?p=2405140\" rel=\"noreferrer\">this link</a></p>\n\n<p>It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The <code>@GeneratedValue</code> annotation is only used in conjunction with <code>@Id</code> to create auto-numbers.</p>\n\n<p>The <code>@GeneratedValue</code> annotation just tells Hibernate that the database is generating this value itself.</p>\n\n<p>The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this:</p>\n\n<pre>\n@Entity\npublic class GeneralSequenceNumber {\n @Id\n @GeneratedValue(...)\n private Long number;\n}\n\n@Entity \npublic class MyEntity {\n @Id ..\n private Long id;\n\n @OneToOne(...)\n private GeneralSequnceNumber myVal;\n}\n</pre>\n"
},
{
"answer_id": 1717889,
"author": "kammy",
"author_id": 209014,
"author_profile": "https://Stackoverflow.com/users/209014",
"pm_score": 0,
"selected": false,
"text": "<p>This is not the same as using a sequence. When using a sequence, you are not inserting or updating anything. You are simply retrieving the next sequence value. It looks like hibernate does not support it.</p>\n"
},
{
"answer_id": 2669182,
"author": "Paul",
"author_id": 290849,
"author_profile": "https://Stackoverflow.com/users/290849",
"pm_score": 3,
"selected": false,
"text": "<p>As a followup here's how I got it to work:</p>\n\n<pre><code>@Override public Long getNextExternalId() {\n BigDecimal seq =\n (BigDecimal)((List)em.createNativeQuery(\"select col_msd_external_id_seq.nextval from dual\").getResultList()).get(0);\n return seq.longValue();\n}\n</code></pre>\n"
},
{
"answer_id": 4270743,
"author": "Gustavo Orair",
"author_id": 519289,
"author_profile": "https://Stackoverflow.com/users/519289",
"pm_score": 2,
"selected": false,
"text": "<p>I've found this specific note in session 9.1.9 GeneratedValue Annotation from JPA specification:\n\"[43] Portable applications should not use the GeneratedValue annotation on other persistent fields or properties.\"\nSo, I presume that it is not possible to auto generate value for non primary key values at least using simply JPA.</p>\n"
},
{
"answer_id": 10647933,
"author": "Sergey Vedernikov",
"author_id": 620858,
"author_profile": "https://Stackoverflow.com/users/620858",
"pm_score": 6,
"selected": false,
"text": "<p>I found that <code>@Column(columnDefinition="serial")</code> works perfect but only for PostgreSQL. For me this was perfect solution, because second entity is "ugly" option.</p>\n<p>A call to <code>saveAndFlush</code> on the entity is also necessary, and <code>save</code> won't be enough to populate the value from the DB.</p>\n"
},
{
"answer_id": 11842769,
"author": "Sebastian Götz",
"author_id": 1482214,
"author_profile": "https://Stackoverflow.com/users/1482214",
"pm_score": 3,
"selected": false,
"text": "<p>Although this is an old thread I want to share my solution and hopefully get some feedback on this. Be warned that I only tested this solution with my local database in some JUnit testcase. So this is not a productive feature so far.</p>\n\n<p>I solved that issue for my by introducing a custom annotation called Sequence with no property. It's just a marker for fields that should be assigned a value from an incremented sequence.</p>\n\n<pre><code>@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.FIELD)\npublic @interface Sequence\n{\n}\n</code></pre>\n\n<p>Using this annotation i marked my entities.</p>\n\n<pre><code>public class Area extends BaseEntity implements ClientAware, IssuerAware\n{\n @Column(name = \"areaNumber\", updatable = false)\n @Sequence\n private Integer areaNumber;\n....\n}\n</code></pre>\n\n<p>To keep things database independent I introduced an entity called SequenceNumber which holds the sequence current value and the increment size. I chose the className as unique key so each entity class wil get its own sequence.</p>\n\n<pre><code>@Entity\n@Table(name = \"SequenceNumber\", uniqueConstraints = { @UniqueConstraint(columnNames = { \"className\" }) })\npublic class SequenceNumber\n{\n @Id\n @Column(name = \"className\", updatable = false)\n private String className;\n\n @Column(name = \"nextValue\")\n private Integer nextValue = 1;\n\n @Column(name = \"incrementValue\")\n private Integer incrementValue = 10;\n\n ... some getters and setters ....\n}\n</code></pre>\n\n<p>The last step and the most difficult is a PreInsertListener that handles the sequence number assignment. Note that I used spring as bean container.</p>\n\n<pre><code>@Component\npublic class SequenceListener implements PreInsertEventListener\n{\n private static final long serialVersionUID = 7946581162328559098L;\n private final static Logger log = Logger.getLogger(SequenceListener.class);\n\n @Autowired\n private SessionFactoryImplementor sessionFactoryImpl;\n\n private final Map<String, CacheEntry> cache = new HashMap<>();\n\n @PostConstruct\n public void selfRegister()\n {\n // As you might expect, an EventListenerRegistry is the place with which event listeners are registered\n // It is a service so we look it up using the service registry\n final EventListenerRegistry eventListenerRegistry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);\n\n // add the listener to the end of the listener chain\n eventListenerRegistry.appendListeners(EventType.PRE_INSERT, this);\n }\n\n @Override\n public boolean onPreInsert(PreInsertEvent p_event)\n {\n updateSequenceValue(p_event.getEntity(), p_event.getState(), p_event.getPersister().getPropertyNames());\n\n return false;\n }\n\n private void updateSequenceValue(Object p_entity, Object[] p_state, String[] p_propertyNames)\n {\n try\n {\n List<Field> fields = ReflectUtil.getFields(p_entity.getClass(), null, Sequence.class);\n\n if (!fields.isEmpty())\n {\n if (log.isDebugEnabled())\n {\n log.debug(\"Intercepted custom sequence entity.\");\n }\n\n for (Field field : fields)\n {\n Integer value = getSequenceNumber(p_entity.getClass().getName());\n\n field.setAccessible(true);\n field.set(p_entity, value);\n setPropertyState(p_state, p_propertyNames, field.getName(), value);\n\n if (log.isDebugEnabled())\n {\n LogMF.debug(log, \"Set {0} property to {1}.\", new Object[] { field, value });\n }\n }\n }\n }\n catch (Exception e)\n {\n log.error(\"Failed to set sequence property.\", e);\n }\n }\n\n private Integer getSequenceNumber(String p_className)\n {\n synchronized (cache)\n {\n CacheEntry current = cache.get(p_className);\n\n // not in cache yet => load from database\n if ((current == null) || current.isEmpty())\n {\n boolean insert = false;\n StatelessSession session = sessionFactoryImpl.openStatelessSession();\n session.beginTransaction();\n\n SequenceNumber sequenceNumber = (SequenceNumber) session.get(SequenceNumber.class, p_className);\n\n // not in database yet => create new sequence\n if (sequenceNumber == null)\n {\n sequenceNumber = new SequenceNumber();\n sequenceNumber.setClassName(p_className);\n insert = true;\n }\n\n current = new CacheEntry(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue(), sequenceNumber.getNextValue());\n cache.put(p_className, current);\n sequenceNumber.setNextValue(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue());\n\n if (insert)\n {\n session.insert(sequenceNumber);\n }\n else\n {\n session.update(sequenceNumber);\n }\n session.getTransaction().commit();\n session.close();\n }\n\n return current.next();\n }\n }\n\n private void setPropertyState(Object[] propertyStates, String[] propertyNames, String propertyName, Object propertyState)\n {\n for (int i = 0; i < propertyNames.length; i++)\n {\n if (propertyName.equals(propertyNames[i]))\n {\n propertyStates[i] = propertyState;\n return;\n }\n }\n }\n\n private static class CacheEntry\n {\n private int current;\n private final int limit;\n\n public CacheEntry(final int p_limit, final int p_current)\n {\n current = p_current;\n limit = p_limit;\n }\n\n public Integer next()\n {\n return current++;\n }\n\n public boolean isEmpty()\n {\n return current >= limit;\n }\n }\n}\n</code></pre>\n\n<p>As you can see from the above code the listener used one SequenceNumber instance per entity class and reserves a couple of sequence numbers defined by the incrementValue of the SequenceNumber entity. If it runs out of sequence numbers it loads the SequenceNumber entity for the target class and reserves incrementValue values for the next calls. This way I do not need to query the database each time a sequence value is needed.\nNote the StatelessSession that is being opened for reserving the next set of sequence numbers. You cannot use the same session the target entity is currently persisted since this would lead to a ConcurrentModificationException in the EntityPersister.</p>\n\n<p>Hope this helps someone.</p>\n"
},
{
"answer_id": 23831524,
"author": "Rumal",
"author_id": 969252,
"author_profile": "https://Stackoverflow.com/users/969252",
"pm_score": 5,
"selected": false,
"text": "<p>I know this is a very old question, but it's showed firstly upon the results and jpa has changed a lot since the question.</p>\n\n<p>The right way to do it now is with the <code>@Generated</code> annotation. You can define the sequence, set the default in the column to that sequence and then map the column as:</p>\n\n<pre><code>@Generated(GenerationTime.INSERT)\n@Column(name = \"column_name\", insertable = false)\n</code></pre>\n"
},
{
"answer_id": 35888326,
"author": "Matroska",
"author_id": 269585,
"author_profile": "https://Stackoverflow.com/users/269585",
"pm_score": 4,
"selected": false,
"text": "<p>I fixed the generation of UUID (or sequences) with Hibernate using <code>@PrePersist</code> annotation:</p>\n\n<pre><code>@PrePersist\npublic void initializeUUID() {\n if (uuid == null) {\n uuid = UUID.randomUUID().toString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49368556,
"author": "Spring",
"author_id": 379028,
"author_profile": "https://Stackoverflow.com/users/379028",
"pm_score": -1,
"selected": false,
"text": "<p>After spending hours, this neatly helped me to solve my problem:</p>\n\n<p>For Oracle 12c:</p>\n\n<pre><code>ID NUMBER GENERATED as IDENTITY\n</code></pre>\n\n<p>For H2:</p>\n\n<pre><code>ID BIGINT GENERATED as auto_increment\n</code></pre>\n\n<p>Also make:</p>\n\n<pre><code>@Column(insertable = false)\n</code></pre>\n"
},
{
"answer_id": 53451707,
"author": "Sulaymon Hursanov",
"author_id": 8038849,
"author_profile": "https://Stackoverflow.com/users/8038849",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using postgresql <br>\nAnd i'm using in spring boot 1.5.6</p>\n\n<pre><code>@Column(columnDefinition = \"serial\")\n@Generated(GenerationTime.INSERT)\nprivate Integer orderID;\n</code></pre>\n"
},
{
"answer_id": 56017045,
"author": "Subin Chalil",
"author_id": 2756662,
"author_profile": "https://Stackoverflow.com/users/2756662",
"pm_score": 3,
"selected": false,
"text": "<p>Looks like thread is old, I just wanted to add my solution here(Using AspectJ - AOP in spring).</p>\n\n<p>Solution is to create a custom annotation <code>@InjectSequenceValue</code> as follows.</p>\n\n<pre><code>@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.FIELD)\npublic @interface InjectSequenceValue {\n String sequencename();\n}\n</code></pre>\n\n<p>Now you can annotate any field in entity, so that the underlying field (Long/Integer) value will be injected at runtime using the nextvalue of the sequence.</p>\n\n<p>Annotate like this.</p>\n\n<pre><code>//serialNumber will be injected dynamically, with the next value of the serialnum_sequence.\n @InjectSequenceValue(sequencename = \"serialnum_sequence\") \n Long serialNumber;\n</code></pre>\n\n<p>So far we have marked the field we need to inject the sequence value.So we will look how to inject the sequence value to the marked fields, this is done by creating the point cut in AspectJ.</p>\n\n<p>We will trigger the injection just before the <code>save/persist</code> method is being executed.This is done in the below class.</p>\n\n<pre><code>@Aspect\n@Configuration\npublic class AspectDefinition {\n\n @Autowired\n JdbcTemplate jdbcTemplate;\n\n\n //@Before(\"execution(* org.hibernate.session.save(..))\") Use this for Hibernate.(also include session.save())\n @Before(\"execution(* org.springframework.data.repository.CrudRepository.save(..))\") //This is for JPA.\n public void generateSequence(JoinPoint joinPoint){\n\n Object [] aragumentList=joinPoint.getArgs(); //Getting all arguments of the save\n for (Object arg :aragumentList ) {\n if (arg.getClass().isAnnotationPresent(Entity.class)){ // getting the Entity class\n\n Field[] fields = arg.getClass().getDeclaredFields();\n for (Field field : fields) {\n if (field.isAnnotationPresent(InjectSequenceValue.class)) { //getting annotated fields\n\n field.setAccessible(true); \n try {\n if (field.get(arg) == null){ // Setting the next value\n String sequenceName=field.getAnnotation(InjectSequenceValue.class).sequencename();\n long nextval=getNextValue(sequenceName);\n System.out.println(\"Next value :\"+nextval); //TODO remove sout.\n field.set(arg, nextval);\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n }\n }\n\n /**\n * This method fetches the next value from sequence\n * @param sequence\n * @return\n */\n\n public long getNextValue(String sequence){\n long sequenceNextVal=0L;\n\n SqlRowSet sqlRowSet= jdbcTemplate.queryForRowSet(\"SELECT \"+sequence+\".NEXTVAL as value FROM DUAL\");\n while (sqlRowSet.next()){\n sequenceNextVal=sqlRowSet.getLong(\"value\");\n\n }\n return sequenceNextVal;\n }\n}\n</code></pre>\n\n<p>Now you can annotate any Entity as below.</p>\n\n<pre><code>@Entity\n@Table(name = \"T_USER\")\npublic class UserEntity {\n\n @Id\n @SequenceGenerator(sequenceName = \"userid_sequence\",name = \"this_seq\")\n @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = \"this_seq\")\n Long id;\n String userName;\n String password;\n\n @InjectSequenceValue(sequencename = \"serialnum_sequence\") // this will be injected at the time of saving.\n Long serialNumber;\n\n String name;\n}\n</code></pre>\n"
},
{
"answer_id": 58797977,
"author": "Artyom Novitskii",
"author_id": 12354330,
"author_profile": "https://Stackoverflow.com/users/12354330",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a column with UNIQUEIDENTIFIER type and default generation needed on insert but column is not PK </p>\n\n<pre><code>@Generated(GenerationTime.INSERT)\n@Column(nullable = false , columnDefinition=\"UNIQUEIDENTIFIER\")\nprivate String uuidValue;\n</code></pre>\n\n<p>In db you will have </p>\n\n<pre><code>CREATE TABLE operation.Table1\n(\n Id INT IDENTITY (1,1) NOT NULL,\n UuidValue UNIQUEIDENTIFIER DEFAULT NEWID() NOT NULL)\n</code></pre>\n\n<p>In this case you will not define generator for a value which you need (It will be automatically thanks to <code>columnDefinition=\"UNIQUEIDENTIFIER\"</code>). The same you can try for other column types</p>\n"
},
{
"answer_id": 61297522,
"author": "Ignacio Velásquez Lagos",
"author_id": 5579797,
"author_profile": "https://Stackoverflow.com/users/5579797",
"pm_score": 0,
"selected": false,
"text": "<p>I have found a workaround for this on MySql databases using @PostConstruct and JdbcTemplate in a Spring application. It may be doable with other databases but the use case that I will present is based on my experience with MySql, as it uses auto_increment. </p>\n\n<p>First, I had tried defining a column as auto_increment using the ColumnDefinition property of the @Column annotation, but it was not working as the column needed to be an key in order to be auto incremental, but apparently the column wouldn't be defined as an index until after it was defined, causing a deadlock. </p>\n\n<p>Here is where I came with the idea of creating the column without the auto_increment definition, and adding it <em>after</em> the database was created. This is possible using the @PostConstruct annotation, which causes a method to be invoked right after the application has initialized the beans, coupled with JdbcTemplate's update method. </p>\n\n<p>The code is as follows: </p>\n\n<p>In My Entity: </p>\n\n<pre><code>@Entity\n@Table(name = \"MyTable\", indexes = { @Index(name = \"my_index\", columnList = \"mySequencedValue\") })\npublic class MyEntity {\n //...\n @Column(columnDefinition = \"integer unsigned\", nullable = false, updatable = false, insertable = false)\n private Long mySequencedValue;\n //...\n}\n</code></pre>\n\n<p>In a PostConstructComponent class: </p>\n\n<pre><code>@Component\npublic class PostConstructComponent {\n @Autowired\n private JdbcTemplate jdbcTemplate;\n\n @PostConstruct\n public void makeMyEntityMySequencedValueAutoIncremental() {\n jdbcTemplate.update(\"alter table MyTable modify mySequencedValue int unsigned auto_increment\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 61614713,
"author": "aboger",
"author_id": 1411723,
"author_profile": "https://Stackoverflow.com/users/1411723",
"pm_score": 1,
"selected": false,
"text": "<p>I want to provide an alternative next to @Morten Berg's accepted solution, which worked better for me.</p>\n\n<p>This approach allows to define the field with the actually desired <code>Number</code> type - <code>Long</code> in my use case - instead of <code>GeneralSequenceNumber</code>. This can be useful, e.g. for JSON (de-)serialization.</p>\n\n<p>The downside is that it requires a little more database overhead.</p>\n\n<hr>\n\n<p>First, we need an <code>ActualEntity</code> in which we want to auto-increment <code>generated</code> of type <code>Long</code>:</p>\n\n<pre><code>// ...\n@Entity\npublic class ActualEntity {\n\n @Id \n // ...\n Long id;\n\n @Column(unique = true, updatable = false, nullable = false)\n Long generated;\n\n // ...\n\n}\n</code></pre>\n\n<p>Next, we need a helper entity <code>Generated</code>. I placed it package-private next to <code>ActualEntity</code>, to keep it an implementation detail of the package:</p>\n\n<pre><code>@Entity\nclass Generated {\n\n @Id\n @GeneratedValue(strategy = SEQUENCE, generator = \"seq\")\n @SequenceGenerator(name = \"seq\", initialValue = 1, allocationSize = 1)\n Long id;\n\n}\n</code></pre>\n\n<p>Finally, we need a place to hook in right before we save the <code>ActualEntity</code>. There, we create and persist a<code>Generated</code> instance. This then provides a database-sequence generated <code>id</code> of type <code>Long</code>. We make use of this value by writing it to <code>ActualEntity.generated</code>. </p>\n\n<p>In my use case, I implemented this using a Spring Data REST <code>@RepositoryEventHandler</code>, which get's called right before the <code>ActualEntity</code> get's persisted. It should demonstrate the principle:</p>\n\n<pre><code>@Component\n@RepositoryEventHandler\npublic class ActualEntityHandler {\n\n @Autowired\n EntityManager entityManager;\n\n @Transactional\n @HandleBeforeCreate\n public void generate(ActualEntity entity) {\n Generated generated = new Generated();\n\n entityManager.persist(generated);\n entity.setGlobalId(generated.getId());\n entityManager.remove(generated);\n }\n\n}\n</code></pre>\n\n<p>I didn't test it in a real-life application, so please enjoy with care.</p>\n"
},
{
"answer_id": 63688702,
"author": "Aritra Das",
"author_id": 9898631,
"author_profile": "https://Stackoverflow.com/users/9898631",
"pm_score": 0,
"selected": false,
"text": "<p>I was struggling with this today, was able to solve using this</p>\n<pre><code>@Generated(GenerationTime.INSERT)\n@Column(name = "internal_id", columnDefinition = "serial", updatable = false)\nprivate int internalId;\n</code></pre>\n"
},
{
"answer_id": 70979696,
"author": "heisbrandon",
"author_id": 3870855,
"author_profile": "https://Stackoverflow.com/users/3870855",
"pm_score": 2,
"selected": false,
"text": "<p>You can do exactly what you are asking.</p>\n<p>I've found it is possible to adapt Hibernate's <a href=\"https://docs.jboss.org/hibernate/orm/5.6/javadocs/org/hibernate/id/IdentifierGenerator.html\" rel=\"nofollow noreferrer\">IdentifierGenerator</a> implementations by registering them with an <a href=\"https://docs.jboss.org/hibernate/orm/5.6/javadocs/org/hibernate/integrator/spi/Integrator.html\" rel=\"nofollow noreferrer\">Integrator</a>. With this you should be able to use any id sequence generator provided by Hibernate to generate sequences for non-id fields (presumably the non-sequential id generators would work as well).</p>\n<p>There are quite a few options for generating ids this way. Check out some of the implementations of IdentifierGenerator, specifically <a href=\"https://docs.jboss.org/hibernate/orm/5.6/javadocs/org/hibernate/id/enhanced/SequenceStyleGenerator.html\" rel=\"nofollow noreferrer\">SequenceStyleGenerator</a> and <a href=\"https://docs.jboss.org/hibernate/orm/5.6/javadocs/org/hibernate/id/enhanced/TableGenerator.html\" rel=\"nofollow noreferrer\">TableGenerator</a>. If you have configured generators using the <a href=\"https://docs.jboss.org/hibernate/orm/5.6/javadocs/index.html?org/hibernate/id/enhanced/TableGenerator.html\" rel=\"nofollow noreferrer\">@GenericGenerator</a> annotation, then the parameters for these classes may be familiar to you. This would also have the advantage of using Hibernate to generate the SQL.</p>\n<p>Here is how I got it working:</p>\n<pre><code>import org.hibernate.Session;\nimport org.hibernate.boot.Metadata;\nimport org.hibernate.engine.spi.SessionFactoryImplementor;\nimport org.hibernate.id.IdentifierGenerator;\nimport org.hibernate.id.enhanced.TableGenerator;\nimport org.hibernate.integrator.spi.Integrator;\nimport org.hibernate.internal.SessionImpl;\nimport org.hibernate.service.spi.SessionFactoryServiceRegistry;\nimport org.hibernate.tuple.ValueGenerator;\nimport org.hibernate.type.LongType;\nimport java.util.Properties;\n\npublic class SequenceIntegrator implements Integrator, ValueGenerator<Long> {\n public static final String TABLE_NAME = "SEQUENCE_TABLE";\n public static final String VALUE_COLUMN_NAME = "NEXT_VAL";\n public static final String SEGMENT_COLUMN_NAME = "SEQUENCE_NAME";\n private static SessionFactoryServiceRegistry serviceRegistry;\n private static Metadata metadata;\n private static IdentifierGenerator defaultGenerator;\n\n @Override\n public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {\n //assigning metadata and registry to fields for use in a below example\n SequenceIntegrator.metadata = metadata;\n SequenceIntegrator.serviceRegistry = sessionFactoryServiceRegistry;\n SequenceIntegrator.defaultGenerator = getTableGenerator(metadata, sessionFactoryServiceRegistry, "DEFAULT");\n }\n\n private TableGenerator getTableGenerator(Metadata metadata, SessionFactoryServiceRegistry sessionFactoryServiceRegistry, String segmentValue) {\n TableGenerator generator = new TableGenerator();\n Properties properties = new Properties();\n properties.setProperty("table_name", TABLE_NAME);\n properties.setProperty("value_column_name", VALUE_COLUMN_NAME);\n properties.setProperty("segment_column_name", SEGMENT_COLUMN_NAME);\n properties.setProperty("segment_value", segmentValue);\n\n //any type should work if the generator supports it\n generator.configure(LongType.INSTANCE, properties, sessionFactoryServiceRegistry);\n\n //this should create the table if ddl auto update is enabled and if this function is called inside of the integrate method\n generator.registerExportables(metadata.getDatabase());\n return generator;\n }\n\n @Override\n public Long generateValue(Session session, Object o) {\n // registering additional generators with getTableGenerator will work here. inserting new sequences can be done dynamically\n // example:\n // TableGenerator classSpecificGenerator = getTableGenerator(metadata, serviceRegistry, o.getClass().getName());\n // return (Long) classSpecificGenerator.generate((SessionImpl)session, o);\n return (Long) defaultGenerator.generate((SessionImpl)session, o);\n }\n\n @Override\n public void disintegrate(SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {\n\n }\n}\n</code></pre>\n<p>You would need to register this class in the META-INF/services directory. Here is what the Hibernate documentation has to say about registering an Integrator:</p>\n<blockquote>\n<p>For the integrator to be automatically used when Hibernate starts up, you will need to add a META-INF/services/org.hibernate.integrator.spi.Integrator file to your jar. The file should contain the fully qualified name of the class implementing the interface.</p>\n</blockquote>\n<p>Because this class implements the <a href=\"https://docs.jboss.org/hibernate/orm/5.6/javadocs/org/hibernate/tuple/ValueGenerator.html\" rel=\"nofollow noreferrer\">ValueGenerator</a> class, it can be used with the <a href=\"https://docs.jboss.org/hibernate/orm/5.6/javadocs/org/hibernate/annotations/GeneratorType.html\" rel=\"nofollow noreferrer\">@GeneratorType</a> annotation to automatically generate the sequential values. Here is how your class might be configured:</p>\n<pre><code>@Entity\n@Table(name = "MyTable")\npublic class MyEntity {\n\n //...\n @Id //... etc\n public Long getId() {\n return id;\n }\n\n @GeneratorType(type = SequenceIntegrator.class, when = GenerationTime.INSERT)\n @Column(name = "SEQ_VAL", unique = false, nullable = false, insertable = true, updatable = true)\n public Long getMySequencedValue(){\n return myVal;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 73945897,
"author": "A.Casanova",
"author_id": 17047177,
"author_profile": "https://Stackoverflow.com/users/17047177",
"pm_score": 0,
"selected": false,
"text": "<pre><code>@Column(name = "<column name>", columnDefinition = "serial")\n</code></pre>\n<p>Works for mySQL</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22992/"
] |
Is it possible to use a DB sequence for some column that **is not the identifier/is not part of a composite identifier**?
I'm using hibernate as jpa provider, and I have a table that has some columns that are generated values (using a sequence), although they are not part of the identifier.
What I want is to use a sequence to create a new value for an entity, where the column for the sequence is **NOT** (part of) the primary key:
```
@Entity
@Table(name = "MyTable")
public class MyEntity {
//...
@Id //... etc
public Long getId() {
return id;
}
//note NO @Id here! but this doesn't work...
@GeneratedValue(strategy = GenerationType.AUTO, generator = "myGen")
@SequenceGenerator(name = "myGen", sequenceName = "MY_SEQUENCE")
@Column(name = "SEQ_VAL", unique = false, nullable = false, insertable = true, updatable = true)
public Long getMySequencedValue(){
return myVal;
}
}
```
Then when I do this:
```
em.persist(new MyEntity());
```
the id will be generated, but the `mySequenceVal` property will be also generated by my JPA provider.
Just to make things clear: I want **Hibernate** to generate the value for the `mySequencedValue` property. I know Hibernate can handle database-generated values, but I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property. If Hibernate can generate values for primary keys, why can't it generate for a simple property?
|
Looking for answers to this problem, I stumbled upon [this link](http://forum.hibernate.org/viewtopic.php?p=2405140)
It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The `@GeneratedValue` annotation is only used in conjunction with `@Id` to create auto-numbers.
The `@GeneratedValue` annotation just tells Hibernate that the database is generating this value itself.
The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this:
```
@Entity
public class GeneralSequenceNumber {
@Id
@GeneratedValue(...)
private Long number;
}
@Entity
public class MyEntity {
@Id ..
private Long id;
@OneToOne(...)
private GeneralSequnceNumber myVal;
}
```
|
277,634 |
<p>still new to the world of linq, and i need some help flatening a list of parents that have children, into a single list of ParentChild's.</p>
<p>Just like this:</p>
<pre><code>class Program
{
static void Main()
{
List<Parent> parents = new List<Parent>();
parents.Add(new Parent { Name = "Parent1", Children = new List<Child> { new Child { Name = "Child1" }, new Child { Name = "Child2" } } });
parents.Add(new Parent { Name = "Parent2", Children = new List<Child> { new Child { Name = "Child3" }, new Child { Name = "Child4" } } });
// linq query to return List<ParentChild> parentChildList;
// ParentName = Parent1, ChildName = Child1
// ParentName = Parent1, ChildName = Child2
// ParentName = Parent2, ChildName = Child3
// ParentName = Parent2, ChildName = Child4
}
internal class ParentChild
{
public string ParentName { get; set; }
public string ChildName { get; set; }
}
internal class Parent
{
public string Name { get; set; }
public List<Child> Children { get; set; }
}
internal class Child
{
public string Name { get; set; }
}
}
</code></pre>
<p>Many thanks,
Chris</p>
|
[
{
"answer_id": 277637,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 5,
"selected": true,
"text": "<pre><code>from parent in parents\nfrom child in parent.Children\nselect new ParentChild() { ParentName = parent.Name, ChildName = child.Name };\n</code></pre>\n"
},
{
"answer_id": 277648,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 2,
"selected": false,
"text": "<p>This should do it for you:</p>\n\n<pre><code>var k = from p in parents\n from c in p.Children\n select new {Name = p.Name, Child = c.Name };\n</code></pre>\n\n<p>EDIT: Opps forgot to return a new ParentChild object. but Kent beat me to it ;)</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26759/"
] |
still new to the world of linq, and i need some help flatening a list of parents that have children, into a single list of ParentChild's.
Just like this:
```
class Program
{
static void Main()
{
List<Parent> parents = new List<Parent>();
parents.Add(new Parent { Name = "Parent1", Children = new List<Child> { new Child { Name = "Child1" }, new Child { Name = "Child2" } } });
parents.Add(new Parent { Name = "Parent2", Children = new List<Child> { new Child { Name = "Child3" }, new Child { Name = "Child4" } } });
// linq query to return List<ParentChild> parentChildList;
// ParentName = Parent1, ChildName = Child1
// ParentName = Parent1, ChildName = Child2
// ParentName = Parent2, ChildName = Child3
// ParentName = Parent2, ChildName = Child4
}
internal class ParentChild
{
public string ParentName { get; set; }
public string ChildName { get; set; }
}
internal class Parent
{
public string Name { get; set; }
public List<Child> Children { get; set; }
}
internal class Child
{
public string Name { get; set; }
}
}
```
Many thanks,
Chris
|
```
from parent in parents
from child in parent.Children
select new ParentChild() { ParentName = parent.Name, ChildName = child.Name };
```
|
277,640 |
<p>SPListItem.GetFormattedValue seems to have a strange behavior for DateTime fields.
It retrieves the DateTime value through SPListItem's indexer which according to this <a href="http://msdn.microsoft.com/en-us/library/ms197282.aspx" rel="noreferrer">MSDN article</a> returns <em>local</em> time.
Here's a snippet from Reflector</p>
<pre><code>public string GetFormattedValue(string fieldName)
{
SPField field = this.Fields.GetField(fieldName);
if (field != null)
{
return field.GetFieldValueAsHtml(this[fieldName]);
}
return null;
}
</code></pre>
<p>So it uses SPListItem's indexer to retrieve the value and than SPFields.GetFieldValueAsHtml to format the value. GetFieldValueAsHtml seems to assume the date is in UTC and convert it to local time no matter what kind it is. (Reflector shows that it uses GetFieldValueAsText which uses value.ToString() but for some reason it assumes the time to be UTC.)</p>
<p>The end result is that the string representation on a time field obtained trough listItem.GetFormattedValue() (at least in my case) is incorrect, being local time + (local time - UTC).</p>
<p>Have anybody encountered the same issue with SPListItem.GetFormattedValue() and what was your workaround?</p>
|
[
{
"answer_id": 278934,
"author": "Nat",
"author_id": 13813,
"author_profile": "https://Stackoverflow.com/users/13813",
"pm_score": 0,
"selected": false,
"text": "<p>I have had a recognised bug with the date conversion from UTC in SharePoint. It was fixed in SP1.</p>\n"
},
{
"answer_id": 457151,
"author": "Soda",
"author_id": 56623,
"author_profile": "https://Stackoverflow.com/users/56623",
"pm_score": 4,
"selected": true,
"text": "<p>Converting the date back to universal time before calling GetFieldValueAsHtml works just fine.</p>\n\n<pre><code>DateTime localTime = (DateTime)item[\"DueDate\"];\n// this is local time but if you do localDateTime.Kind it returns Unspecified\n// treats the date as universal time.. \n// let's give it the universal time :)\nDateTime universalTime = SPContext.Current.Web\n .RegionalSettings.TimeZone.LocalTimeToUTC(localTime);\nstring correctFormattedValue = \n item.Fields[\"DueDate\"].GetFieldValueAsHtml(universalTime);\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] |
SPListItem.GetFormattedValue seems to have a strange behavior for DateTime fields.
It retrieves the DateTime value through SPListItem's indexer which according to this [MSDN article](http://msdn.microsoft.com/en-us/library/ms197282.aspx) returns *local* time.
Here's a snippet from Reflector
```
public string GetFormattedValue(string fieldName)
{
SPField field = this.Fields.GetField(fieldName);
if (field != null)
{
return field.GetFieldValueAsHtml(this[fieldName]);
}
return null;
}
```
So it uses SPListItem's indexer to retrieve the value and than SPFields.GetFieldValueAsHtml to format the value. GetFieldValueAsHtml seems to assume the date is in UTC and convert it to local time no matter what kind it is. (Reflector shows that it uses GetFieldValueAsText which uses value.ToString() but for some reason it assumes the time to be UTC.)
The end result is that the string representation on a time field obtained trough listItem.GetFormattedValue() (at least in my case) is incorrect, being local time + (local time - UTC).
Have anybody encountered the same issue with SPListItem.GetFormattedValue() and what was your workaround?
|
Converting the date back to universal time before calling GetFieldValueAsHtml works just fine.
```
DateTime localTime = (DateTime)item["DueDate"];
// this is local time but if you do localDateTime.Kind it returns Unspecified
// treats the date as universal time..
// let's give it the universal time :)
DateTime universalTime = SPContext.Current.Web
.RegionalSettings.TimeZone.LocalTimeToUTC(localTime);
string correctFormattedValue =
item.Fields["DueDate"].GetFieldValueAsHtml(universalTime);
```
|
277,646 |
<p>I am having a number of panels in my page in which I am collecting user information and saving the page details. The page panel has textbox, dropdown list, listbox.</p>
<p>When I need to come to this page. I need to show the Page if these controls have any values. How to do this?</p>
|
[
{
"answer_id": 277654,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 6,
"selected": true,
"text": "<p>It boils down to enumerating all the controls in the control hierarchy:</p>\n\n<pre><code> IEnumerable<Control> EnumerateControlsRecursive(Control parent)\n {\n foreach (Control child in parent.Controls)\n {\n yield return child;\n foreach (Control descendant in EnumerateControlsRecursive(child))\n yield return descendant;\n }\n }\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code> foreach (Control c in EnumerateControlsRecursive(Page))\n {\n if(c is TextBox)\n {\n // do something useful\n }\n }\n</code></pre>\n"
},
{
"answer_id": 277656,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 2,
"selected": false,
"text": "<p>You can loop thru the panels controls</p>\n\n<pre><code>foreach (Control c in MyPanel.Controls) \n{\n if (c is Textbox) {\n // do something with textbox\n } else if (c is Checkbox) {\n /// do something with checkbox\n }\n}\n</code></pre>\n\n<p>If you have them nested inside, then you'll need a function that does this recursively.</p>\n"
},
{
"answer_id": 277664,
"author": "Richard Dorman",
"author_id": 1199234,
"author_profile": "https://Stackoverflow.com/users/1199234",
"pm_score": 0,
"selected": false,
"text": "<p>Depeding on which UI library or language you are using, container controls such as panels maintain a list of child controls. To test if a form/page has any data you need to recursively search each panel for data entry controls such as text boxes. Then test if any of the data entry controls contain values other than default value.</p>\n\n<p>A simpler solutions would be to implement an observer class that attaches to the changed events of your data controls. If the observer is triggered then your page has changes. You will need to take into consideration actions such as changing and then reverting data. </p>\n"
},
{
"answer_id": 1321133,
"author": "Andrew Corkery",
"author_id": 59700,
"author_profile": "https://Stackoverflow.com/users/59700",
"pm_score": 0,
"selected": false,
"text": "<p>Very similar solution to Cristian's here, which uses recursion and generics to find any control in the page (you can specify the control at which to start searching).</p>\n\n<p><a href=\"http://intrepidnoodle.com/articles/24.aspx\" rel=\"nofollow noreferrer\">http://intrepidnoodle.com/articles/24.aspx</a></p>\n"
},
{
"answer_id": 7195784,
"author": "theoski",
"author_id": 598807,
"author_profile": "https://Stackoverflow.com/users/598807",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is an old post, and I really liked <a href=\"https://stackoverflow.com/users/16526/cristian-libardo\">christian libardo's</a> solution. However, I do not like the fact that in order to yield an entire set of elements to the outer scope I would have to iterate over those elements yet again only to yield those to myself from an inner scope to the current scope. I prefer:</p>\n\n<pre><code>IEnumerable<Control> getCtls(Control par)\n{ \n List<Control> ret = new List<Control>();\n foreach (Control c in par.Controls)\n {\n ret.Add(c);\n ret.AddRange(getCtls(c));\n }\n return (IEnumerable<Control>)ret;\n}\n</code></pre>\n\n<p>Which allows me to use it like so:</p>\n\n<pre><code>foreach (Button but in getCtls(Page).OfType<Button>())\n{\n //disable the button\n but.Enabled = false;\n} \n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
I am having a number of panels in my page in which I am collecting user information and saving the page details. The page panel has textbox, dropdown list, listbox.
When I need to come to this page. I need to show the Page if these controls have any values. How to do this?
|
It boils down to enumerating all the controls in the control hierarchy:
```
IEnumerable<Control> EnumerateControlsRecursive(Control parent)
{
foreach (Control child in parent.Controls)
{
yield return child;
foreach (Control descendant in EnumerateControlsRecursive(child))
yield return descendant;
}
}
```
You can use it like this:
```
foreach (Control c in EnumerateControlsRecursive(Page))
{
if(c is TextBox)
{
// do something useful
}
}
```
|
277,660 |
<p>3/10/2008 = 1822556159</p>
<p>2/10/2008 = 1822523391</p>
<p>1/10/2008 = 1822490623</p>
<p>30/09/2008 = 1822392319</p>
<p>29/09/2008 = 1822359551</p>
<p>This is all the information that I know at the current time. </p>
<p>Dates increment by 32768 except when changing month when the increment is 32768 x 2 (65536).</p>
<p>Has anyone seen this binary date format and how can I extract the correct date?</p>
<hr>
<p>It is possible that the remaining portion of the date is for time (hours, minutes, seconds)</p>
|
[
{
"answer_id": 277683,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "<p>September 30th 2008</p>\n\n<pre><code>1822392319 = 0x6c9f7fff\n0x6c = 108 = 2008 (based on 1900 start date)\n0x9 = 9 = September\n0xf7fff - take top 5 bits = 0x1e = 30\n</code></pre>\n\n<p>October 1st 2008</p>\n\n<pre><code>1822490623 = 0x6ca0ffff\n0x6c = 108 = 2008\n0xa = 10 = October\n0x0ffff - take top 5 bits = 0x01 = 1\n</code></pre>\n\n<p>It's anyone's guess what the remaining 15 one-bits are for, if anything.</p>\n\n<p>EDIT: by take top 5 bits I mean:</p>\n\n<pre><code>day_of_month = (value >> 15) & 0x1f\n</code></pre>\n\n<p>Similarly:</p>\n\n<pre><code>year = (value >> 24) & 0xff + 1900\nmonth = (value >> 20) & 0x0f\n</code></pre>\n"
},
{
"answer_id": 277686,
"author": "mana",
"author_id": 12016,
"author_profile": "https://Stackoverflow.com/users/12016",
"pm_score": 2,
"selected": false,
"text": "<p>write it down in a binary format:</p>\n\n<pre><code>a = 1822556159\n1101100 1010 00011 111111111111111\nb = 1822523391\n1101100 1010 00010 111111111111111\nc = 1822490623\n1101100 1010 00001 111111111111111\nd = 1822392319 \n1101100 1001 11110 111111111111111\n</code></pre>\n\n<p>where 1101100 is 108, as Alnitak said, the rest is month (1010 or 1001) and days.</p>\n\n<p>the 1s at the end may be reserved for representing seconds/milliseconds.</p>\n"
},
{
"answer_id": 277691,
"author": "Adam Jaskiewicz",
"author_id": 35322,
"author_profile": "https://Stackoverflow.com/users/35322",
"pm_score": 0,
"selected": false,
"text": "<p>32768 is 2^15; they're reserving 15 bits for the days, which I don't think divides evenly into any useful combination of hours, minutes, and/or seconds.</p>\n"
},
{
"answer_id": 277713,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 2,
"selected": false,
"text": "<p>EDIT: Alnitak is correct about this being a fixed-point binary date representation. However, the principles may be similar to what is described below; instead of a decimal place the format is fixed and the lower 15-bits are most likely the time. If you have any examples, post them and we will try to help.</p>\n\n<p>ORIGINAL: This is most likely the Windows OLE/COM date format which uses a Double to represent a date and time. The integer portion of the number is for the date and the fraction is for the time. It can represent dates between January 1, 100, and December 31, 9999. You can find more information at <a href=\"http://msdn.microsoft.com/en-us/library/a1z81fxe.aspx\" rel=\"nofollow noreferrer\">MSDN</a> or google for OLE date COM double.</p>\n\n<p>EDIT: Here is one <a href=\"http://dotnetperls.com/Content/Excel-FromOADate.aspx\" rel=\"nofollow noreferrer\">C# example</a> using DateTime.FromOADate. Here is a little more detail from <a href=\"http://msdn.microsoft.com/en-us/library/aa912065.aspx\" rel=\"nofollow noreferrer\">MSDN VariantTimeToSystemTime</a>.</p>\n\n<blockquote>\n <p>A variant time is stored as an 8-byte real value (double), representing a date between January 1, 1753 and December 31, 2078, inclusive. </p>\n \n <p>The value 2.0 represents January 1, 1900; 3.0 represents January 2, 1900, and so on. </p>\n \n <p>Adding 1 to the value increments the date by a day. The fractional part of the value represents the time of day. Therefore, 2.5 represents noon on January 1, 1900; 3.25 represents 6:00 A.M. on January 2, 1900, and so on. </p>\n \n <p>Negative numbers represent the dates prior to December 30, 1899.</p>\n</blockquote>\n\n<p>This is a little conflicting as the <a href=\"http://msdn.microsoft.com/en-us/library/38wh24td.aspx\" rel=\"nofollow noreferrer\">COleDateTime</a> documentation says it supports January 1, 100, while this documentation says it supports January 1, 1753.</p>\n\n<p>There are interfaces for VB (use CDbl() and CDate()), C# (DateTime.FromOADate/ToOADate), Java (<a href=\"http://techpubs.borland.com/starteam/2006/en/SDKDocs/api/com/starbase/util/OLEDate.html\" rel=\"nofollow noreferrer\">OLEDate</a> - looks deprecated though), <a href=\"http://treetron.googlepages.com/xls.oledatetime.html\" rel=\"nofollow noreferrer\">Delphi</a>, <a href=\"http://code.activestate.com/recipes/496683/\" rel=\"nofollow noreferrer\">Python</a>, etc.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
3/10/2008 = 1822556159
2/10/2008 = 1822523391
1/10/2008 = 1822490623
30/09/2008 = 1822392319
29/09/2008 = 1822359551
This is all the information that I know at the current time.
Dates increment by 32768 except when changing month when the increment is 32768 x 2 (65536).
Has anyone seen this binary date format and how can I extract the correct date?
---
It is possible that the remaining portion of the date is for time (hours, minutes, seconds)
|
September 30th 2008
```
1822392319 = 0x6c9f7fff
0x6c = 108 = 2008 (based on 1900 start date)
0x9 = 9 = September
0xf7fff - take top 5 bits = 0x1e = 30
```
October 1st 2008
```
1822490623 = 0x6ca0ffff
0x6c = 108 = 2008
0xa = 10 = October
0x0ffff - take top 5 bits = 0x01 = 1
```
It's anyone's guess what the remaining 15 one-bits are for, if anything.
EDIT: by take top 5 bits I mean:
```
day_of_month = (value >> 15) & 0x1f
```
Similarly:
```
year = (value >> 24) & 0xff + 1900
month = (value >> 20) & 0x0f
```
|
277,715 |
<p>i tried the following</p>
<ol>
<li><code>svnadmin create svn_repos</code></li>
<li><code>svn import my_first_proj file:///c:/svn_repos -m "initial import"</code></li>
<li><code>svn checkout file:///c:/svn_repos</code></li>
</ol>
<p>and the command returned</p>
<pre><code>A svn_repos\trunk
A svn_repos\trunk\Sample.txt.txt
A svn_repos\branches
A svn_repos\branches\my_pers_branch
Checked out revision 1.
</code></pre>
<p>Yet the <code>.svn</code> folder was not created in the checked out folders.
Because of which [I guess], I'm not able to do <code>svn copy</code> or <code>svn merge</code>.</p>
<p>Why does this occur?
what is the problem?
is there anything wrong in my commands</p>
|
[
{
"answer_id": 277737,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "<p>Are you sure it's not just hidden (they are by default)?</p>\n\n<p>Try running <code>dir /AH</code></p>\n"
},
{
"answer_id": 277738,
"author": "Mitch Haile",
"author_id": 28807,
"author_profile": "https://Stackoverflow.com/users/28807",
"pm_score": 1,
"selected": false,
"text": "<p>What does 'svn status' say? If .svn is really missing, it will print something like:</p>\n\n<pre><code>svn: warning: '.' is not a working copy\n</code></pre>\n"
},
{
"answer_id": 277782,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps you're expecting to find that .svn directory inside the my_first_proj directory. Currently, your svn is checked out inside a \"svn_repos\" directory, relative to the path you typed in the checkout command. What you may want to do is :</p>\n\n<pre><code>svn checkout --force file:///c:/svn_repos/ my_first_proj \n</code></pre>\n\n<p>Which checks out a repository inside an existing directory. The usual approach is to checkout to another directory the first time, though.</p>\n"
},
{
"answer_id": 277834,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 2,
"selected": false,
"text": "<p>On Windows Subversion might use hidden _svn directories instead of .svn in some situations. </p>\n\n<p>This behavior is switched by the SVN_ASP_DOT_NET_HACK environment variable. See the <a href=\"http://svn.collab.net/repos/svn/trunk/notes/asp-dot-net-hack.txt\" rel=\"nofollow noreferrer\">Subversion documentation</a>.</p>\n"
},
{
"answer_id": 277898,
"author": "lmop",
"author_id": 22260,
"author_profile": "https://Stackoverflow.com/users/22260",
"pm_score": 2,
"selected": false,
"text": "<p>You haven't specified a path in your checkout so it's defaulted to the basename of the repository itself. In other words it operated as:</p>\n\n<pre><code>svn checkout file:///c:/svn_repos ./svn_repos\n</code></pre>\n\n<p>This has had the effect that it has checked out your working copy within the repository directory! If you look in the repository you should find <code>trunk</code> and <code>branches</code> directories and the rest of the files. It will behave as you expect if instead you do:</p>\n\n<pre><code>svnadmin create svn_repos\nsvn import my_first_proj file:///c:/svn_repos -m \"initial import\"\nsvn checkout file:///c:/svn_repos my_working_copy\n</code></pre>\n"
},
{
"answer_id": 278130,
"author": "user34078",
"author_id": 34078,
"author_profile": "https://Stackoverflow.com/users/34078",
"pm_score": 0,
"selected": false,
"text": "<p>Please provide some more details:</p>\n\n<p>What directory are you in when you perform each command?</p>\n\n<p>It looks to me like you may be checking out your project into the repository itself?</p>\n\n<p>Also, what operating system are you using?</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
i tried the following
1. `svnadmin create svn_repos`
2. `svn import my_first_proj file:///c:/svn_repos -m "initial import"`
3. `svn checkout file:///c:/svn_repos`
and the command returned
```
A svn_repos\trunk
A svn_repos\trunk\Sample.txt.txt
A svn_repos\branches
A svn_repos\branches\my_pers_branch
Checked out revision 1.
```
Yet the `.svn` folder was not created in the checked out folders.
Because of which [I guess], I'm not able to do `svn copy` or `svn merge`.
Why does this occur?
what is the problem?
is there anything wrong in my commands
|
Perhaps you're expecting to find that .svn directory inside the my\_first\_proj directory. Currently, your svn is checked out inside a "svn\_repos" directory, relative to the path you typed in the checkout command. What you may want to do is :
```
svn checkout --force file:///c:/svn_repos/ my_first_proj
```
Which checks out a repository inside an existing directory. The usual approach is to checkout to another directory the first time, though.
|
277,726 |
<p>I have a query that is currently using a correlated subquery to return the results, but I am thinking the problem could be solved more eloquently perhaps using ROW_NUMBER().</p>
<p>The problem is around the profile of a value v, through a number of years for an Item. Each item has a number of versions, each with its own profile whick starts when the version is introduced and the data currently looks like this:</p>
<pre>
ItemId ItemVersionId Year Value
===========================================
1 1 01 0.1
1 1 02 0.1
1 1 03 0.2
1 1 04 0.2
1 1 05 0.2
1 1 06 0.3
1 1 07 0.3
1 1 08 0.4
1 2 04 0.3
1 2 05 0.3
1 2 06 0.3
1 2 07 0.4
1 2 08 0.5
1 3 07 0.6
1 3 08 0.7
2 1 01 0.1
2 1 01 0.1
2 1 01 0.2
etc
</pre>
<p>I want to return the full profile for an Item using the most recent version where applicable. For the above example for item 1:</p>
<pre>
ItemId ItemVersionId Year Value
===========================================
1 1 01 0.1
1 1 02 0.1
1 1 03 0.2
1 2 04 0.3
1 2 05 0.3
1 2 06 0.3
1 3 07 0.6
1 3 08 0.7
</pre>
<p>I am currently using</p>
<pre><code>SELECT ItemId, ItemVersionId, Year, Value
FROM table t
WHERE
ItemId = 1
AND ItemVersionId = (SELECT MAX(ItemVersionId) FROM table WHERE ItemId = t.ItemId AND Year = t.Year)
</code></pre>
<p>Whilst this returns the correct I suspect there is a more efficient way to do it, especially when the table gets large.</p>
<p>I am using SQL Server 2005.</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 277740,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 0,
"selected": false,
"text": "<p>I think it's okay how you do it. You could check if there is a <strong>composite index on ItemId and Year</strong>.</p>\n\n<p>You could inspect the query plan to see the impact of that query.</p>\n\n<p>If there is an \"Item\" table in your database you could try another approach. <strong>Insert a column ItemVersionId</strong> in that table and make sure you update that value when new versions are saved. Then in your query <strong>join the Item table using ItemId and ItemVersionId</strong> instead of using that subquery.</p>\n"
},
{
"answer_id": 277762,
"author": "Bliek",
"author_id": 17434,
"author_profile": "https://Stackoverflow.com/users/17434",
"pm_score": 4,
"selected": true,
"text": "<p>I would do it with a CTE:</p>\n\n<pre><code>WITH Result AS\n(\n SELECT Row_Number() OVER (PARTITION BY ItemId, Year\nORDER BY ItemversionId DESC) AS RowNumber\n ,ItemId\n ,ItemversionId\n ,Year\n ,Value\n FROM table\n)\nSELECT ItemId\n ,ItemversionId\n ,Year\n ,Value\nFROM Result\nWHERE RowNumber = 1\nORDER BY ItemId, Year\n</code></pre>\n"
},
{
"answer_id": 278107,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "<p>This should work, although you will have to test performance with your own data:</p>\n\n<pre><code>SELECT\n T1.ItemID,\n T1.ItemVersionID,\n T1.Year,\n T1.Value\nFROM\n MyTable T1\nINNER JOIN (SELECT Year, MAX(ItemVersionID) AS MaxItemVersionID FROM MyTable T2 WHERE T2.ItemID = 1 GROUP BY Year) SQ ON\n SQ.Year = T1.Year AND\n SQ.MaxItemVersionID = T1.ItemVersionID\nWHERE\n T1.ItemID = 1\n</code></pre>\n\n<p>Also, you can alter the subquery to also group by and return an ItemID so that you can return data for more than one item at a time if you need to for some other part of your application. Just be sure to then add the ItemID to the join criteria.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21197/"
] |
I have a query that is currently using a correlated subquery to return the results, but I am thinking the problem could be solved more eloquently perhaps using ROW\_NUMBER().
The problem is around the profile of a value v, through a number of years for an Item. Each item has a number of versions, each with its own profile whick starts when the version is introduced and the data currently looks like this:
```
ItemId ItemVersionId Year Value
===========================================
1 1 01 0.1
1 1 02 0.1
1 1 03 0.2
1 1 04 0.2
1 1 05 0.2
1 1 06 0.3
1 1 07 0.3
1 1 08 0.4
1 2 04 0.3
1 2 05 0.3
1 2 06 0.3
1 2 07 0.4
1 2 08 0.5
1 3 07 0.6
1 3 08 0.7
2 1 01 0.1
2 1 01 0.1
2 1 01 0.2
etc
```
I want to return the full profile for an Item using the most recent version where applicable. For the above example for item 1:
```
ItemId ItemVersionId Year Value
===========================================
1 1 01 0.1
1 1 02 0.1
1 1 03 0.2
1 2 04 0.3
1 2 05 0.3
1 2 06 0.3
1 3 07 0.6
1 3 08 0.7
```
I am currently using
```
SELECT ItemId, ItemVersionId, Year, Value
FROM table t
WHERE
ItemId = 1
AND ItemVersionId = (SELECT MAX(ItemVersionId) FROM table WHERE ItemId = t.ItemId AND Year = t.Year)
```
Whilst this returns the correct I suspect there is a more efficient way to do it, especially when the table gets large.
I am using SQL Server 2005.
Thanks in advance
|
I would do it with a CTE:
```
WITH Result AS
(
SELECT Row_Number() OVER (PARTITION BY ItemId, Year
ORDER BY ItemversionId DESC) AS RowNumber
,ItemId
,ItemversionId
,Year
,Value
FROM table
)
SELECT ItemId
,ItemversionId
,Year
,Value
FROM Result
WHERE RowNumber = 1
ORDER BY ItemId, Year
```
|
277,744 |
<p>I'm getting an Exception while trying to insert a row in oracle table.
I'm using ojdbc5.jar for oracle 11
this is the sql i'm trying </p>
<pre><code>INSERT INTO rule_definitions(RULE_DEFINITION_SYS,rule_definition_type,
rule_name,rule_text,rule_comment,rule_message,rule_condition,rule_active,
rule_type,current_value,last_modified_by,last_modified_dttm,
rule_category_sys,recheck_unit,recheck_period,trackable)
VALUES(RULE_DEFINITIONS_SEQ.NEXTVAL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
</code></pre>
<p>and i get following Exception. Any help will be appreciated.</p>
<pre>
java.ljava.lang.ArrayIndexOutOfBoundsException: 15
at oracle.jdbc.driver.OracleSql.computeBasicInfo(OracleSql.java:950)
at oracle.jdbc.driver.OracleSql.getSqlKind(OracleSql.java:623)
at oracle.jdbc.driver.OraclePreparedStatement.(OraclePreparedStatement.java:1212)
at oracle.jdbc.driver.T4CPreparedStatement.(T4CPreparedStatement.java:28)
at oracle.jdbc.driver.T4CDriverExtension.allocatePreparedStatement(T4CDriverExtension.java:68)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:3059)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:2961)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:5874)
at org.jboss.resource.adapter.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:232)
at com.gehcit.platform.cds.common.util.db.DBWrapper.executeInsertOracleReturnPK(DBWrapper.java:605)
</pre>
|
[
{
"answer_id": 277754,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 0,
"selected": false,
"text": "<p>Without seeing the code, the only thing I can think of is to check that each connection is being accessed in a thread safe manner. The Oracle drivers are usually pretty solid. The only time I've seen weird internal errors like that is when you've got more than one thread accessing the same connection instance and doing weird stuff with it. They aren't thread safe, and should be kept to one per thread.</p>\n"
},
{
"answer_id": 277755,
"author": "Arne Burmeister",
"author_id": 12890,
"author_profile": "https://Stackoverflow.com/users/12890",
"pm_score": 0,
"selected": false,
"text": "<p>You create a prepared statement with 15 placeholders, if i understand correct. So you need to pass an array with 15 parameter values to the call. Maybe you missed one or added a surplus one?</p>\n"
},
{
"answer_id": 277894,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like you're passing in the wrong number of parameters. You should be passing in 15, but you're either sending 16 or 14.</p>\n"
},
{
"answer_id": 277904,
"author": "Colin Pickard",
"author_id": 12744,
"author_profile": "https://Stackoverflow.com/users/12744",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah unless my mouse-cursor-counting is off, you're trying to insert 16 values into 15 columns.</p>\n\n<p>Try the same thing SQLPlus*, you should get ORA-00913: too many values</p>\n"
},
{
"answer_id": 280527,
"author": "Raimonds Simanovskis",
"author_id": 16829,
"author_profile": "https://Stackoverflow.com/users/16829",
"pm_score": 6,
"selected": true,
"text": "<p>In Oracle Metalink (Oracle's support site - Note ID 736273.1) I found that this is a bug in JDBC adapter (version 10.2.0.0.0 to 11.1.0.7.0) that when you call preparedStatement with more than 7 positional parameters then JDBC will throw this error.</p>\n\n<p>If you have access to Oracle Metalink then one option is to go there and download mentioned patch.</p>\n\n<p>The other solution is workaround - use named parameters instead of positional parameters:</p>\n\n<pre><code>INSERT INTO rule_definitions(RULE_DEFINITION_SYS,rule_definition_type,\nrule_name,rule_text,rule_comment,rule_message,rule_condition,rule_active,\nrule_type,current_value,last_modified_by,last_modified_dttm,\nrule_category_sys,recheck_unit,recheck_period,trackable)\nVALUES(RULE_DEFINITIONS_SEQ.NEXTVAL,:rule_definition_type,\n:rule_name,:rule_text,:rule_comment,:rule_message,:rule_condition,:rule_active,\n:rule_type,:current_value,:last_modified_by,:last_modified_dttm,\n:rule_category_sys,:recheck_unit,:recheck_period,:trackable)\n</code></pre>\n\n<p>and then use</p>\n\n<pre><code>preparedStatement.setStringAtName(\"rule_definition_type\", ...)\n</code></pre>\n\n<p>etc. to set named bind variables for this query.</p>\n"
},
{
"answer_id": 11360203,
"author": "Kirsten",
"author_id": 1506406,
"author_profile": "https://Stackoverflow.com/users/1506406",
"pm_score": 0,
"selected": false,
"text": "<p>When you don't have access to the oracle.jdbc.PreparedStatement class (and are forced to use java.sql.PreparedStatement, which does not support the methods #setXXXAtName()), the proposed solution to use named parameters is not an option.</p>\n\n<p>I've used the PreparedStatement and GeneratedKeyHolder approach for the mandatory values to be passed (luckily less than 7), and used the generated primary key returned to issue a simple SQL update for the remaining values.</p>\n"
},
{
"answer_id": 38477322,
"author": "Siva Anand",
"author_id": 2573744,
"author_profile": "https://Stackoverflow.com/users/2573744",
"pm_score": 1,
"selected": false,
"text": "<p>i am using mybatis + oracle + spring + maven.\nSame error \"arrayindexoutofboundsexception\", if having 8 (or) above parameters.</p>\n\n<p>In pom changed version ojdbc6 to ojdbc14,</p>\n\n<pre><code> <dependency>\n <groupId>com.oracle</groupId>\n <artifactId>ojdbc14</artifactId>\n <version>10.2.0.3.0</version>\n </dependency>\n</code></pre>\n\n<p>It worked.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11247/"
] |
I'm getting an Exception while trying to insert a row in oracle table.
I'm using ojdbc5.jar for oracle 11
this is the sql i'm trying
```
INSERT INTO rule_definitions(RULE_DEFINITION_SYS,rule_definition_type,
rule_name,rule_text,rule_comment,rule_message,rule_condition,rule_active,
rule_type,current_value,last_modified_by,last_modified_dttm,
rule_category_sys,recheck_unit,recheck_period,trackable)
VALUES(RULE_DEFINITIONS_SEQ.NEXTVAL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
```
and i get following Exception. Any help will be appreciated.
```
java.ljava.lang.ArrayIndexOutOfBoundsException: 15
at oracle.jdbc.driver.OracleSql.computeBasicInfo(OracleSql.java:950)
at oracle.jdbc.driver.OracleSql.getSqlKind(OracleSql.java:623)
at oracle.jdbc.driver.OraclePreparedStatement.(OraclePreparedStatement.java:1212)
at oracle.jdbc.driver.T4CPreparedStatement.(T4CPreparedStatement.java:28)
at oracle.jdbc.driver.T4CDriverExtension.allocatePreparedStatement(T4CDriverExtension.java:68)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:3059)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:2961)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:5874)
at org.jboss.resource.adapter.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:232)
at com.gehcit.platform.cds.common.util.db.DBWrapper.executeInsertOracleReturnPK(DBWrapper.java:605)
```
|
In Oracle Metalink (Oracle's support site - Note ID 736273.1) I found that this is a bug in JDBC adapter (version 10.2.0.0.0 to 11.1.0.7.0) that when you call preparedStatement with more than 7 positional parameters then JDBC will throw this error.
If you have access to Oracle Metalink then one option is to go there and download mentioned patch.
The other solution is workaround - use named parameters instead of positional parameters:
```
INSERT INTO rule_definitions(RULE_DEFINITION_SYS,rule_definition_type,
rule_name,rule_text,rule_comment,rule_message,rule_condition,rule_active,
rule_type,current_value,last_modified_by,last_modified_dttm,
rule_category_sys,recheck_unit,recheck_period,trackable)
VALUES(RULE_DEFINITIONS_SEQ.NEXTVAL,:rule_definition_type,
:rule_name,:rule_text,:rule_comment,:rule_message,:rule_condition,:rule_active,
:rule_type,:current_value,:last_modified_by,:last_modified_dttm,
:rule_category_sys,:recheck_unit,:recheck_period,:trackable)
```
and then use
```
preparedStatement.setStringAtName("rule_definition_type", ...)
```
etc. to set named bind variables for this query.
|
277,771 |
<p>How do I create, execute and control a winform from within a console application?</p>
|
[
{
"answer_id": 277776,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 8,
"selected": true,
"text": "<p>The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:</p>\n\n<pre><code>using System.Windows.Forms;\n\n[STAThread]\nstatic void Main() {\n Application.EnableVisualStyles();\n Application.Run(new Form()); // or whatever\n}\n</code></pre>\n\n<p>The important bit is the <code>[STAThread]</code> on your <code>Main()</code> method, required for full COM support.</p>\n"
},
{
"answer_id": 277778,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 3,
"selected": false,
"text": "<p>You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.</p>\n"
},
{
"answer_id": 277781,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application</p>\n"
},
{
"answer_id": 279811,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Here is the best method that I've found:\nFirst, set your projects output type to \"Windows Application\", then P/Invoke AllocConsole to create a console window.</p>\n\n<pre><code>internal static class NativeMethods\n{\n [DllImport(\"kernel32.dll\")]\n internal static extern Boolean AllocConsole();\n}\n\nstatic class Program\n{\n\n static void Main(string[] args) {\n if (args.Length == 0) {\n // run as windows app\n Application.EnableVisualStyles();\n Application.Run(new Form1()); \n } else {\n // run as console app\n NativeMethods.AllocConsole();\n Console.WriteLine(\"Hello World\");\n Console.ReadLine();\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 8347807,
"author": "SharpShade",
"author_id": 559310,
"author_profile": "https://Stackoverflow.com/users/559310",
"pm_score": 3,
"selected": false,
"text": "<p>It´s very simple to do:</p>\n\n<p>Just add following attribute and code to your Main-method:</p>\n\n<pre><code>[STAThread]\nvoid Main(string[] args])\n{\n Application.EnableVisualStyles();\n //Do some stuff...\n while(!Exit)\n {\n Application.DoEvents(); //Now if you call \"form.Show()\" your form won´t be frozen\n //Do your stuff\n }\n}\n</code></pre>\n\n<p>Now you´re fully able to show WinForms :)</p>\n"
},
{
"answer_id": 11058118,
"author": "Tergiver",
"author_id": 351385,
"author_profile": "https://Stackoverflow.com/users/351385",
"pm_score": 5,
"selected": false,
"text": "<p>I recently wanted to do this and found that I was not happy with any of the answers here.</p>\n\n<p>If you follow Marc's advice and set the output-type to Console Application there are two problems:</p>\n\n<p>1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn't go away until your program exits. We can mitigate this problem by calling FreeConsole prior to showing the GUI (Application.Run). The annoyance here is that the console window still appears. It immediately goes away, but is there for a moment none-the-less.</p>\n\n<p>2) If you launch it from a console, and display a GUI, the console is blocked until the GUI exits. This is because the console (cmd.exe) thinks it should launch Console apps synchronously and Windows apps asynchronously (the unix equivalent of \"myprocess &\"). \n<br/></p>\n\n<p><br/>\nIf you leave the output-type as Windows Application, but <em>correctly</em> call AttachConsole, you don't get a second console window when invoked from a console and you don't get the unnecessary console when invoked from Explorer. The correct way to call AttachConsole is to pass -1 to it. This causes our process to attach to the console of our parent process (the console window that launched us).</p>\n\n<p>However, this has two different problems:</p>\n\n<p>1) Because the console launches Windows apps in the background, it immediately displays the prompt and allows further input. On the one hand this is good news, the console is not blocked on your GUI app, but in the case where you want to dump output to the console and never show the GUI, your program's output comes after the prompt and no new prompt is displayed when you're done. This looks a bit confusing, not to mention that your \"console app\" is running in the background and the user is free to execute other commands while it's running.</p>\n\n<p>2) Stream redirection gets messed up as well, e.g. \"myapp some parameters > somefile\" fails to redirect. The stream redirection problem requires a significant amount of p/Invoke to fixup the standard handles, but it is solvable.\n<br/></p>\n\n<p><br/>\nAfter many hours of hunting and experimenting, I've come to the conclusion that there is no way to do this perfectly. You simply cannot get all the benefits of both console and window without any side effects. It's a matter of picking which side effects are least annoying for your application's purposes.</p>\n"
},
{
"answer_id": 31307612,
"author": "SunsetQuest",
"author_id": 2352507,
"author_profile": "https://Stackoverflow.com/users/2352507",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for my needs...</p>\n\n<pre><code>Task mytask = Task.Run(() =>\n{\n MyForm form = new MyForm();\n form.ShowDialog();\n});\n</code></pre>\n\n<p>This starts the from in a new thread and does not release the thread until the form is closed. <code>Task</code> is in .Net 4 and later. </p>\n"
},
{
"answer_id": 32155377,
"author": "Raj kumar",
"author_id": 1642862,
"author_profile": "https://Stackoverflow.com/users/1642862",
"pm_score": 0,
"selected": false,
"text": "<p>Its totally depends upon your choice, that how you are implementing.<br/>\na. Attached process , ex: input on form and print on console <br/>\nb. Independent process, ex: start a timer, don't close even if console exit.</p>\n\n<p>for a,</p>\n\n<pre><code>Application.Run(new Form1());\n//or -------------\nForm1 f = new Form1();\nf.ShowDialog();\n</code></pre>\n\n<p>for b,\nUse thread, or task anything,\n<a href=\"http://www.asptricks.net/2015/08/how-to-run-windows-form-from-console.html\" rel=\"nofollow\">How to open win form independently?</a></p>\n"
},
{
"answer_id": 49944418,
"author": "AndrewToasterr",
"author_id": 9675356,
"author_profile": "https://Stackoverflow.com/users/9675356",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to escape from <b>Form Freeze</b> and use editing (like text for a button) use this code</p>\n\n<pre><code>Form form = new Form();\nForm.Button.Text = \"randomText\";\nSystem.Windows.Forms.Application.EnableVisualStyles();\nSystem.Windows.Forms.Application.Run(form);\n</code></pre>\n"
},
{
"answer_id": 50827451,
"author": "Biju Joseph",
"author_id": 7453276,
"author_profile": "https://Stackoverflow.com/users/7453276",
"pm_score": 2,
"selected": false,
"text": "<p>All the above answers are great help, but I thought to add some more tips for the absolute beginner.</p>\n\n<p>So, you want to do something with <strong>Windows Forms, in a Console Application:</strong></p>\n\n<p>Add a reference to <strong>System.Windows.Forms.dll</strong> in your Console application project in Solution Explorer. (Right Click on Solution-name->add->Reference...)</p>\n\n<p>Specify the name space in code: <code>using System.Windows.Forms;</code></p>\n\n<p>Declare the needed properties in your class for the controls you wish to add to the form.</p>\n\n<p>e.g. <code>int Left { get; set; } // need to specify the LEFT position of the button on the Form</code></p>\n\n<p>And then add the following code snippet in <code>Main()</code>:</p>\n\n<pre><code>static void Main(string[] args)\n{\nApplication.EnableVisualStyles();\n Form frm = new Form(); // create aForm object\n\n Button btn = new Button()\n {\n Left = 120,\n Width = 130,\n Height = 30,\n Top = 150,\n Text = \"Biju Joseph, Redmond, WA\"\n };\n //… more code \n frm.Controls.Add(btn); // add button to the Form\n // …. add more code here as needed\n\n frm.ShowDialog(); // a modal dialog \n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30717/"
] |
How do I create, execute and control a winform from within a console application?
|
The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:
```
using System.Windows.Forms;
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form()); // or whatever
}
```
The important bit is the `[STAThread]` on your `Main()` method, required for full COM support.
|
277,772 |
<p>I keep stumbling on the format specifiers for the printf() family of functions. What I want is to be able to print a double (or float) with a maximum given number of digits after the decimal point. If I use:</p>
<pre><code>printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
</code></pre>
<p>I get</p>
<pre><code>359.013
359.010
</code></pre>
<p>Instead of the desired</p>
<pre><code>359.013
359.01
</code></pre>
<p>Can anybody help me?</p>
|
[
{
"answer_id": 277779,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": false,
"text": "<p>To get rid of the trailing zeros, you should use the \"%g\" format:</p>\n\n<pre><code>float num = 1.33;\nprintf(\"%g\", num); //output: 1.33\n</code></pre>\n\n<p>After the question was clarified a bit, that suppressing zeros is not the only thing that was asked, but limiting the output to three decimal places was required as well. I think that can't be done with sprintf format strings alone. As <a href=\"https://stackoverflow.com/questions/277772/#277810\">Pax Diablo</a> pointed out, string manipulation would be required.</p>\n"
},
{
"answer_id": 277810,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": true,
"text": "<p>This can't be done with the normal <code>printf</code> format specifiers. The closest you could get would be:</p>\n\n<pre><code>printf(\"%.6g\", 359.013); // 359.013\nprintf(\"%.6g\", 359.01); // 359.01\n</code></pre>\n\n<p>but the \".6\" is the <em>total</em> numeric width so</p>\n\n<pre><code>printf(\"%.6g\", 3.01357); // 3.01357\n</code></pre>\n\n<p>breaks it.</p>\n\n<p>What you <em>can</em> do is to <code>sprintf(\"%.20g\")</code> the number to a string buffer then manipulate the string to only have N characters past the decimal point.</p>\n\n<p>Assuming your number is in the variable num, the following function will remove all but the first <code>N</code> decimals, then strip off the trailing zeros (and decimal point if they were all zeros).</p>\n\n<pre><code>char str[50];\nsprintf (str,\"%.20g\",num); // Make the number.\nmorphNumericString (str, 3);\n: :\nvoid morphNumericString (char *s, int n) {\n char *p;\n int count;\n\n p = strchr (s,'.'); // Find decimal point, if any.\n if (p != NULL) {\n count = n; // Adjust for more or less decimals.\n while (count >= 0) { // Maximum decimals allowed.\n count--;\n if (*p == '\\0') // If there's less than desired.\n break;\n p++; // Next character.\n }\n\n *p-- = '\\0'; // Truncate string.\n while (*p == '0') // Remove trailing zeros.\n *p-- = '\\0';\n\n if (*p == '.') { // If all decimals were zeros, remove \".\".\n *p = '\\0';\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If you're not happy with the truncation aspect (which would turn <code>0.12399</code> into <code>0.123</code> rather than rounding it to <code>0.124</code>), you can actually use the rounding facilities already provided by <code>printf</code>. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:</p>\n\n<pre><code>#include <stdio.h>\n\nvoid nDecimals (char *s, double d, int n) {\n int sz; double d2;\n\n // Allow for negative.\n\n d2 = (d >= 0) ? d : -d;\n sz = (d >= 0) ? 0 : 1;\n\n // Add one for each whole digit (0.xx special case).\n\n if (d2 < 1) sz++;\n while (d2 >= 1) { d2 /= 10.0; sz++; }\n\n // Adjust for decimal point and fractionals.\n\n sz += 1 + n;\n\n // Create format string then use it.\n\n sprintf (s, \"%*.*f\", sz, n, d);\n}\n\nint main (void) {\n char str[50];\n double num[] = { 40, 359.01335, -359.00999,\n 359.01, 3.01357, 0.111111111, 1.1223344 };\n for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {\n nDecimals (str, num[i], 3);\n printf (\"%30.20f -> %s\\n\", num[i], str);\n }\n return 0;\n}\n</code></pre>\n\n<p>The whole point of <code>nDecimals()</code> in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness <code>main()</code> shows this in action:</p>\n\n<pre><code> 40.00000000000000000000 -> 40.000\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.010\n 359.00999999999999090505 -> 359.010\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n</code></pre>\n\n<p>Once you have the correctly rounded value, you can once again pass that to <code>morphNumericString()</code> to remove trailing zeros by simply changing:</p>\n\n<pre><code>nDecimals (str, num[i], 3);\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>nDecimals (str, num[i], 3);\nmorphNumericString (str, 3);\n</code></pre>\n\n<p>(or calling <code>morphNumericString</code> at the end of <code>nDecimals</code> but, in that case, I'd probably just combine the two into one function), and you end up with:</p>\n\n<pre><code> 40.00000000000000000000 -> 40\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.01\n 359.00999999999999090505 -> 359.01\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n</code></pre>\n"
},
{
"answer_id": 278033,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my first try at an answer:</p>\n\n<pre>\nvoid\nxprintfloat(char *format, float f)\n{\n char s[50];\n char *p;\n\n sprintf(s, format, f);\n for(p=s; *p; ++p)\n if('.' == *p) {\n while(*++p);\n while('0'==*--p) *p = '\\0';\n }\n printf(\"%s\", s);\n}\n</pre>\n\n<p>Known bugs: Possible buffer overflow depending on format. If \".\" is present for other reason than %f wrong result might happen.</p>\n"
},
{
"answer_id": 2174887,
"author": "David Thornley",
"author_id": 196390,
"author_profile": "https://Stackoverflow.com/users/196390",
"pm_score": 0,
"selected": false,
"text": "<p>Slight variation on above:</p>\n\n<ol>\n<li>Eliminates period for case (10000.0).</li>\n<li>Breaks after first period is processed.</li>\n</ol>\n\n<p>Code here:</p>\n\n<pre><code>void EliminateTrailingFloatZeros(char *iValue)\n{\n char *p = 0;\n for(p=iValue; *p; ++p) {\n if('.' == *p) {\n while(*++p);\n while('0'==*--p) *p = '\\0';\n if(*p == '.') *p = '\\0';\n break;\n }\n }\n}\n</code></pre>\n\n<p>It still has potential for overflow, so be careful ;P</p>\n"
},
{
"answer_id": 3201560,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 2,
"selected": false,
"text": "<p>What about something like this (might have rounding errors and negative-value issues that need debugging, left as an exercise for the reader):</p>\n\n<pre><code>printf(\"%.0d%.4g\\n\", (int)f/10, f-((int)f-(int)f%10));\n</code></pre>\n\n<p>It's slightly programmatic but at least it doesn't make you do any string manipulation.</p>\n"
},
{
"answer_id": 4247516,
"author": "Juha",
"author_id": 311323,
"author_profile": "https://Stackoverflow.com/users/311323",
"pm_score": 4,
"selected": false,
"text": "<p>I like the answer of R. slightly tweaked:</p>\n\n<pre><code>float f = 1234.56789;\nprintf(\"%d.%.0f\", f, 1000*(f-(int)f));\n</code></pre>\n\n<p>'1000' determines the precision.</p>\n\n<p><em>Power to the 0.5 rounding.</em></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Ok, this answer was edited a few times and I lost track what I was thinking a few years back (and originally it did not fill all the criteria). So here is a new version (that fills all criteria and handles negative numbers correctly):</p>\n\n<pre><code>double f = 1234.05678900;\nchar s[100]; \nint decimals = 10;\n\nsprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\nprintf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n</code></pre>\n\n<p>And the test cases:</p>\n\n<pre><code>#import <stdio.h>\n#import <stdlib.h>\n#import <math.h>\n\nint main(void){\n\n double f = 1234.05678900;\n char s[100];\n int decimals;\n\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" 3 decimals: %d%s\\n\", (int)f, s+1);\n\n f = -f;\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 10: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 3: %d%s\\n\", (int)f, s+1);\n\n decimals = 2;\n f = 1.012;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" additional : %d%s\\n\", (int)f, s+1);\n\n return 0;\n}\n</code></pre>\n\n<p>And the output of the tests:</p>\n\n<pre><code> 10 decimals: 1234.056789\n 3 decimals: 1234.057\n negative 10: -1234.056789\n negative 3: -1234.057\n additional : 1.01\n</code></pre>\n\n<p>Now, all criteria are met:</p>\n\n<ul>\n<li>maximum number of decimals behind the zero is fixed</li>\n<li>trailing zeros are removed</li>\n<li>it does it mathematically right (right?)</li>\n<li>works (now) also when first decimal is zero </li>\n</ul>\n\n<p>Unfortunately this answer is a two-liner as <code>sprintf</code> does not return the string.</p>\n"
},
{
"answer_id": 15127324,
"author": "Iaijutsu",
"author_id": 2118088,
"author_profile": "https://Stackoverflow.com/users/2118088",
"pm_score": 1,
"selected": false,
"text": "<p>A simple solution but it gets the job done, assigns a known length and precision and avoids the chance of going exponential format (which is a risk when you use %g):</p>\n\n<pre><code>// Since we are only interested in 3 decimal places, this function\n// can avoid any potential miniscule floating point differences\n// which can return false when using \"==\"\nint DoubleEquals(double i, double j)\n{\n return (fabs(i - j) < 0.000001);\n}\n\nvoid PrintMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%.2f\", d);\n else\n printf(\"%.3f\", d);\n}\n</code></pre>\n\n<p>Add or remove \"elses\" if you want a max of 2 decimals; 4 decimals; etc.</p>\n\n<p>For example if you wanted 2 decimals:</p>\n\n<pre><code>void PrintMaxTwoDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else\n printf(\"%.2f\", d);\n}\n</code></pre>\n\n<p>If you want to specify the minimum width to keep fields aligned, increment as necessary, for example:</p>\n\n<pre><code>void PrintAlignedMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%7.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%9.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%10.2f\", d);\n else\n printf(\"%11.3f\", d);\n}\n</code></pre>\n\n<p>You could also convert that to a function where you pass the desired width of the field:</p>\n\n<pre><code>void PrintAlignedWidthMaxThreeDecimal(int w, double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%*.0f\", w-4, d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%*.1f\", w-2, d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%*.2f\", w-1, d);\n else\n printf(\"%*.3f\", w, d);\n}\n</code></pre>\n"
},
{
"answer_id": 15285177,
"author": "DaveR",
"author_id": 2146709,
"author_profile": "https://Stackoverflow.com/users/2146709",
"pm_score": 2,
"selected": false,
"text": "<p>I search the string (starting rightmost) for the first character in the range <code>1</code> to <code>9</code> (ASCII value <code>49</code>-<code>57</code>) then <code>null</code> (set to <code>0</code>) each char right of it - see below:</p>\n\n<pre><code>void stripTrailingZeros(void) { \n //This finds the index of the rightmost ASCII char[1-9] in array\n //All elements to the left of this are nulled (=0)\n int i = 20;\n unsigned char char1 = 0; //initialised to ensure entry to condition below\n\n while ((char1 > 57) || (char1 < 49)) {\n i--;\n char1 = sprintfBuffer[i];\n }\n\n //null chars left of i\n for (int j = i; j < 20; j++) {\n sprintfBuffer[i] = 0;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18993051,
"author": "TeamXlink",
"author_id": 2812967,
"author_profile": "https://Stackoverflow.com/users/2812967",
"pm_score": -1,
"selected": false,
"text": "<p>Your code rounds to three decimal places due to the \".3\" before the f</p>\n\n<pre><code>printf(\"%1.3f\", 359.01335);\nprintf(\"%1.3f\", 359.00999);\n</code></pre>\n\n<p>Thus if you the second line rounded to two decimal places, you should change it to this:</p>\n\n<pre><code>printf(\"%1.3f\", 359.01335);\nprintf(\"%1.2f\", 359.00999);\n</code></pre>\n\n<p>That code will output your desired results:</p>\n\n<pre><code>359.013\n359.01\n</code></pre>\n\n<p>*Note this is assuming you already have it printing on separate lines, if not then the following will prevent it from printing on the same line:</p>\n\n<pre><code>printf(\"%1.3f\\n\", 359.01335);\nprintf(\"%1.2f\\n\", 359.00999);\n</code></pre>\n\n<p>The Following program source code was my test for this answer</p>\n\n<pre><code>#include <cstdio>\n\nint main()\n{\n\n printf(\"%1.3f\\n\", 359.01335);\n printf(\"%1.2f\\n\", 359.00999);\n\n while (true){}\n\n return 0;\n\n}\n</code></pre>\n"
},
{
"answer_id": 25313464,
"author": "Jim Hunziker",
"author_id": 6160,
"author_profile": "https://Stackoverflow.com/users/6160",
"pm_score": 3,
"selected": false,
"text": "<p>Why not just do this?</p>\n\n<pre><code>double f = 359.01335;\nprintf(\"%g\", round(f * 1000.0) / 1000.0);\n</code></pre>\n"
},
{
"answer_id": 33448480,
"author": "magnusviri",
"author_id": 5509250,
"author_profile": "https://Stackoverflow.com/users/5509250",
"pm_score": 1,
"selected": false,
"text": "<p>I found problems in some of the solutions posted. I put this together based on answers above. It seems to work for me.</p>\n\n<pre><code>int doubleEquals(double i, double j) {\n return (fabs(i - j) < 0.000001);\n}\n\nvoid printTruncatedDouble(double dd, int max_len) {\n char str[50];\n int match = 0;\n for ( int ii = 0; ii < max_len; ii++ ) {\n if (doubleEquals(dd * pow(10,ii), floor(dd * pow(10,ii)))) {\n sprintf (str,\"%f\", round(dd*pow(10,ii))/pow(10,ii));\n match = 1;\n break;\n }\n }\n if ( match != 1 ) {\n sprintf (str,\"%f\", round(dd*pow(10,max_len))/pow(10,max_len));\n }\n char *pp;\n int count;\n pp = strchr (str,'.');\n if (pp != NULL) {\n count = max_len;\n while (count >= 0) {\n count--;\n if (*pp == '\\0')\n break;\n pp++;\n }\n *pp-- = '\\0';\n while (*pp == '0')\n *pp-- = '\\0';\n if (*pp == '.') {\n *pp = '\\0';\n }\n }\n printf (\"%s\\n\", str);\n}\n\nint main(int argc, char **argv)\n{\n printTruncatedDouble( -1.999, 2 ); // prints -2\n printTruncatedDouble( -1.006, 2 ); // prints -1.01\n printTruncatedDouble( -1.005, 2 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.005, 2 ); // prints 1 (should be 1.01?)\n printTruncatedDouble( 1.006, 2 ); // prints 1.01\n printTruncatedDouble( 1.999, 2 ); // prints 2\n printf(\"\\n\");\n printTruncatedDouble( -1.999, 3 ); // prints -1.999\n printTruncatedDouble( -1.001, 3 ); // prints -1.001\n printTruncatedDouble( -1.0005, 3 ); // prints -1.001 (shound be -1?)\n printTruncatedDouble( -1.0004, 3 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.0004, 3 ); // prints 1\n printTruncatedDouble( 1.0005, 3 ); // prints 1.001\n printTruncatedDouble( 1.001, 3 ); // prints 1.001\n printTruncatedDouble( 1.999, 3 ); // prints 1.999\n printf(\"\\n\");\n exit(0);\n}\n</code></pre>\n"
},
{
"answer_id": 36202854,
"author": "nwellnhof",
"author_id": 1956010,
"author_profile": "https://Stackoverflow.com/users/1956010",
"pm_score": 2,
"selected": false,
"text": "<p>Some of the highly voted solutions suggest the <code>%g</code> conversion specifier of <code>printf</code>. This is wrong because there are cases where <code>%g</code> will produce scientific notation. Other solutions use math to print the desired number of decimal digits.</p>\n\n<p>I think the easiest solution is to use <code>sprintf</code> with the <code>%f</code> conversion specifier and to manually remove trailing zeros and possibly a decimal point from the result. Here's a C99 solution:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nchar*\nformat_double(double d) {\n int size = snprintf(NULL, 0, \"%.3f\", d);\n char *str = malloc(size + 1);\n snprintf(str, size + 1, \"%.3f\", d);\n\n for (int i = size - 1, end = size; i >= 0; i--) {\n if (str[i] == '0') {\n if (end == i + 1) {\n end = i;\n }\n }\n else if (str[i] == '.') {\n if (end == i + 1) {\n end = i;\n }\n str[end] = '\\0';\n break;\n }\n }\n\n return str;\n}\n</code></pre>\n\n<p>Note that the characters used for digits and the decimal separator depend on the current locale. The code above assumes a C or US English locale.</p>\n"
},
{
"answer_id": 61432422,
"author": "Ankit Mishra",
"author_id": 13272795,
"author_profile": "https://Stackoverflow.com/users/13272795",
"pm_score": 0,
"selected": false,
"text": "<p>I would say you should use\n <code>printf(\"%.8g\",value);</code> </p>\n\n<p>If you use <code>\"%.6g\"</code> you will not get desired output for some numbers like.32.230210 it should print <code>32.23021</code> but it prints <code>32.2302</code></p>\n"
},
{
"answer_id": 63631055,
"author": "ravin.wang",
"author_id": 3968307,
"author_profile": "https://Stackoverflow.com/users/3968307",
"pm_score": 0,
"selected": false,
"text": "<p>Hit the same issue, double precision is 15 decimal, and float precision is 6 decimal, so I wrote to 2 functions for them separately</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <stdio.h>\n#include <math.h>\n#include <string>\n#include <string.h>\n\nstd::string doublecompactstring(double d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return "NAN";\n sprintf(buf, "%.15f", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nstd::string floatcompactstring(float d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return "NAN";\n sprintf(buf, "%.6f", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nint main(int argc, const char* argv[])\n{\n double a = 0.000000000000001;\n float b = 0.000001f;\n\n printf("a: %s\\n", doublecompactstring(a).c_str());\n printf("b: %s\\n", floatcompactstring(b).c_str());\n return 0;\n}\n</code></pre>\n<p>output is</p>\n<pre><code>a: 0.000000000000001\nb: 0.000001\n</code></pre>\n"
},
{
"answer_id": 67717966,
"author": "baah",
"author_id": 16046159,
"author_profile": "https://Stackoverflow.com/users/16046159",
"pm_score": 0,
"selected": false,
"text": "<p>I needed that and the first answer from paxdiablo does the trick. But I was not needing truncating and the version below is maybe slightly faster?\nStarting to search end of string (EOS) after the ".", only one placement of EOS.</p>\n<pre><code>//https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf\n//adapted from paxdiablo (removed truncating)\nchar StringForDouble[50];\nchar *PointerInString;\nvoid PrintDouble (double number) {\n sprintf(StringForDouble,"%.10f",number); // convert number to string\n PointerInString=strchr(&StringForDouble[0],'.'); // find decimal point, if any\n if(PointerInString!=NULL) {\n PointerInString=strchr(&PointerInString[0],'\\0'); // find end of string\n do{\n PointerInString--;\n } while(PointerInString[0]=='0'); // remove trailing zeros\n if (PointerInString[0]=='.') { // if all decimals were zeros, remove "."\n PointerInString[0]='\\0';\n } else {\n PointerInString[1]='\\0'; //otherwise put EOS after the first non zero char\n }\n }\n printf("%s",&StringForDouble[0]);\n}\n</code></pre>\n"
},
{
"answer_id": 70378558,
"author": "user1686153",
"author_id": 1686153,
"author_profile": "https://Stackoverflow.com/users/1686153",
"pm_score": 1,
"selected": false,
"text": "<p>My idea is to calculate the <em>required</em> precision that would not result in trailing zeroes for a given double value and pass it to the <code>"%1.*f"</code> format in printf().\nThis can even be done as one-liner:</p>\n<pre><code>int main() {\n double r=1234.56789;\n int precision=3;\n printf(L"%1.*f", prec(r, precision), r);\n}\n\nint prec(const double& r, int precision)\n{\n double rPos = (r < 0)? -r : r;\n double nkd = fmod(rPos, 1.0); // 0..0.99999999\n int i, ex10 = 1;\n for (i = 0; i < precision; ++i)\n ex10 *= 10;\n int nki = (int)(nkd * ex10 + 0.5);\n\n // "Eliminate" trailing zeroes\n int requiredPrecision = precision;\n for (; requiredPrecision && !(nki % 10); ) {\n --requiredPrecision;\n nki /= 10;\n }\n return requiredPrecision; \n}\n</code></pre>\n<p>And here is another <code>%g</code> solution. You should always provide a format precision that is "wide enough" (default is only 6) and round the value. I think this is a nice way to do it:</p>\n<pre><code>double round(const double &value, const double& rounding) {\n return rounding!=0 ? floor(value/rounding + 0.5)*rounding : value;\n}\n\nprintf("%.12g" round(val, 0.001)); // prints up to 3 relevant digits\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25824/"
] |
I keep stumbling on the format specifiers for the printf() family of functions. What I want is to be able to print a double (or float) with a maximum given number of digits after the decimal point. If I use:
```
printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
```
I get
```
359.013
359.010
```
Instead of the desired
```
359.013
359.01
```
Can anybody help me?
|
This can't be done with the normal `printf` format specifiers. The closest you could get would be:
```
printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01); // 359.01
```
but the ".6" is the *total* numeric width so
```
printf("%.6g", 3.01357); // 3.01357
```
breaks it.
What you *can* do is to `sprintf("%.20g")` the number to a string buffer then manipulate the string to only have N characters past the decimal point.
Assuming your number is in the variable num, the following function will remove all but the first `N` decimals, then strip off the trailing zeros (and decimal point if they were all zeros).
```
char str[50];
sprintf (str,"%.20g",num); // Make the number.
morphNumericString (str, 3);
: :
void morphNumericString (char *s, int n) {
char *p;
int count;
p = strchr (s,'.'); // Find decimal point, if any.
if (p != NULL) {
count = n; // Adjust for more or less decimals.
while (count >= 0) { // Maximum decimals allowed.
count--;
if (*p == '\0') // If there's less than desired.
break;
p++; // Next character.
}
*p-- = '\0'; // Truncate string.
while (*p == '0') // Remove trailing zeros.
*p-- = '\0';
if (*p == '.') { // If all decimals were zeros, remove ".".
*p = '\0';
}
}
}
```
---
If you're not happy with the truncation aspect (which would turn `0.12399` into `0.123` rather than rounding it to `0.124`), you can actually use the rounding facilities already provided by `printf`. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:
```
#include <stdio.h>
void nDecimals (char *s, double d, int n) {
int sz; double d2;
// Allow for negative.
d2 = (d >= 0) ? d : -d;
sz = (d >= 0) ? 0 : 1;
// Add one for each whole digit (0.xx special case).
if (d2 < 1) sz++;
while (d2 >= 1) { d2 /= 10.0; sz++; }
// Adjust for decimal point and fractionals.
sz += 1 + n;
// Create format string then use it.
sprintf (s, "%*.*f", sz, n, d);
}
int main (void) {
char str[50];
double num[] = { 40, 359.01335, -359.00999,
359.01, 3.01357, 0.111111111, 1.1223344 };
for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
nDecimals (str, num[i], 3);
printf ("%30.20f -> %s\n", num[i], str);
}
return 0;
}
```
The whole point of `nDecimals()` in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness `main()` shows this in action:
```
40.00000000000000000000 -> 40.000
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
359.00999999999999090505 -> 359.010
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
```
Once you have the correctly rounded value, you can once again pass that to `morphNumericString()` to remove trailing zeros by simply changing:
```
nDecimals (str, num[i], 3);
```
into:
```
nDecimals (str, num[i], 3);
morphNumericString (str, 3);
```
(or calling `morphNumericString` at the end of `nDecimals` but, in that case, I'd probably just combine the two into one function), and you end up with:
```
40.00000000000000000000 -> 40
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
359.00999999999999090505 -> 359.01
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
```
|
277,775 |
<p>I want to call a c# function from my javascript function.</p>
<p>I have a link button in my ascx (please see the code below). The problem is that if you press enter in firefox is not working however it is working fine in internet explorer.</p>
<pre><code><li class="clearfix border_top">
<label for="title" class="first_column bold">Search For</label>
<div class="contactUs_details">
<input type="text" id="advanced_txtBox1" name="advanced_txtBox1" class="searchbox" runat="server" style="width:300px;" />&nbsp;&nbsp;&nbsp;&nbsp;
<asp:CheckBox ID="chkSearchBDJ" runat="server" Text="Search BDJ" CssClass="checkboxlistnoborder" />
</div>
</li>
<div class="img_SearchNow">
<asp:LinkButton ID="btnSearchNow" CausesValidation="true" runat="server" OnClick="btnSearchNow_Click"></asp:LinkButton>
</div>
</code></pre>
<p>I have linkButton see above on which I have called on c# function on Click, But if you pree some text in above textbox and press "Enter" it should automatically call function "btnSearchNow_Click". It is working fine in IE but not working in Firefox.</p>
|
[
{
"answer_id": 277779,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": false,
"text": "<p>To get rid of the trailing zeros, you should use the \"%g\" format:</p>\n\n<pre><code>float num = 1.33;\nprintf(\"%g\", num); //output: 1.33\n</code></pre>\n\n<p>After the question was clarified a bit, that suppressing zeros is not the only thing that was asked, but limiting the output to three decimal places was required as well. I think that can't be done with sprintf format strings alone. As <a href=\"https://stackoverflow.com/questions/277772/#277810\">Pax Diablo</a> pointed out, string manipulation would be required.</p>\n"
},
{
"answer_id": 277810,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": true,
"text": "<p>This can't be done with the normal <code>printf</code> format specifiers. The closest you could get would be:</p>\n\n<pre><code>printf(\"%.6g\", 359.013); // 359.013\nprintf(\"%.6g\", 359.01); // 359.01\n</code></pre>\n\n<p>but the \".6\" is the <em>total</em> numeric width so</p>\n\n<pre><code>printf(\"%.6g\", 3.01357); // 3.01357\n</code></pre>\n\n<p>breaks it.</p>\n\n<p>What you <em>can</em> do is to <code>sprintf(\"%.20g\")</code> the number to a string buffer then manipulate the string to only have N characters past the decimal point.</p>\n\n<p>Assuming your number is in the variable num, the following function will remove all but the first <code>N</code> decimals, then strip off the trailing zeros (and decimal point if they were all zeros).</p>\n\n<pre><code>char str[50];\nsprintf (str,\"%.20g\",num); // Make the number.\nmorphNumericString (str, 3);\n: :\nvoid morphNumericString (char *s, int n) {\n char *p;\n int count;\n\n p = strchr (s,'.'); // Find decimal point, if any.\n if (p != NULL) {\n count = n; // Adjust for more or less decimals.\n while (count >= 0) { // Maximum decimals allowed.\n count--;\n if (*p == '\\0') // If there's less than desired.\n break;\n p++; // Next character.\n }\n\n *p-- = '\\0'; // Truncate string.\n while (*p == '0') // Remove trailing zeros.\n *p-- = '\\0';\n\n if (*p == '.') { // If all decimals were zeros, remove \".\".\n *p = '\\0';\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If you're not happy with the truncation aspect (which would turn <code>0.12399</code> into <code>0.123</code> rather than rounding it to <code>0.124</code>), you can actually use the rounding facilities already provided by <code>printf</code>. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:</p>\n\n<pre><code>#include <stdio.h>\n\nvoid nDecimals (char *s, double d, int n) {\n int sz; double d2;\n\n // Allow for negative.\n\n d2 = (d >= 0) ? d : -d;\n sz = (d >= 0) ? 0 : 1;\n\n // Add one for each whole digit (0.xx special case).\n\n if (d2 < 1) sz++;\n while (d2 >= 1) { d2 /= 10.0; sz++; }\n\n // Adjust for decimal point and fractionals.\n\n sz += 1 + n;\n\n // Create format string then use it.\n\n sprintf (s, \"%*.*f\", sz, n, d);\n}\n\nint main (void) {\n char str[50];\n double num[] = { 40, 359.01335, -359.00999,\n 359.01, 3.01357, 0.111111111, 1.1223344 };\n for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {\n nDecimals (str, num[i], 3);\n printf (\"%30.20f -> %s\\n\", num[i], str);\n }\n return 0;\n}\n</code></pre>\n\n<p>The whole point of <code>nDecimals()</code> in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness <code>main()</code> shows this in action:</p>\n\n<pre><code> 40.00000000000000000000 -> 40.000\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.010\n 359.00999999999999090505 -> 359.010\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n</code></pre>\n\n<p>Once you have the correctly rounded value, you can once again pass that to <code>morphNumericString()</code> to remove trailing zeros by simply changing:</p>\n\n<pre><code>nDecimals (str, num[i], 3);\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>nDecimals (str, num[i], 3);\nmorphNumericString (str, 3);\n</code></pre>\n\n<p>(or calling <code>morphNumericString</code> at the end of <code>nDecimals</code> but, in that case, I'd probably just combine the two into one function), and you end up with:</p>\n\n<pre><code> 40.00000000000000000000 -> 40\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.01\n 359.00999999999999090505 -> 359.01\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n</code></pre>\n"
},
{
"answer_id": 278033,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my first try at an answer:</p>\n\n<pre>\nvoid\nxprintfloat(char *format, float f)\n{\n char s[50];\n char *p;\n\n sprintf(s, format, f);\n for(p=s; *p; ++p)\n if('.' == *p) {\n while(*++p);\n while('0'==*--p) *p = '\\0';\n }\n printf(\"%s\", s);\n}\n</pre>\n\n<p>Known bugs: Possible buffer overflow depending on format. If \".\" is present for other reason than %f wrong result might happen.</p>\n"
},
{
"answer_id": 2174887,
"author": "David Thornley",
"author_id": 196390,
"author_profile": "https://Stackoverflow.com/users/196390",
"pm_score": 0,
"selected": false,
"text": "<p>Slight variation on above:</p>\n\n<ol>\n<li>Eliminates period for case (10000.0).</li>\n<li>Breaks after first period is processed.</li>\n</ol>\n\n<p>Code here:</p>\n\n<pre><code>void EliminateTrailingFloatZeros(char *iValue)\n{\n char *p = 0;\n for(p=iValue; *p; ++p) {\n if('.' == *p) {\n while(*++p);\n while('0'==*--p) *p = '\\0';\n if(*p == '.') *p = '\\0';\n break;\n }\n }\n}\n</code></pre>\n\n<p>It still has potential for overflow, so be careful ;P</p>\n"
},
{
"answer_id": 3201560,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 2,
"selected": false,
"text": "<p>What about something like this (might have rounding errors and negative-value issues that need debugging, left as an exercise for the reader):</p>\n\n<pre><code>printf(\"%.0d%.4g\\n\", (int)f/10, f-((int)f-(int)f%10));\n</code></pre>\n\n<p>It's slightly programmatic but at least it doesn't make you do any string manipulation.</p>\n"
},
{
"answer_id": 4247516,
"author": "Juha",
"author_id": 311323,
"author_profile": "https://Stackoverflow.com/users/311323",
"pm_score": 4,
"selected": false,
"text": "<p>I like the answer of R. slightly tweaked:</p>\n\n<pre><code>float f = 1234.56789;\nprintf(\"%d.%.0f\", f, 1000*(f-(int)f));\n</code></pre>\n\n<p>'1000' determines the precision.</p>\n\n<p><em>Power to the 0.5 rounding.</em></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Ok, this answer was edited a few times and I lost track what I was thinking a few years back (and originally it did not fill all the criteria). So here is a new version (that fills all criteria and handles negative numbers correctly):</p>\n\n<pre><code>double f = 1234.05678900;\nchar s[100]; \nint decimals = 10;\n\nsprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\nprintf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n</code></pre>\n\n<p>And the test cases:</p>\n\n<pre><code>#import <stdio.h>\n#import <stdlib.h>\n#import <math.h>\n\nint main(void){\n\n double f = 1234.05678900;\n char s[100];\n int decimals;\n\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" 3 decimals: %d%s\\n\", (int)f, s+1);\n\n f = -f;\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 10: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 3: %d%s\\n\", (int)f, s+1);\n\n decimals = 2;\n f = 1.012;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" additional : %d%s\\n\", (int)f, s+1);\n\n return 0;\n}\n</code></pre>\n\n<p>And the output of the tests:</p>\n\n<pre><code> 10 decimals: 1234.056789\n 3 decimals: 1234.057\n negative 10: -1234.056789\n negative 3: -1234.057\n additional : 1.01\n</code></pre>\n\n<p>Now, all criteria are met:</p>\n\n<ul>\n<li>maximum number of decimals behind the zero is fixed</li>\n<li>trailing zeros are removed</li>\n<li>it does it mathematically right (right?)</li>\n<li>works (now) also when first decimal is zero </li>\n</ul>\n\n<p>Unfortunately this answer is a two-liner as <code>sprintf</code> does not return the string.</p>\n"
},
{
"answer_id": 15127324,
"author": "Iaijutsu",
"author_id": 2118088,
"author_profile": "https://Stackoverflow.com/users/2118088",
"pm_score": 1,
"selected": false,
"text": "<p>A simple solution but it gets the job done, assigns a known length and precision and avoids the chance of going exponential format (which is a risk when you use %g):</p>\n\n<pre><code>// Since we are only interested in 3 decimal places, this function\n// can avoid any potential miniscule floating point differences\n// which can return false when using \"==\"\nint DoubleEquals(double i, double j)\n{\n return (fabs(i - j) < 0.000001);\n}\n\nvoid PrintMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%.2f\", d);\n else\n printf(\"%.3f\", d);\n}\n</code></pre>\n\n<p>Add or remove \"elses\" if you want a max of 2 decimals; 4 decimals; etc.</p>\n\n<p>For example if you wanted 2 decimals:</p>\n\n<pre><code>void PrintMaxTwoDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else\n printf(\"%.2f\", d);\n}\n</code></pre>\n\n<p>If you want to specify the minimum width to keep fields aligned, increment as necessary, for example:</p>\n\n<pre><code>void PrintAlignedMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%7.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%9.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%10.2f\", d);\n else\n printf(\"%11.3f\", d);\n}\n</code></pre>\n\n<p>You could also convert that to a function where you pass the desired width of the field:</p>\n\n<pre><code>void PrintAlignedWidthMaxThreeDecimal(int w, double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%*.0f\", w-4, d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%*.1f\", w-2, d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%*.2f\", w-1, d);\n else\n printf(\"%*.3f\", w, d);\n}\n</code></pre>\n"
},
{
"answer_id": 15285177,
"author": "DaveR",
"author_id": 2146709,
"author_profile": "https://Stackoverflow.com/users/2146709",
"pm_score": 2,
"selected": false,
"text": "<p>I search the string (starting rightmost) for the first character in the range <code>1</code> to <code>9</code> (ASCII value <code>49</code>-<code>57</code>) then <code>null</code> (set to <code>0</code>) each char right of it - see below:</p>\n\n<pre><code>void stripTrailingZeros(void) { \n //This finds the index of the rightmost ASCII char[1-9] in array\n //All elements to the left of this are nulled (=0)\n int i = 20;\n unsigned char char1 = 0; //initialised to ensure entry to condition below\n\n while ((char1 > 57) || (char1 < 49)) {\n i--;\n char1 = sprintfBuffer[i];\n }\n\n //null chars left of i\n for (int j = i; j < 20; j++) {\n sprintfBuffer[i] = 0;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18993051,
"author": "TeamXlink",
"author_id": 2812967,
"author_profile": "https://Stackoverflow.com/users/2812967",
"pm_score": -1,
"selected": false,
"text": "<p>Your code rounds to three decimal places due to the \".3\" before the f</p>\n\n<pre><code>printf(\"%1.3f\", 359.01335);\nprintf(\"%1.3f\", 359.00999);\n</code></pre>\n\n<p>Thus if you the second line rounded to two decimal places, you should change it to this:</p>\n\n<pre><code>printf(\"%1.3f\", 359.01335);\nprintf(\"%1.2f\", 359.00999);\n</code></pre>\n\n<p>That code will output your desired results:</p>\n\n<pre><code>359.013\n359.01\n</code></pre>\n\n<p>*Note this is assuming you already have it printing on separate lines, if not then the following will prevent it from printing on the same line:</p>\n\n<pre><code>printf(\"%1.3f\\n\", 359.01335);\nprintf(\"%1.2f\\n\", 359.00999);\n</code></pre>\n\n<p>The Following program source code was my test for this answer</p>\n\n<pre><code>#include <cstdio>\n\nint main()\n{\n\n printf(\"%1.3f\\n\", 359.01335);\n printf(\"%1.2f\\n\", 359.00999);\n\n while (true){}\n\n return 0;\n\n}\n</code></pre>\n"
},
{
"answer_id": 25313464,
"author": "Jim Hunziker",
"author_id": 6160,
"author_profile": "https://Stackoverflow.com/users/6160",
"pm_score": 3,
"selected": false,
"text": "<p>Why not just do this?</p>\n\n<pre><code>double f = 359.01335;\nprintf(\"%g\", round(f * 1000.0) / 1000.0);\n</code></pre>\n"
},
{
"answer_id": 33448480,
"author": "magnusviri",
"author_id": 5509250,
"author_profile": "https://Stackoverflow.com/users/5509250",
"pm_score": 1,
"selected": false,
"text": "<p>I found problems in some of the solutions posted. I put this together based on answers above. It seems to work for me.</p>\n\n<pre><code>int doubleEquals(double i, double j) {\n return (fabs(i - j) < 0.000001);\n}\n\nvoid printTruncatedDouble(double dd, int max_len) {\n char str[50];\n int match = 0;\n for ( int ii = 0; ii < max_len; ii++ ) {\n if (doubleEquals(dd * pow(10,ii), floor(dd * pow(10,ii)))) {\n sprintf (str,\"%f\", round(dd*pow(10,ii))/pow(10,ii));\n match = 1;\n break;\n }\n }\n if ( match != 1 ) {\n sprintf (str,\"%f\", round(dd*pow(10,max_len))/pow(10,max_len));\n }\n char *pp;\n int count;\n pp = strchr (str,'.');\n if (pp != NULL) {\n count = max_len;\n while (count >= 0) {\n count--;\n if (*pp == '\\0')\n break;\n pp++;\n }\n *pp-- = '\\0';\n while (*pp == '0')\n *pp-- = '\\0';\n if (*pp == '.') {\n *pp = '\\0';\n }\n }\n printf (\"%s\\n\", str);\n}\n\nint main(int argc, char **argv)\n{\n printTruncatedDouble( -1.999, 2 ); // prints -2\n printTruncatedDouble( -1.006, 2 ); // prints -1.01\n printTruncatedDouble( -1.005, 2 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.005, 2 ); // prints 1 (should be 1.01?)\n printTruncatedDouble( 1.006, 2 ); // prints 1.01\n printTruncatedDouble( 1.999, 2 ); // prints 2\n printf(\"\\n\");\n printTruncatedDouble( -1.999, 3 ); // prints -1.999\n printTruncatedDouble( -1.001, 3 ); // prints -1.001\n printTruncatedDouble( -1.0005, 3 ); // prints -1.001 (shound be -1?)\n printTruncatedDouble( -1.0004, 3 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.0004, 3 ); // prints 1\n printTruncatedDouble( 1.0005, 3 ); // prints 1.001\n printTruncatedDouble( 1.001, 3 ); // prints 1.001\n printTruncatedDouble( 1.999, 3 ); // prints 1.999\n printf(\"\\n\");\n exit(0);\n}\n</code></pre>\n"
},
{
"answer_id": 36202854,
"author": "nwellnhof",
"author_id": 1956010,
"author_profile": "https://Stackoverflow.com/users/1956010",
"pm_score": 2,
"selected": false,
"text": "<p>Some of the highly voted solutions suggest the <code>%g</code> conversion specifier of <code>printf</code>. This is wrong because there are cases where <code>%g</code> will produce scientific notation. Other solutions use math to print the desired number of decimal digits.</p>\n\n<p>I think the easiest solution is to use <code>sprintf</code> with the <code>%f</code> conversion specifier and to manually remove trailing zeros and possibly a decimal point from the result. Here's a C99 solution:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nchar*\nformat_double(double d) {\n int size = snprintf(NULL, 0, \"%.3f\", d);\n char *str = malloc(size + 1);\n snprintf(str, size + 1, \"%.3f\", d);\n\n for (int i = size - 1, end = size; i >= 0; i--) {\n if (str[i] == '0') {\n if (end == i + 1) {\n end = i;\n }\n }\n else if (str[i] == '.') {\n if (end == i + 1) {\n end = i;\n }\n str[end] = '\\0';\n break;\n }\n }\n\n return str;\n}\n</code></pre>\n\n<p>Note that the characters used for digits and the decimal separator depend on the current locale. The code above assumes a C or US English locale.</p>\n"
},
{
"answer_id": 61432422,
"author": "Ankit Mishra",
"author_id": 13272795,
"author_profile": "https://Stackoverflow.com/users/13272795",
"pm_score": 0,
"selected": false,
"text": "<p>I would say you should use\n <code>printf(\"%.8g\",value);</code> </p>\n\n<p>If you use <code>\"%.6g\"</code> you will not get desired output for some numbers like.32.230210 it should print <code>32.23021</code> but it prints <code>32.2302</code></p>\n"
},
{
"answer_id": 63631055,
"author": "ravin.wang",
"author_id": 3968307,
"author_profile": "https://Stackoverflow.com/users/3968307",
"pm_score": 0,
"selected": false,
"text": "<p>Hit the same issue, double precision is 15 decimal, and float precision is 6 decimal, so I wrote to 2 functions for them separately</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <stdio.h>\n#include <math.h>\n#include <string>\n#include <string.h>\n\nstd::string doublecompactstring(double d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return "NAN";\n sprintf(buf, "%.15f", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nstd::string floatcompactstring(float d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return "NAN";\n sprintf(buf, "%.6f", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nint main(int argc, const char* argv[])\n{\n double a = 0.000000000000001;\n float b = 0.000001f;\n\n printf("a: %s\\n", doublecompactstring(a).c_str());\n printf("b: %s\\n", floatcompactstring(b).c_str());\n return 0;\n}\n</code></pre>\n<p>output is</p>\n<pre><code>a: 0.000000000000001\nb: 0.000001\n</code></pre>\n"
},
{
"answer_id": 67717966,
"author": "baah",
"author_id": 16046159,
"author_profile": "https://Stackoverflow.com/users/16046159",
"pm_score": 0,
"selected": false,
"text": "<p>I needed that and the first answer from paxdiablo does the trick. But I was not needing truncating and the version below is maybe slightly faster?\nStarting to search end of string (EOS) after the ".", only one placement of EOS.</p>\n<pre><code>//https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf\n//adapted from paxdiablo (removed truncating)\nchar StringForDouble[50];\nchar *PointerInString;\nvoid PrintDouble (double number) {\n sprintf(StringForDouble,"%.10f",number); // convert number to string\n PointerInString=strchr(&StringForDouble[0],'.'); // find decimal point, if any\n if(PointerInString!=NULL) {\n PointerInString=strchr(&PointerInString[0],'\\0'); // find end of string\n do{\n PointerInString--;\n } while(PointerInString[0]=='0'); // remove trailing zeros\n if (PointerInString[0]=='.') { // if all decimals were zeros, remove "."\n PointerInString[0]='\\0';\n } else {\n PointerInString[1]='\\0'; //otherwise put EOS after the first non zero char\n }\n }\n printf("%s",&StringForDouble[0]);\n}\n</code></pre>\n"
},
{
"answer_id": 70378558,
"author": "user1686153",
"author_id": 1686153,
"author_profile": "https://Stackoverflow.com/users/1686153",
"pm_score": 1,
"selected": false,
"text": "<p>My idea is to calculate the <em>required</em> precision that would not result in trailing zeroes for a given double value and pass it to the <code>"%1.*f"</code> format in printf().\nThis can even be done as one-liner:</p>\n<pre><code>int main() {\n double r=1234.56789;\n int precision=3;\n printf(L"%1.*f", prec(r, precision), r);\n}\n\nint prec(const double& r, int precision)\n{\n double rPos = (r < 0)? -r : r;\n double nkd = fmod(rPos, 1.0); // 0..0.99999999\n int i, ex10 = 1;\n for (i = 0; i < precision; ++i)\n ex10 *= 10;\n int nki = (int)(nkd * ex10 + 0.5);\n\n // "Eliminate" trailing zeroes\n int requiredPrecision = precision;\n for (; requiredPrecision && !(nki % 10); ) {\n --requiredPrecision;\n nki /= 10;\n }\n return requiredPrecision; \n}\n</code></pre>\n<p>And here is another <code>%g</code> solution. You should always provide a format precision that is "wide enough" (default is only 6) and round the value. I think this is a nice way to do it:</p>\n<pre><code>double round(const double &value, const double& rounding) {\n return rounding!=0 ? floor(value/rounding + 0.5)*rounding : value;\n}\n\nprintf("%.12g" round(val, 0.001)); // prints up to 3 relevant digits\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30394/"
] |
I want to call a c# function from my javascript function.
I have a link button in my ascx (please see the code below). The problem is that if you press enter in firefox is not working however it is working fine in internet explorer.
```
<li class="clearfix border_top">
<label for="title" class="first_column bold">Search For</label>
<div class="contactUs_details">
<input type="text" id="advanced_txtBox1" name="advanced_txtBox1" class="searchbox" runat="server" style="width:300px;" />
<asp:CheckBox ID="chkSearchBDJ" runat="server" Text="Search BDJ" CssClass="checkboxlistnoborder" />
</div>
</li>
<div class="img_SearchNow">
<asp:LinkButton ID="btnSearchNow" CausesValidation="true" runat="server" OnClick="btnSearchNow_Click"></asp:LinkButton>
</div>
```
I have linkButton see above on which I have called on c# function on Click, But if you pree some text in above textbox and press "Enter" it should automatically call function "btnSearchNow\_Click". It is working fine in IE but not working in Firefox.
|
This can't be done with the normal `printf` format specifiers. The closest you could get would be:
```
printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01); // 359.01
```
but the ".6" is the *total* numeric width so
```
printf("%.6g", 3.01357); // 3.01357
```
breaks it.
What you *can* do is to `sprintf("%.20g")` the number to a string buffer then manipulate the string to only have N characters past the decimal point.
Assuming your number is in the variable num, the following function will remove all but the first `N` decimals, then strip off the trailing zeros (and decimal point if they were all zeros).
```
char str[50];
sprintf (str,"%.20g",num); // Make the number.
morphNumericString (str, 3);
: :
void morphNumericString (char *s, int n) {
char *p;
int count;
p = strchr (s,'.'); // Find decimal point, if any.
if (p != NULL) {
count = n; // Adjust for more or less decimals.
while (count >= 0) { // Maximum decimals allowed.
count--;
if (*p == '\0') // If there's less than desired.
break;
p++; // Next character.
}
*p-- = '\0'; // Truncate string.
while (*p == '0') // Remove trailing zeros.
*p-- = '\0';
if (*p == '.') { // If all decimals were zeros, remove ".".
*p = '\0';
}
}
}
```
---
If you're not happy with the truncation aspect (which would turn `0.12399` into `0.123` rather than rounding it to `0.124`), you can actually use the rounding facilities already provided by `printf`. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:
```
#include <stdio.h>
void nDecimals (char *s, double d, int n) {
int sz; double d2;
// Allow for negative.
d2 = (d >= 0) ? d : -d;
sz = (d >= 0) ? 0 : 1;
// Add one for each whole digit (0.xx special case).
if (d2 < 1) sz++;
while (d2 >= 1) { d2 /= 10.0; sz++; }
// Adjust for decimal point and fractionals.
sz += 1 + n;
// Create format string then use it.
sprintf (s, "%*.*f", sz, n, d);
}
int main (void) {
char str[50];
double num[] = { 40, 359.01335, -359.00999,
359.01, 3.01357, 0.111111111, 1.1223344 };
for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
nDecimals (str, num[i], 3);
printf ("%30.20f -> %s\n", num[i], str);
}
return 0;
}
```
The whole point of `nDecimals()` in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness `main()` shows this in action:
```
40.00000000000000000000 -> 40.000
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
359.00999999999999090505 -> 359.010
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
```
Once you have the correctly rounded value, you can once again pass that to `morphNumericString()` to remove trailing zeros by simply changing:
```
nDecimals (str, num[i], 3);
```
into:
```
nDecimals (str, num[i], 3);
morphNumericString (str, 3);
```
(or calling `morphNumericString` at the end of `nDecimals` but, in that case, I'd probably just combine the two into one function), and you end up with:
```
40.00000000000000000000 -> 40
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
359.00999999999999090505 -> 359.01
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
```
|
277,793 |
<p>I'm using Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/Transformer.html" rel="nofollow noreferrer">Transformer</a> class to process an XML Document object.</p>
<p>This is the code that creates the Transformer:</p>
<pre><code>import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(source, result);
</code></pre>
<p>Currently, my output looks like this: <svg ... />. I'd like it to include the namespace of each element, as in <svg:svg ... /></p>
<p>How can I do that ?</p>
|
[
{
"answer_id": 277848,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "<p>The package description for <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/package-summary.html#package_description\" rel=\"nofollow noreferrer\">javax.xml.transform</a> has a section <em>Qualified Name Representation</em> which seems to imply that it is possible to get the namespace represented in both input and output.</p>\n\n<p>It isn't really clear to me what the result would look like, other than the namespace URI would be included.</p>\n\n<p>Give it a try - hopefully someone else will have more concrete experience.</p>\n"
},
{
"answer_id": 284615,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 3,
"selected": true,
"text": "<p>Note that <code><svg xmlns=\"SVGNS\" /></code> is the same as <code><svg:svg xmlns:svg=\"SVGNS\" /></code>. </p>\n\n<p>Did you check you called <code>setNamespaceAware(true)</code> on your <code>DocumentBuilderFactory</code> instance ?</p>\n"
},
{
"answer_id": 1056298,
"author": "Ted Johnson",
"author_id": 30231,
"author_profile": "https://Stackoverflow.com/users/30231",
"pm_score": 0,
"selected": false,
"text": "<p>What I found is that you need to put it on yourself as a prefix, not even use the namespaces.</p>\n\n<p>I used el.setAttribute(\"xmi:type\", type) for example rather than el.setAttributeNS(\"xsi\", \"type\", type); or el.setAttributeNS(\"<a href=\"http://www...../URI\" rel=\"nofollow noreferrer\">http://www...../URI</a>\", \"type\", type);\nI am finding that the NS method does not do quite what you thing it will do. Additionally it will still render it xmlns=\"...\" rather than using the prefix.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
I'm using Java's [Transformer](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/Transformer.html) class to process an XML Document object.
This is the code that creates the Transformer:
```
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(source, result);
```
Currently, my output looks like this: <svg ... />. I'd like it to include the namespace of each element, as in <svg:svg ... />
How can I do that ?
|
Note that `<svg xmlns="SVGNS" />` is the same as `<svg:svg xmlns:svg="SVGNS" />`.
Did you check you called `setNamespaceAware(true)` on your `DocumentBuilderFactory` instance ?
|
277,817 |
<h2>Scenario</h2>
<p>I have two wrappers around Microsoft Office, one for 2003 and one for 2007. Since having two versions of Microsoft Office running side by side is "not officially possible" nor recommended by Microsoft, we have two boxes, one with Office 2003 and the other with Office 2007. We compile the wrappers separately. The DLLs are included in our solution, each box has the <em>same</em> checkout but with either Office 2003 or 2007 "unloaded" so it doesn't attempt to compile that particular DLL. Failure to do that will throw errors on compilation due to the Office COM DLLs not available. </p>
<p>We use .NET 2.0 and Visual Studio 2008.</p>
<h2>Facts</h2>
<p>Since Microsoft mysteriously changed the Office 2003 API in 2007, renaming and changing some methods (<em>sigh</em>) thus making them not backwards compatible, we <em>need</em> the two wrappers.
We have each build machine with the solution and one Office DLL activated. E.g.: the machine with Office 2003 has the "Office 2007" DLL unloaded, therefore not compiling it. The other box is the same idea but the other way around. All this because we can't have 2 different Office in the same box for programming purposes. (you could technically have two Office together according to Microsoft) but <em>not</em> for programming and not without some issues.</p>
<h2>Problem</h2>
<p>When we change the Application Version (from 1.5.0.1 to 1.5.0.2 for example) we need to recompile the DLL to match the new version of the application, this is automatically done, because the Office wrapper is included in the solution. Since the wrappers are contained in the solution, those inherit the APP Version, but we have to do it twice and then "copy" the other DLL to the machine that creates the installer. (A Pain…)</p>
<h2>Question</h2>
<p>Is it possible to compile a DLL that will work with <em>any</em> version of the application, despite being "older"? I've read something about manifests but I have never had to interact with those. Any pointers will be appreciated.</p>
<p>The secret reason for this is that we haven't changed our wrappers in "ages" and neither did Microsoft with their ancient APIs, yet we are recompiling the DLL to match the app version on <em>every</em> release we make. I'd like to automate this process instead of having to rely on <em>two</em> machines.</p>
<p>I can't remove the DLL from the project (neither of them) because there are dependencies. </p>
<p>I could create a third "master wrapper" but haven't thought about it yet. </p>
<p>Any ideas? Anyone else with the same requirement? </p>
<h2>UPDATE</h2>
<p>Clarifying:</p>
<p>I have 1 solution with N projects. </p>
<p>"Application" + Office11Wrapper.dll + Office12Wrapper.dll.</p>
<p>Both "wrappers" use dependencies for application + other libraries in the solution (datalayer, businesslayer, framework, etc.)</p>
<p>Each wrapper has references for the respective Office package (2003 and 2007). </p>
<p>If I compile and don't have office 12 installed, I get errors from Office12Wrapper.dll not finding the Office 2007 libraries.
So what I have are two building machines, one with Office 2003, one with Office 2007. After a full SVN update + compile on each machine, we simply use office12.dll in the "installer" to have the wrapper compiled against the "same code, same version".</p>
<p>Note: The Office 2007 Build Machine, has the Wrapper for Office 2003 "unloaded" and viceversa.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 277835,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Just a thought - could you use TlbExp to create two interop assemblies (with different names and assemblies), and use an interface/factory to code against the two via your own interface? Once you have the interop dll, you don't need the COM dependency (except of course for testing etc).</p>\n\n<p>TlbImp has a /asmversion for the version, so it could be done as part of the build script; but I'm sure you even need this: just make sure that \"specific version\" is false in the reference (solution explorer)?</p>\n\n<p>Also - I know it doesn't help, but C# 4.0 with <code>dynamic</code> and/or \"No PIA\" might help here (in the future; maybe).</p>\n"
},
{
"answer_id": 277893,
"author": "NerdFury",
"author_id": 6146,
"author_profile": "https://Stackoverflow.com/users/6146",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure I am completely following everything you stated, but let me try:</p>\n\n<p>It sounds like you have one solution with 2(?) projects. One is the actual application, and the other is a wrapper for the Office API. Your application then has a project reference to your Office API wrapper. I've never programmed for office before, but it sounds like the programming APIs are a common component that you can only have one version of on a machine (ie. 2003 or 2007, not both). And maybe this is where the problem is, but because you have a project reference, the wrapper will be compiled first, copied to the bin directory of your application, where your application will be linked to that build of the wrapper. This will cause the manifest of the application to specifically request that version of the wrapper at run time.</p>\n\n<p>If you had the wrapper in a separate solution, and added a reference to the compiled library rather than the project, you would always link your application to that version of the wrapper and you could avoid the problem.</p>\n\n<p>Another possible choice is Assembly Binding Redirection. This is more advanced, and comes with it's own set of problems, but you can read about it <a href=\"http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Or similar to Marc's idea, you could extract an interface and pull some common objects into a Framework library, and code your application against the interface and common objects. Then at runtime use reflection to load the assembly and instantiate the wrapper you want.</p>\n\n<p>I think the key is to remove the project dependency if you can. It sounds like the wrapper is pretty stable and isn't changing, otherwise you wouldn't be asking to link to a previous version of it.</p>\n"
},
{
"answer_id": 277955,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 1,
"selected": false,
"text": "<p>Installing Office 2003 and 2007 side-by-side on the same machine <a href=\"http://support.microsoft.com/kb/928091\" rel=\"nofollow noreferrer\">is definitely possible</a> - we do it in our organisation even on end-user production workstations. </p>\n\n<p>In that linked article, Microsoft recommend that you don't do this for actual use. But in your case it appears to be just for a single build machine, i.e. you're not going to actually use either version of Office on that machine. In this context, I would try to see if you can make the side-by-side installation work.</p>\n\n<p>My assumption might be wrong, and you're attempting to do this for every developer's machine. In that case, you should ignore this answer :-)</p>\n"
},
{
"answer_id": 284462,
"author": "Eric Rosenberger",
"author_id": 36979,
"author_profile": "https://Stackoverflow.com/users/36979",
"pm_score": 5,
"selected": true,
"text": "<p>When the .NET assembly resolver is unable to find a referenced assembly at runtime (in this case, it cannot find the particular wrapper DLL version the application was linked against), its default behavior is to fail and essentially crash the application. However, this behavior can be overridden by hooking the AppDomain.AssemblyResolve event. This event is fired whenever a referenced assembly cannot be found, and it gives you the opportunity to substitute another assembly in place of the missing one (provided that they are compatible). So, for instance, you could substitute an older version of the wrapper DLL that you load yourself.</p>\n\n<p>The best way I've found to do this is to add a static constructor on the main class of the application that hooks the event, e.g.:</p>\n\n<pre><code>using System.Reflection;\n\nstatic Program()\n{\n AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)\n {\n AssemblyName requestedName = new AssemblyName(e.Name);\n\n if (requestedName.Name == \"Office11Wrapper\")\n {\n // Put code here to load whatever version of the assembly you actually have\n\n return Assembly.LoadFile(\"Office11Wrapper.DLL\");\n }\n else\n {\n return null;\n }\n }\n}\n</code></pre>\n\n<p>By putting this in a static constructor of the main application class, it is guaranteed to run before any code attempts to access anything in the wrapper DLL, ensuring that the hook is in place ahead of time.</p>\n\n<p>You can also use policy files to do version redirection, but that tends to be more complex.</p>\n"
},
{
"answer_id": 1002808,
"author": "Sean Aitken",
"author_id": 71524,
"author_profile": "https://Stackoverflow.com/users/71524",
"pm_score": 0,
"selected": false,
"text": "<p>Nice sleuthwork! I just threw together an implementation based on the concept presented above, and it works wonderfully:</p>\n\n<pre><code>static Assembly domain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n string partialName = args.Name.Substring(0, args.Name.IndexOf(','));\n return Assembly.Load(new AssemblyName(partialName));\n}\n</code></pre>\n\n<p>Of course there is room for enhancement, but this does the trick for me!</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
] |
Scenario
--------
I have two wrappers around Microsoft Office, one for 2003 and one for 2007. Since having two versions of Microsoft Office running side by side is "not officially possible" nor recommended by Microsoft, we have two boxes, one with Office 2003 and the other with Office 2007. We compile the wrappers separately. The DLLs are included in our solution, each box has the *same* checkout but with either Office 2003 or 2007 "unloaded" so it doesn't attempt to compile that particular DLL. Failure to do that will throw errors on compilation due to the Office COM DLLs not available.
We use .NET 2.0 and Visual Studio 2008.
Facts
-----
Since Microsoft mysteriously changed the Office 2003 API in 2007, renaming and changing some methods (*sigh*) thus making them not backwards compatible, we *need* the two wrappers.
We have each build machine with the solution and one Office DLL activated. E.g.: the machine with Office 2003 has the "Office 2007" DLL unloaded, therefore not compiling it. The other box is the same idea but the other way around. All this because we can't have 2 different Office in the same box for programming purposes. (you could technically have two Office together according to Microsoft) but *not* for programming and not without some issues.
Problem
-------
When we change the Application Version (from 1.5.0.1 to 1.5.0.2 for example) we need to recompile the DLL to match the new version of the application, this is automatically done, because the Office wrapper is included in the solution. Since the wrappers are contained in the solution, those inherit the APP Version, but we have to do it twice and then "copy" the other DLL to the machine that creates the installer. (A Pain…)
Question
--------
Is it possible to compile a DLL that will work with *any* version of the application, despite being "older"? I've read something about manifests but I have never had to interact with those. Any pointers will be appreciated.
The secret reason for this is that we haven't changed our wrappers in "ages" and neither did Microsoft with their ancient APIs, yet we are recompiling the DLL to match the app version on *every* release we make. I'd like to automate this process instead of having to rely on *two* machines.
I can't remove the DLL from the project (neither of them) because there are dependencies.
I could create a third "master wrapper" but haven't thought about it yet.
Any ideas? Anyone else with the same requirement?
UPDATE
------
Clarifying:
I have 1 solution with N projects.
"Application" + Office11Wrapper.dll + Office12Wrapper.dll.
Both "wrappers" use dependencies for application + other libraries in the solution (datalayer, businesslayer, framework, etc.)
Each wrapper has references for the respective Office package (2003 and 2007).
If I compile and don't have office 12 installed, I get errors from Office12Wrapper.dll not finding the Office 2007 libraries.
So what I have are two building machines, one with Office 2003, one with Office 2007. After a full SVN update + compile on each machine, we simply use office12.dll in the "installer" to have the wrapper compiled against the "same code, same version".
Note: The Office 2007 Build Machine, has the Wrapper for Office 2003 "unloaded" and viceversa.
Thanks in advance.
|
When the .NET assembly resolver is unable to find a referenced assembly at runtime (in this case, it cannot find the particular wrapper DLL version the application was linked against), its default behavior is to fail and essentially crash the application. However, this behavior can be overridden by hooking the AppDomain.AssemblyResolve event. This event is fired whenever a referenced assembly cannot be found, and it gives you the opportunity to substitute another assembly in place of the missing one (provided that they are compatible). So, for instance, you could substitute an older version of the wrapper DLL that you load yourself.
The best way I've found to do this is to add a static constructor on the main class of the application that hooks the event, e.g.:
```
using System.Reflection;
static Program()
{
AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
{
AssemblyName requestedName = new AssemblyName(e.Name);
if (requestedName.Name == "Office11Wrapper")
{
// Put code here to load whatever version of the assembly you actually have
return Assembly.LoadFile("Office11Wrapper.DLL");
}
else
{
return null;
}
}
}
```
By putting this in a static constructor of the main application class, it is guaranteed to run before any code attempts to access anything in the wrapper DLL, ensuring that the hook is in place ahead of time.
You can also use policy files to do version redirection, but that tends to be more complex.
|
277,857 |
<p>This code does not seem to compile, I just need to write something to a small log text file (a new row to end of file).</p>
<pre><code><%@ Import Namespace="System.IO" %>
void Page_Load( object sender, EventArgs e ){
FileSystem myFileSystem = new FileSystem();
myFileSystem.WriteAllText(logFile, hash, false);
</code></pre>
|
[
{
"answer_id": 277868,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 2,
"selected": false,
"text": "<p>FileSystem is a class from the VisualBasic namespace:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.aspx</a></p>\n\n<p>Have a look at the FileStream class in C#:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx</a></p>\n"
},
{
"answer_id": 277873,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>I can't see any class called FileSystem in <a href=\"http://msdn.microsoft.com/en-us/library/system.io.aspx\" rel=\"nofollow noreferrer\">the <code>System.IO</code> namespace</a>. Is this something new in .NET 4.0 which you're trying to use?</p>\n\n<p>Note that the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.aspx\" rel=\"nofollow noreferrer\"><code>File</code></a> class has a <em>static</em> method called <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx\" rel=\"nofollow noreferrer\"><code>WriteAllText</code></a>. Is that what you meant?</p>\n\n<p>EDIT: To append to a file instead, use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.appendalltext.aspx\" rel=\"nofollow noreferrer\"><code>File.AppendAllText</code></a>.</p>\n"
},
{
"answer_id": 277874,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 2,
"selected": false,
"text": "<p>FileSystem is in Microsoft.VisualBasic.File.IO. You'd have to reference that.</p>\n\n<p>Although you probably don't really want FileSystem at all. You probably want System.IO.File</p>\n"
},
{
"answer_id": 277905,
"author": "Tom",
"author_id": 20979,
"author_profile": "https://Stackoverflow.com/users/20979",
"pm_score": 0,
"selected": false,
"text": "<p>This one seem to compile:</p>\n\n<pre><code>File myFileSystem = new File();\nmyFileSystem.AppendAllText(logFile, hash, false);\n</code></pre>\n"
},
{
"answer_id": 277962,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 1,
"selected": false,
"text": "<p>Without a doubt log4net! <a href=\"http://logging.apache.org/log4net/index.html\" rel=\"nofollow noreferrer\">http://logging.apache.org/log4net/index.html</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20979/"
] |
This code does not seem to compile, I just need to write something to a small log text file (a new row to end of file).
```
<%@ Import Namespace="System.IO" %>
void Page_Load( object sender, EventArgs e ){
FileSystem myFileSystem = new FileSystem();
myFileSystem.WriteAllText(logFile, hash, false);
```
|
I can't see any class called FileSystem in [the `System.IO` namespace](http://msdn.microsoft.com/en-us/library/system.io.aspx). Is this something new in .NET 4.0 which you're trying to use?
Note that the [`File`](http://msdn.microsoft.com/en-us/library/system.io.file.aspx) class has a *static* method called [`WriteAllText`](http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx). Is that what you meant?
EDIT: To append to a file instead, use [`File.AppendAllText`](http://msdn.microsoft.com/en-us/library/system.io.file.appendalltext.aspx).
|
277,869 |
<p>In a piece of C# that I am writing at the moment I need to handle several methods with the same signature in the same way. Also there might be more of these methods in the future. Instead of repeating the same kind of logic over and over I thought up the following:</p>
<pre><code>private delegate bool cleanStep(BuildData bd, out String strFailure);
List<cleanStep> steps = new List<cleanStep>();
steps.Add(WriteReadme);
steps.Add(DeleteFiles);
steps.Add(TFSHelper.DeleteLabel);
steps.Add(TFSHelper.DeleteBuild);
List<cleanStep>.Enumerator enumerator = steps.GetEnumerator();
bool result = true;
while (result && enumerator.MoveNext())
{
result = enumerator.Current.Invoke(build, out strFailure);
if (!result)
{
logger.Write(LogTypes.Error, strFailure);
}
}
</code></pre>
<p>I think this has some nice features but it also feels a bit over enginered and obfuscating.</p>
<p><strong>Can you thank of a better a way of doing this ?</strong></p>
<p>btw: </p>
<ul>
<li>it doesn't needs to be transactional. </li>
<li>strFailure does not hide exceptions it wraps them
completely when necessary</li>
</ul>
<p>Thanks. </p>
|
[
{
"answer_id": 277882,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Why not use a foreach loop and just break? (I've renamed <code>cleanStep</code> to <code>CleanStep</code> here for conventionality - I suggest you do the same.)</p>\n\n<pre><code>foreach(CleanStep step in steps)\n{\n string failureText;\n if (!step(build, out failureText))\n {\n logger.Write(LogTypes.Error, strFailure);\n break;\n }\n}\n</code></pre>\n\n<p>Note that this also obeys the contract of <code>IEnumerator<T></code> where your current code doesn't - <code>foreach</code> automatically calls <code>Dispose</code>, and <code>IEnumerator<T></code> implements <code>IDisposable</code>. It won't be an issue in this case, but with iterator blocks, <a href=\"http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx\" rel=\"nofollow noreferrer\">disposal is used to execute <code>finally</code> blocks</a>.</p>\n"
},
{
"answer_id": 277885,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 2,
"selected": false,
"text": "<p>Your solution is both straight foward and easy to understand. I can see no reason to do it another way :)</p>\n\n<p>The only thing I'd suggest is to replace your iterator with a foreach loop and break on an error.</p>\n"
},
{
"answer_id": 277890,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>Re obfuscated - well <code>foreach</code> with break might be clearer (plus it'll <code>Dispose()</code> the enumerator, which you aren't doing).</p>\n\n<p>Actually, a \"params cleanStep[] targets\" might help:</p>\n\n<pre><code>static bool RunTargets(params cleanStep[] targets)\n{\n // detail as per Jon's post\n}\n</code></pre>\n\n<p>then you can call:</p>\n\n<pre><code>bool foo = RunTargets(WriteReadme, DeleteFiles,\n TFSHelper.DeleteLabel, TFSHelper.DeleteBuild);\n</code></pre>\n"
},
{
"answer_id": 278001,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 0,
"selected": false,
"text": "<p>I would return an Exception object instead of a string. Since exceptions often have a global policy, I would write some Exception extensions. Now you get:</p>\n\n<pre><code>static Exception Run( this IEnumerable<Step> steps) {\n return \n steps\n .FirstOrDefault( (step) => step( build ) != null )\n .LogIfFailure(); //or .ThrowIfFailure()\n}\n</code></pre>\n\n<p>The extensions:</p>\n\n<pre><code>public static class ExceptionExtensions {\n private static logger = new Logger();\n\n public static Exception LogIfFailure( this Exception e ) {\n if( e != null )\n logger.Write( e.Message );\n return e;\n }\n public static Exception ShowDialogIfFailure( this Exception e ) {\n if( e != null )\n MessageBox.Show( e.Message );\n return e;\n }\n public static void ThrowIfFailure( this Exception e ) {\n if( e != null )\n Throw( e );\n }\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6434/"
] |
In a piece of C# that I am writing at the moment I need to handle several methods with the same signature in the same way. Also there might be more of these methods in the future. Instead of repeating the same kind of logic over and over I thought up the following:
```
private delegate bool cleanStep(BuildData bd, out String strFailure);
List<cleanStep> steps = new List<cleanStep>();
steps.Add(WriteReadme);
steps.Add(DeleteFiles);
steps.Add(TFSHelper.DeleteLabel);
steps.Add(TFSHelper.DeleteBuild);
List<cleanStep>.Enumerator enumerator = steps.GetEnumerator();
bool result = true;
while (result && enumerator.MoveNext())
{
result = enumerator.Current.Invoke(build, out strFailure);
if (!result)
{
logger.Write(LogTypes.Error, strFailure);
}
}
```
I think this has some nice features but it also feels a bit over enginered and obfuscating.
**Can you thank of a better a way of doing this ?**
btw:
* it doesn't needs to be transactional.
* strFailure does not hide exceptions it wraps them
completely when necessary
Thanks.
|
Why not use a foreach loop and just break? (I've renamed `cleanStep` to `CleanStep` here for conventionality - I suggest you do the same.)
```
foreach(CleanStep step in steps)
{
string failureText;
if (!step(build, out failureText))
{
logger.Write(LogTypes.Error, strFailure);
break;
}
}
```
Note that this also obeys the contract of `IEnumerator<T>` where your current code doesn't - `foreach` automatically calls `Dispose`, and `IEnumerator<T>` implements `IDisposable`. It won't be an issue in this case, but with iterator blocks, [disposal is used to execute `finally` blocks](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx).
|
277,881 |
<p>I have a WCF service, hosted in IIS 7.0 that needs to run database queries. In order to get the right permissions to do this I am impersonating within the service as follows:</p>
<h3>Code</h3>
<pre><code>[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
public void MyOperation(int arg)
</code></pre>
<h3>Configuration</h3>
<pre><code><behavior name="ReceivingServiceBehavior">
<!-- Other behaviors -->
<serviceAuthorization impersonateCallerForAllOperations="true" />
</behavior>
</code></pre>
<p>When I try to connect and run my query I get the following:</p>
<pre>
Exception - System.IO.FileLoadException: Could not load file or
assembly 'System.Transactions, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. Either a
required impersonation level was not provided, or the provided
impersonation level is invalid. (Exception from HRESULT: 0x80070542)
File name: 'System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' ---> System.Runtime.InteropServices.COMException (0x80070542): Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542)
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Fourth.GHS.MessageRelay.RegistrationDBStorage.FindRegistration(SystemKey key)
</pre>
|
[
{
"answer_id": 277918,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>Hmmm... I don't know. However, you could force the dll to load early on. Since you are using IIS, this would presumably be in your global.asax - something like creating and throwing away a TransactionScope should do the job...</p>\n"
},
{
"answer_id": 278155,
"author": "Kwal",
"author_id": 35220,
"author_profile": "https://Stackoverflow.com/users/35220",
"pm_score": 3,
"selected": true,
"text": "<p>If you want the SQL queries to be executed as the impersonated identity, you may actually need to enable delegation to your SQL server. Check out this article for more info:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms730088.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms730088.aspx</a></p>\n"
},
{
"answer_id": 281022,
"author": "Simon",
"author_id": 994,
"author_profile": "https://Stackoverflow.com/users/994",
"pm_score": 0,
"selected": false,
"text": "<p>Having played around with this some more, the easiest solution for IIS hosted services is to run your Application Pool with the identity of a domain user that has the requisite permissions. There are probably issues with this in terms of security but for our purposes it's good enough. We can restrict the permissions given to that user but everything works without having to get into Kerberos, impersonation, delegation and the mysteries of AD.</p>\n"
},
{
"answer_id": 320917,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 3,
"selected": false,
"text": "<p>Does your WCF client set the required \"allowed impersonation level\":</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.serviceModel>\n\n <!-- .... -->\n\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"ImpersonationBehavior\">\n <clientCredentials>\n <windows allowedImpersonationLevel=\"Impersonation\" />\n </clientCredentials>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n </system.serviceModel>\n</configuration>\n</code></pre>\n\n<p>By default this is set to <strong>Identification</strong> if nothing is specified explicitly. Check out <a href=\"http://agilior.pt/blogs/bruno.camara/archive/2008/02/19/3721.aspx\" rel=\"noreferrer\">this blog post</a> for more info.</p>\n"
},
{
"answer_id": 424044,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>thank you guys,\nI solved it by reading the XML under the declaration of:</p>\n\n<pre><code>[OperationBehavior(Impersonation:=ImpersonationOption.Required)]\n</code></pre>\n\n<p>it worked only when I read the XML directly from the WCFService Class.</p>\n"
},
{
"answer_id": 1070380,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you huseyint. I've been fighting this one for the past day and a half. Here's some stuff that would have saved me a ton of time. So hopefully it will save someone else some time. \nI was having problems with the SQLConnection and impersonation throwing a registry access is denied using transport security. I tried even using transportwithmessagecredential. Inside of procmon I was getting \"Bad Impersonation\".\nMy config is\nIIS 7, virtual dir only has windows authentication enabled and I disabled kernel mode authentication. Basic settings I set it to use pass through authentication.</p>\n\n<p>Service Config -</p>\n\n<pre><code> <system.serviceModel>\n <serviceHostingEnvironment aspNetCompatibilityEnabled=\"false\" />\n <services>\n <service behaviorConfiguration=\"SymitarService.ScheduleServiceBehavior\" name=\"SymitarService.ScheduleService\">\n <endpoint address=\"\" binding=\"wsHttpBinding\" bindingConfiguration=\"wsSecure\" contract=\"SymitarService.IScheduleService\">\n <identity>\n <dns value=\"localhost\" /> \n </identity>\n </endpoint>\n <endpoint address=\"mex\" binding=\"wsHttpBinding\" bindingConfiguration=\"wsSecure\" contract=\"IMetadataExchange\" />\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"SymitarService.UserDirectoryBehavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"true\" />\n <serviceAuthorization impersonateCallerForAllOperations=\"true\" />\n </behavior>\n <behavior name=\"SymitarService.ScheduleServiceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"true\" />\n <serviceAuthorization impersonateCallerForAllOperations=\"true\" />\n </behavior>\n </serviceBehaviors>\n </behaviors>\n <bindings>\n <netTcpBinding>\n <binding name=\"tcpSecure\" portSharingEnabled=\"true\" />\n </netTcpBinding>\n <wsHttpBinding>\n <binding name=\"wsSecure\" allowCookies=\"true\">\n <security mode=\"Transport\">\n <transport clientCredentialType=\"Windows\" proxyCredentialType=\"Windows\" />\n <message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" />\n </security>\n </binding>\n </wsHttpBinding>\n <mexTcpBinding>\n <binding name=\"mexSecure\" />\n </mexTcpBinding>\n </bindings>\n </system.serviceModel>\n</code></pre>\n\n<p>and the client</p>\n\n<pre><code><system.serviceModel>\n <bindings>\n <wsHttpBinding>\n <binding name=\"WSHttpBinding_IScheduleService\" closeTimeout=\"01:00:00\" openTimeout=\"01:00:00\" receiveTimeout=\"01:00:00\" sendTimeout=\"01:00:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"65536\" useDefaultWebProxy=\"true\" allowCookies=\"true\">\n <readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" />\n <reliableSession ordered=\"true\" inactivityTimeout=\"00:20:00\" enabled=\"false\" />\n <security mode=\"Transport\">\n <transport clientCredentialType=\"Windows\" proxyCredentialType=\"Windows\" realm=\"\" />\n <message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" establishSecurityContext=\"true\" />\n </security>\n </binding>\n </wsHttpBinding>\n </bindings>\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"ImpersonationBehavior\">\n <clientCredentials>\n <windows allowedImpersonationLevel=\"Impersonation\" allowNtlm=\"true\"/>\n </clientCredentials>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n <client>\n <endpoint address=\"https://server:444/SymitarService/ScheduleService.svc\" \n binding=\"wsHttpBinding\" \n bindingConfiguration=\"WSHttpBinding_IScheduleService\" \n contract=\"Symitar.ScheduleService.IScheduleService\" \n name=\"WSHttpBinding_IScheduleService\"\n behaviorConfiguration=\"ImpersonationBehavior\"\n >\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n </client>\n </system.serviceModel>\n</code></pre>\n"
},
{
"answer_id": 29347482,
"author": "Abdelrahman ELGAMAL",
"author_id": 436075,
"author_profile": "https://Stackoverflow.com/users/436075",
"pm_score": 0,
"selected": false,
"text": "<p>This one solved my problem.</p>\n\n<p>Right click on Visual studio (whichever version you use)\nProperties\nSelect compatibility tab\nFill the checkbox which says \"Run this program as administrator\"\nOpen the project from the file location\nRun the application</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994/"
] |
I have a WCF service, hosted in IIS 7.0 that needs to run database queries. In order to get the right permissions to do this I am impersonating within the service as follows:
### Code
```
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
public void MyOperation(int arg)
```
### Configuration
```
<behavior name="ReceivingServiceBehavior">
<!-- Other behaviors -->
<serviceAuthorization impersonateCallerForAllOperations="true" />
</behavior>
```
When I try to connect and run my query I get the following:
```
Exception - System.IO.FileLoadException: Could not load file or
assembly 'System.Transactions, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. Either a
required impersonation level was not provided, or the provided
impersonation level is invalid. (Exception from HRESULT: 0x80070542)
File name: 'System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' ---> System.Runtime.InteropServices.COMException (0x80070542): Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542)
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Fourth.GHS.MessageRelay.RegistrationDBStorage.FindRegistration(SystemKey key)
```
|
If you want the SQL queries to be executed as the impersonated identity, you may actually need to enable delegation to your SQL server. Check out this article for more info:
<http://msdn.microsoft.com/en-us/library/ms730088.aspx>
|
277,884 |
<p>I need to check the <code>RequestType</code> of an <code>HttpRequest</code> in ASP.NET (or <code>WebRequest.Method</code>). I know that I can just use the string values "<code>POST</code>" or "<code>GET</code>" for the request type, but I could have sworn there was a constant somewhere in some class in .NET that contained the values.</p>
<p>Out of curiosity I was wondering if anyone knew what class these string constants for <code>GET</code> and <code>POST</code> were in. I've tried searching online but I've had no luck, so I thought I'd ask here.</p>
|
[
{
"answer_id": 277908,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 8,
"selected": true,
"text": "<pre><code>System.Net.WebRequestMethods.Http\n .Connect = \"CONNECT\"\n .Get = \"GET\"\n .Head = \"HEAD\"\n .MkCol = \"MKCOL\"\n .Post = \"POST\"\n .Put = \"PUT\"\n</code></pre>\n\n<p>Ultimately, though; since <code>const</code> expressions are burned into the caller, this is identical to using \"GET\" etc, just without the risk of a typo.</p>\n"
},
{
"answer_id": 277969,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>In ASP.NET MVC they're in <strong>System.Web.Mvc.HttpVerbs</strong>. But all methods that take one of these enum values also has a text override, as there is no complete set of HTTP verbs, only a set of currently defined values (see <a href=\"http://www.ietf.org/rfc/rfc2518.txt\" rel=\"noreferrer\">here</a> and <a href=\"http://www.ietf.org/rfc/rfc2616.txt\" rel=\"noreferrer\">here</a> and <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html\" rel=\"noreferrer\">here</a>). </p>\n\n<p>You can't create an enumeration that covers all verbs, as there is the possibility that verbs can be added, and <a href=\"http://blogs.msdn.com/brada/archive/2004/01/05/50987.aspx\" rel=\"noreferrer\">enumerations have versioning issues</a> that make this impractical.</p>\n"
},
{
"answer_id": 30209587,
"author": "xmedeko",
"author_id": 254109,
"author_profile": "https://Stackoverflow.com/users/254109",
"pm_score": 6,
"selected": false,
"text": "<p>Also exists <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpmethod\" rel=\"noreferrer\"><code>System.Net.Http.HttpMethod</code></a> which can serve instead of enum. You can compare them <code>aMethod == HttpMethod.Get</code>, etc. To get string method name call e.g. <code>HttpMethod.Get.Method</code>. </p>\n"
},
{
"answer_id": 54843751,
"author": "Felix K.",
"author_id": 2477619,
"author_profile": "https://Stackoverflow.com/users/2477619",
"pm_score": 4,
"selected": false,
"text": "<p>In <strong>ASP.NET Core</strong> you will find a collection of http method strings in the <a href=\"https://github.com/dotnet/aspnetcore/blob/v5.0.4/src/Http/Http.Abstractions/src/HttpMethods.cs\" rel=\"noreferrer\">HttpMethods.cs</a> class under the <code>Microsoft.AspNetCore.Http</code> namespace.</p>\n<p>This class also offers boolean helpers such as <code>IsGet()</code> or <code>IsPost()</code> for better semantics.</p>\n<p>Please note that these strings are exposed as <code>public static readonly string</code> and not as <code>constants</code>.</p>\n<p><strong>UPDATE 2020-05-17:</strong> <code>GetCanonicalizedValue(string method)</code> was added to the <code>HttpMethods.cs</code> class in ASP.NET Core v5, which returns the static instance equivalent to the provided string method name.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
I need to check the `RequestType` of an `HttpRequest` in ASP.NET (or `WebRequest.Method`). I know that I can just use the string values "`POST`" or "`GET`" for the request type, but I could have sworn there was a constant somewhere in some class in .NET that contained the values.
Out of curiosity I was wondering if anyone knew what class these string constants for `GET` and `POST` were in. I've tried searching online but I've had no luck, so I thought I'd ask here.
|
```
System.Net.WebRequestMethods.Http
.Connect = "CONNECT"
.Get = "GET"
.Head = "HEAD"
.MkCol = "MKCOL"
.Post = "POST"
.Put = "PUT"
```
Ultimately, though; since `const` expressions are burned into the caller, this is identical to using "GET" etc, just without the risk of a typo.
|
277,899 |
<p>Is it alright to do this?</p>
<pre><code>$author = strtolower($_SESSION['valid_username']);
</code></pre>
<p>I want to enter all authors into the table as lower case.</p>
|
[
{
"answer_id": 277910,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, that's fine as long as <code>$_SESSION['valid_username']</code> is set, otherwise you'll get a notice (if your error reporting is set that low).</p>\n\n<p>You can check if it exists with <code>if (isset($_SESSION['valid_username']))</code></p>\n"
},
{
"answer_id": 277911,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<p>yes.</p>\n\n<pre><code>$_SESSION['valid_username']\n</code></pre>\n\n<p>is a session variable which evaluates to a string so passing it as a parameter to the strtolower function is not a problem.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
Is it alright to do this?
```
$author = strtolower($_SESSION['valid_username']);
```
I want to enter all authors into the table as lower case.
|
Yes, that's fine as long as `$_SESSION['valid_username']` is set, otherwise you'll get a notice (if your error reporting is set that low).
You can check if it exists with `if (isset($_SESSION['valid_username']))`
|
277,900 |
<p>I want to do something like:</p>
<pre><code>exec sproc1 and sproc2 at the same time
when they are both finished exec sproc3
</code></pre>
<p>I can do this in dts.
Is there a way to do it in transact sql?
Or is there a way to do it with a batch script (eg vbs or powershell)?</p>
|
[
{
"answer_id": 277966,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "<p>You could create a CLR Stored Procedure that (using C#) would call the first two on their own threads, and then block until both are complete... then run the third one.</p>\n\n<p>Are you able to use CLR sprocs in your situation? If so, I'll edit this answer to have more detail.</p>\n"
},
{
"answer_id": 278538,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 1,
"selected": false,
"text": "<p>Do you absolutely need both SPs to be executed in parallel?</p>\n\n<p>With simple CRUD statements within a single SP, I've found SQL S. does a very good job of determining which of them can be run in parallel and do so. I've never seen SQL S. run 2 SPs in parallel if both are called sequentially from a T-SQL statement, don't even know if it's even possible.</p>\n\n<p>Now then, do the DTS really execute them in parallel? It could be it simply executes them sequentially, then calls the 3rd SP after the last finishes successfully.</p>\n\n<p>If it really runs them in parallel, probably you should stick with DTS, but then I'd like to know what it does if I have a DTS package call, say, 10 heavy duty SPs in parallel... I may have to do some testings to learn that myself :D</p>\n"
},
{
"answer_id": 473941,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>You can use SSIS. The benefits of this are that the package can be stored in the SQL Server and easily scheduled there.</p>\n\n<p>From PowerShell or just about any external scripting language, you can use the SQL command line osql or sqlcmd. This technique can also be used to schedule it on the SQL Server by shelling out using xp_cmdshell also.</p>\n"
},
{
"answer_id": 628621,
"author": "Grokling",
"author_id": 75918,
"author_profile": "https://Stackoverflow.com/users/75918",
"pm_score": 3,
"selected": true,
"text": "<p>sp _ start _ job</p>\n\n<p>I'm doing a similar thing at the moment, and the only way I've found to avoid using SSIS or some external shell is to split my load routine into 'threads' manually, and then fire a single master sqlagent job which in turn executes as many sp _ start _ job's as I have threads. From that point, they all run autonomously.</p>\n\n<p>It's not exactly what we're looking for, but the result is the same. If you test the job status for the sub jobs, you can implement your conditional start of sproc 3 as well.</p>\n\n<p>What's the point in 8 cores if we can't use them all at once?</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36189/"
] |
I want to do something like:
```
exec sproc1 and sproc2 at the same time
when they are both finished exec sproc3
```
I can do this in dts.
Is there a way to do it in transact sql?
Or is there a way to do it with a batch script (eg vbs or powershell)?
|
sp \_ start \_ job
I'm doing a similar thing at the moment, and the only way I've found to avoid using SSIS or some external shell is to split my load routine into 'threads' manually, and then fire a single master sqlagent job which in turn executes as many sp \_ start \_ job's as I have threads. From that point, they all run autonomously.
It's not exactly what we're looking for, but the result is the same. If you test the job status for the sub jobs, you can implement your conditional start of sproc 3 as well.
What's the point in 8 cores if we can't use them all at once?
|
277,914 |
<p>I've got a PHPUnit mock object that returns <code>'return value'</code> no matter what its arguments:</p>
<pre><code>// From inside a test...
$mock = $this->getMock('myObject', 'methodToMock');
$mock->expects($this->any))
->method('methodToMock')
->will($this->returnValue('return value'));
</code></pre>
<p>What I want to be able to do is return a different value based on the arguments passed to the mock method. I've tried something like:</p>
<pre><code>$mock = $this->getMock('myObject', 'methodToMock');
// methodToMock('one')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('one'))
->will($this->returnValue('method called with argument "one"'));
// methodToMock('two')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('two'))
->will($this->returnValue('method called with argument "two"'));
</code></pre>
<p>But this causes PHPUnit to complain if the mock isn't called with the argument <code>'two'</code>, so I assume that the definition of <code>methodToMock('two')</code> overwrites the definition of the first.</p>
<p>So my question is: Is there any way to get a PHPUnit mock object to return a different value based on its arguments? And if so, how?</p>
|
[
{
"answer_id": 277975,
"author": "eddy147",
"author_id": 30759,
"author_profile": "https://Stackoverflow.com/users/30759",
"pm_score": 0,
"selected": false,
"text": "<p>Do you mean something like this?</p>\n\n<pre><code>public function TestSomeCondition($condition){\n $mockObj = $this->getMockObject();\n $mockObj->setReturnValue('yourMethod',$condition);\n}\n</code></pre>\n"
},
{
"answer_id": 278099,
"author": "JamShady",
"author_id": 11905,
"author_profile": "https://Stackoverflow.com/users/11905",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem which I couldn't work out as well (there's surprisingly little information about for PHPUnit). In my case, I just made each test separate test - known input and known output. I realised that I didn't need to make a jack-of-all-trades mock object, I only needed a specific one for a specific test, and thus I separated the tests out and can test individual aspects of my code as a separate unit. I'm not sure if this might be applicable to you or not, but that's down to what you need to test.</p>\n"
},
{
"answer_id": 292423,
"author": "Howard Sandford",
"author_id": 37904,
"author_profile": "https://Stackoverflow.com/users/37904",
"pm_score": 8,
"selected": true,
"text": "<p>Use a callback. e.g. (straight from PHPUnit documentation):</p>\n\n<pre><code><?php\nclass StubTest extends PHPUnit_Framework_TestCase\n{\n public function testReturnCallbackStub()\n {\n $stub = $this->getMock(\n 'SomeClass', array('doSomething')\n );\n\n $stub->expects($this->any())\n ->method('doSomething')\n ->will($this->returnCallback('callback'));\n\n // $stub->doSomething() returns callback(...)\n }\n}\n\nfunction callback() {\n $args = func_get_args();\n // ...\n}\n?>\n</code></pre>\n\n<p>Do whatever processing you want in the callback() and return the result based on your $args as appropriate.</p>\n"
},
{
"answer_id": 1514902,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Try :</p>\n\n<pre><code>->with($this->equalTo('one'),$this->equalTo('two))->will($this->returnValue('return value'));\n</code></pre>\n"
},
{
"answer_id": 2055436,
"author": "Adam",
"author_id": 249627,
"author_profile": "https://Stackoverflow.com/users/249627",
"pm_score": 6,
"selected": false,
"text": "<p>I had a similar problem (although slightly different... I didn't need different return value based on arguments, but had to test to ensure 2 sets of arguments were being passed to the same function). I stumbled upon using something like this:</p>\n\n<pre><code>$mock = $this->getMock();\n$mock->expects($this->at(0))\n ->method('foo')\n ->with(...)\n ->will($this->returnValue(...));\n\n$mock->expects($this->at(1))\n ->method('foo')\n ->with(...)\n ->will($this->returnValue(...));\n</code></pre>\n\n<p>It's not perfect, since it requires that the order of the 2 calls to foo() is known, but in practice this probably isn't <em>too</em> bad.</p>\n"
},
{
"answer_id": 4664060,
"author": "Francis Lewis",
"author_id": 572014,
"author_profile": "https://Stackoverflow.com/users/572014",
"pm_score": 5,
"selected": false,
"text": "<p>You would probably want to do a callback in a OOP fashion:</p>\n<pre><code><?php\nclass StubTest extends PHPUnit_Framework_TestCase\n{\n public function testReturnAction()\n {\n $object = $this->getMock('class_name', array('method_to_mock'));\n $object->expects($this->any())\n ->method('method_to_mock')\n ->will($this->returnCallback(array($this, 'returnTestDataCallback')));\n\n $object->returnAction('param1');\n // assert what param1 should return here\n\n $object->returnAction('param2');\n // assert what param2 should return here\n }\n \n public function returnTestDataCallback()\n {\n $args = func_get_args();\n\n // process $args[0] here and return the data you want to mock\n return 'The parameter was ' . $args[0];\n }\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 11737021,
"author": "Nikola Ivancevic",
"author_id": 1162508,
"author_profile": "https://Stackoverflow.com/users/1162508",
"pm_score": 7,
"selected": false,
"text": "<p>From the latest phpUnit docs: \"Sometimes a stubbed method should return different values depending on a predefined list of arguments. You can use <a href=\"https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.stubs.examples.StubTest5.php\" rel=\"noreferrer\">returnValueMap()</a> to create a map that associates arguments with corresponding return values.\"</p>\n\n<pre><code>$mock->expects($this->any())\n ->method('getConfigValue')\n ->will(\n $this->returnValueMap(\n array(\n array('firstparam', 'secondparam', 'retval'),\n array('modes', 'foo', array('Array', 'of', 'modes'))\n )\n )\n );\n</code></pre>\n"
},
{
"answer_id": 18075785,
"author": "Gabriel Gcia Fdez",
"author_id": 1079109,
"author_profile": "https://Stackoverflow.com/users/1079109",
"pm_score": 2,
"selected": false,
"text": "<p>You also can return the argument as follows:</p>\n\n<pre><code>$stub = $this->getMock(\n 'SomeClass', array('doSomething')\n);\n\n$stub->expects($this->any())\n ->method('doSomething')\n ->will($this->returnArgument(0));\n</code></pre>\n\n<p>As you can see in the <a href=\"https://phpunit.de/manual/current/en/test-doubles.html\" rel=\"nofollow noreferrer\">Mocking documentation</a>, the method <code>returnValue($index)</code> allows to return the given argument.</p>\n"
},
{
"answer_id": 22503461,
"author": "Prokhor Sednev",
"author_id": 1333068,
"author_profile": "https://Stackoverflow.com/users/1333068",
"pm_score": 5,
"selected": false,
"text": "<p>It is not exactly what you ask, but in some cases it can help:</p>\n\n<pre><code>$mock->expects( $this->any() ) )\n ->method( 'methodToMock' )\n ->will( $this->onConsecutiveCalls( 'one', 'two' ) );\n</code></pre>\n\n<p><a href=\"http://phpunit.de/manual/3.7/en/test-doubles.html#test-doubles.stubs.examples.StubTest7.php\" rel=\"noreferrer\">onConsecutiveCalls</a> - returns a list of values in the specified order</p>\n"
},
{
"answer_id": 43208045,
"author": "antonmarin",
"author_id": 2526656,
"author_profile": "https://Stackoverflow.com/users/2526656",
"pm_score": 4,
"selected": false,
"text": "<p>Pass two level array, where each element is an array of:</p>\n<ul>\n<li>first are method parameters, and last is return value.</li>\n</ul>\n<p>example:</p>\n<pre><code>->willReturnMap([\n ['firstArg', 'secondArg', 'returnValue']\n])\n</code></pre>\n"
},
{
"answer_id": 43873629,
"author": "jjoselon",
"author_id": 7389315,
"author_profile": "https://Stackoverflow.com/users/7389315",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$this->BusinessMock = $this->createMock('AppBundle\\Entity\\Business');\n\n public function testBusiness()\n {\n /*\n onConcecutiveCalls : Whether you want that the Stub returns differents values when it will be called .\n */\n $this->BusinessMock ->method('getEmployees')\n ->will($this->onConsecutiveCalls(\n $this->returnArgument(0),\n $this->returnValue('employee') \n )\n );\n // first call\n\n $this->assertInstanceOf( //$this->returnArgument(0),\n 'argument',\n $this->BusinessMock->getEmployees()\n );\n // second call\n\n\n $this->assertEquals('employee',$this->BusinessMock->getEmployees()) \n //$this->returnValue('employee'),\n\n\n }\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36191/"
] |
I've got a PHPUnit mock object that returns `'return value'` no matter what its arguments:
```
// From inside a test...
$mock = $this->getMock('myObject', 'methodToMock');
$mock->expects($this->any))
->method('methodToMock')
->will($this->returnValue('return value'));
```
What I want to be able to do is return a different value based on the arguments passed to the mock method. I've tried something like:
```
$mock = $this->getMock('myObject', 'methodToMock');
// methodToMock('one')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('one'))
->will($this->returnValue('method called with argument "one"'));
// methodToMock('two')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('two'))
->will($this->returnValue('method called with argument "two"'));
```
But this causes PHPUnit to complain if the mock isn't called with the argument `'two'`, so I assume that the definition of `methodToMock('two')` overwrites the definition of the first.
So my question is: Is there any way to get a PHPUnit mock object to return a different value based on its arguments? And if so, how?
|
Use a callback. e.g. (straight from PHPUnit documentation):
```
<?php
class StubTest extends PHPUnit_Framework_TestCase
{
public function testReturnCallbackStub()
{
$stub = $this->getMock(
'SomeClass', array('doSomething')
);
$stub->expects($this->any())
->method('doSomething')
->will($this->returnCallback('callback'));
// $stub->doSomething() returns callback(...)
}
}
function callback() {
$args = func_get_args();
// ...
}
?>
```
Do whatever processing you want in the callback() and return the result based on your $args as appropriate.
|
277,922 |
<p>How can I bind arguments to a Python function so that I can call it later without arguments (or with fewer additional arguments)?</p>
<p>For example:</p>
<pre><code>def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
</code></pre>
<p>What is the <code>magic_function</code> I need here?</p>
<hr />
<p><sub>It often happens with frameworks and libraries that people accidentally call a function immediately when trying to give arguments to a callback: for example <code>on_event(action(foo))</code>. The solution is to bind <code>foo</code> as an argument to <code>action</code>, using one of the techniques described here. See for example <a href="https://stackoverflow.com/questions/6920302">How to pass arguments to a Button command in Tkinter?</a> and <a href="https://stackoverflow.com/questions/21962763/">Using a dictionary as a switch statement in Python</a>.</sub></p>
<p><sub>Some APIs, however, allow you to pass the to-be-bound arguments separately, and will do the binding for you. Notably, the threading API in the standard library works this way. See <a href="https://stackoverflow.com/questions/11792629">thread starts running before calling Thread.start</a>.</sub></p>
<p><sub>Explicitly binding arguments is also a way to avoid problems caused by late binding when using closures. This is the problem where, for example, a <code>lambda</code> inside a <code>for</code> loop or list comprehension produces separate functions that compute the same result. See <a href="https://stackoverflow.com/questions/2295290/">What do lambda function closures capture?</a> and <a href="https://stackoverflow.com/questions/3431676/">Creating functions (or lambdas) in a loop (or comprehension)</a>.</sub></p>
|
[
{
"answer_id": 277932,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://docs.python.org/2/library/functools.html#functools.partial\" rel=\"noreferrer\" title=\"Python 2 Documentation: functools module: partial function\"><code>functools.partial</code></a> returns a callable wrapping a function with some or all of the arguments frozen.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nimport functools\n\nprint_hello = functools.partial(sys.stdout.write, \"Hello world\\n\")\n\nprint_hello()\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>Hello world\n</code></pre>\n\n<p>The above usage is equivalent to the following <code>lambda</code>.</p>\n\n<pre><code>print_hello = lambda *a, **kw: sys.stdout.write(\"Hello world\\n\", *a, **kw)\n</code></pre>\n"
},
{
"answer_id": 277933,
"author": "Matthew Trevor",
"author_id": 11265,
"author_profile": "https://Stackoverflow.com/users/11265",
"pm_score": 6,
"selected": false,
"text": "<p>Using <a href=\"https://docs.python.org/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a>:</p>\n<pre><code>>>> from functools import partial\n>>> def f(a, b):\n... return a+b\n... \n>>> p = partial(f, 1, 2)\n>>> p()\n3\n>>> p2 = partial(f, 1)\n>>> p2(7)\n8\n</code></pre>\n"
},
{
"answer_id": 278056,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>Functors can be defined this way in Python. They're callable objects. The \"binding\" merely sets argument values.</p>\n\n<pre><code>class SomeFunctor( object ):\n def __init__( self, arg1, arg2=None ):\n self.arg1= arg1\n self.arg2= arg2\n def __call___( self, arg1=None, arg2=None ):\n a1= arg1 or self.arg1\n a2= arg2 or self.arg2\n # do something\n return\n</code></pre>\n\n<p>You can do things like</p>\n\n<pre><code>x= SomeFunctor( 3.456 )\nx( arg2=123 )\n\ny= SomeFunctor( 3.456, 123 )\ny()\n</code></pre>\n"
},
{
"answer_id": 278217,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "<p>If <code>functools.partial</code> is not available then it can be easily emulated:</p>\n\n<pre><code>>>> make_printer = lambda s: lambda: sys.stdout.write(\"%s\\n\" % s)\n>>> import sys\n>>> print_hello = make_printer(\"hello\")\n>>> print_hello()\nhello\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>def partial(func, *args, **kwargs):\n def f(*args_rest, **kwargs_rest):\n kw = kwargs.copy()\n kw.update(kwargs_rest)\n return func(*(args + args_rest), **kw) \n return f\n\ndef f(a, b):\n return a + b\n\np = partial(f, 1, 2)\nprint p() # -> 3\n\np2 = partial(f, 1)\nprint p2(7) # -> 8\n\nd = dict(a=2, b=3)\np3 = partial(f, **d)\nprint p3(), p3(a=3), p3() # -> 5 6 5\n</code></pre>\n"
},
{
"answer_id": 279892,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "<p>This would work, too:</p>\n\n<pre><code>def curry(func, *args):\n def curried(*innerargs):\n return func(*(args+innerargs))\n curried.__name__ = \"%s(%s, ...)\" % (func.__name__, \", \".join(map(str, args)))\n return curried\n\n>>> w=curry(sys.stdout.write, \"Hey there\")\n>>> w()\nHey there\n</code></pre>\n"
},
{
"answer_id": 15003681,
"author": "Alexander Oh",
"author_id": 887836,
"author_profile": "https://Stackoverflow.com/users/887836",
"pm_score": 4,
"selected": false,
"text": "<p><code>lambda</code>s allow you to create a new unnamed function with fewer arguments and call the function:</p>\n<pre><code>>>> def foobar(x, y, z):\n... print(f'{x}, {y}, {z}')\n... \n>>> foobar(1, 2, 3) # call normal function\n1, 2, 3\n>>> bind = lambda x: foobar(x, 10, 20) # bind 10 and 20 to foobar\n>>> bind(1)\n1, 10, 20\n>>> bind = lambda: foobar(1, 2, 3) # bind all elements\n>>> bind()\n1, 2, 3\n</code></pre>\n<hr />\n<p>You can also use <a href=\"https://docs.python.org/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a>. If you are planning to use named argument binding in the function call this is also applicable:</p>\n<pre><code>>>> from functools import partial\n>>> barfoo = partial(foobar, x=10)\n>>> barfoo(y=5, z=6)\n10, 5, 6\n</code></pre>\n<p>Note that if you bind arguments from the left you need to call the arguments by name. If you bind from the right it works as expected.</p>\n<pre><code>>>> barfoo(5, 6)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: foobar() got multiple values for argument 'x'\n>>> f = partial(foobar, z=20)\n>>> f(1, 1)\n1, 1, 20\n</code></pre>\n"
},
{
"answer_id": 63161150,
"author": "Ataxias",
"author_id": 4055338,
"author_profile": "https://Stackoverflow.com/users/4055338",
"pm_score": 1,
"selected": false,
"text": "<p>The question asks generally about binding arguments, but all answers are about functions. In case you are wondering, <code>partial</code> also works with class constructors (i.e. using a class instead of a function as a first argument), which can be useful for factory classes. You can do it as follows:</p>\n<pre><code>from functools import partial\n\nclass Animal(object):\n def __init__(self, weight, num_legs):\n self.weight = weight\n self.num_legs = num_legs\n \nanimal_class = partial(Animal, weight=12)\nsnake = animal_class(num_legs = 0)\nprint(snake.weight) # prints 12\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20003/"
] |
How can I bind arguments to a Python function so that I can call it later without arguments (or with fewer additional arguments)?
For example:
```
def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
```
What is the `magic_function` I need here?
---
It often happens with frameworks and libraries that people accidentally call a function immediately when trying to give arguments to a callback: for example `on_event(action(foo))`. The solution is to bind `foo` as an argument to `action`, using one of the techniques described here. See for example [How to pass arguments to a Button command in Tkinter?](https://stackoverflow.com/questions/6920302) and [Using a dictionary as a switch statement in Python](https://stackoverflow.com/questions/21962763/).
Some APIs, however, allow you to pass the to-be-bound arguments separately, and will do the binding for you. Notably, the threading API in the standard library works this way. See [thread starts running before calling Thread.start](https://stackoverflow.com/questions/11792629).
Explicitly binding arguments is also a way to avoid problems caused by late binding when using closures. This is the problem where, for example, a `lambda` inside a `for` loop or list comprehension produces separate functions that compute the same result. See [What do lambda function closures capture?](https://stackoverflow.com/questions/2295290/) and [Creating functions (or lambdas) in a loop (or comprehension)](https://stackoverflow.com/questions/3431676/).
|
[`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial "Python 2 Documentation: functools module: partial function") returns a callable wrapping a function with some or all of the arguments frozen.
```py
import sys
import functools
print_hello = functools.partial(sys.stdout.write, "Hello world\n")
print_hello()
```
```none
Hello world
```
The above usage is equivalent to the following `lambda`.
```
print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw)
```
|
277,923 |
<p>How can we find the junit tests in our suite that take the longest amount of time to run? The default output of the junitreport ant task is helpful, but our suite has thousands of tests organized into many smaller suites, so it gets tedious, and the worst offenders are always changing.</p>
<p>We use luntbuild but ideally it would be something we could just run from ant.</p>
|
[
{
"answer_id": 277951,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"http://www.jetbrains.com/teamcity/\" rel=\"nofollow noreferrer\">TeamCity</a>. They have great reports, and version 4.0 even orders your tests so the most flaky tests run first.</p>\n"
},
{
"answer_id": 277963,
"author": "aceinthehole",
"author_id": 520,
"author_profile": "https://Stackoverflow.com/users/520",
"pm_score": 1,
"selected": false,
"text": "<p>If you launch your tests on your build server using cruise control, it is one of the top level options to sort by run time.</p>\n"
},
{
"answer_id": 280352,
"author": "Jeffrey Fredrick",
"author_id": 35894,
"author_profile": "https://Stackoverflow.com/users/35894",
"pm_score": 5,
"selected": true,
"text": "<p>JUnitReport works on the xml files produced by the JUnit task. You could write a task that would read the test durations out of the same xml files (TEST-*.xml). But you can also take a shortcut and just read the summary file created by JUnitReport (TESTS-TestSuites.xml) which has all the information in the single file.</p>\n\n<p>A quick way to do this is to use a bit of xsl to just show the slowest tests:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:text> </xsl:text>\n <xsl:for-each select=\"testsuites/testsuite\">\n <xsl:sort select=\"@time\" data-type=\"number\" order=\"descending\" />\n <xsl:value-of select=\"@name\"/> : <xsl:value-of select=\"@time\"/>\n <xsl:text>\n </xsl:text>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n\n<p>To run from Ant you do this:</p>\n\n<pre><code><target name=\"show.slow.tests\">\n <xslt in=\"target/tests-results/TESTS-TestSuites.xml\" out=\"target/slow.txt\" style=\"slow.xsl\"/>\n</target>\n</code></pre>\n\n<p>Then you can just look at the first X lines to find the X slowest tests:</p>\n\n<p>jfredrick$ head target/slow.txt </p>\n\n<ul>\n ForcingBuildShouldNotLockProjectInQueuedStateTest : 11.581<br/>\n CruiseControlControllerTest : 7.335 <br/>\n AntBuilderTest : 6.512 <br/>\n Maven2BuilderTest : 4.412 <br/>\n CompositeBuilderTest : 2.222 <br/>\n ModificationSetTest : 2.05 <br/>\n NantBuilderTest : 2.04 <br/>\n CruiseControlConfigTest : 1.747<br/> \n ProjectTest : 1.743 <br/>\n BuildLoopMonitorTest : 0.913<br/> \n</ul>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23572/"
] |
How can we find the junit tests in our suite that take the longest amount of time to run? The default output of the junitreport ant task is helpful, but our suite has thousands of tests organized into many smaller suites, so it gets tedious, and the worst offenders are always changing.
We use luntbuild but ideally it would be something we could just run from ant.
|
JUnitReport works on the xml files produced by the JUnit task. You could write a task that would read the test durations out of the same xml files (TEST-\*.xml). But you can also take a shortcut and just read the summary file created by JUnitReport (TESTS-TestSuites.xml) which has all the information in the single file.
A quick way to do this is to use a bit of xsl to just show the slowest tests:
```
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:text> </xsl:text>
<xsl:for-each select="testsuites/testsuite">
<xsl:sort select="@time" data-type="number" order="descending" />
<xsl:value-of select="@name"/> : <xsl:value-of select="@time"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
```
To run from Ant you do this:
```
<target name="show.slow.tests">
<xslt in="target/tests-results/TESTS-TestSuites.xml" out="target/slow.txt" style="slow.xsl"/>
</target>
```
Then you can just look at the first X lines to find the X slowest tests:
jfredrick$ head target/slow.txt
ForcingBuildShouldNotLockProjectInQueuedStateTest : 11.581
CruiseControlControllerTest : 7.335
AntBuilderTest : 6.512
Maven2BuilderTest : 4.412
CompositeBuilderTest : 2.222
ModificationSetTest : 2.05
NantBuilderTest : 2.04
CruiseControlConfigTest : 1.747
ProjectTest : 1.743
BuildLoopMonitorTest : 0.913
|
277,924 |
<p>I'm trying to expand navigation options of the context menu on certain elements (specifically, <code>h1</code> and <code>h2</code> tags)
I want to prevent the browser's default action when right-clicking on those elements.</p>
<p>I found nice information at <a href="http://ajaxcookbook.org/disable-browser-context-menu/" rel="nofollow noreferrer">this page</a>.</p>
<p>However, I couldn't find how to disable the context menu for certain elements. Does someone know how to do it?</p>
<p>I'm using prototype as my javascript API.</p>
|
[
{
"answer_id": 277945,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 3,
"selected": true,
"text": "<p>This will prevent the context menu from appearing on a particular element</p>\n\n<pre><code>$(it).observe(\"contextmenu\", function(e){\n e.stop();\n});\n</code></pre>\n\n<p>So, for example stop all H1/H2 tags from showing a context menu</p>\n\n<pre><code>$$('h1, h2').each(function(it){\n $(it).observe(\"contextmenu\", function(e){\n e.stop();\n });\n})\n</code></pre>\n"
},
{
"answer_id": 277949,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>You can obfuscate it a bit, but ultimately your page is only a guest in the browser in, (and you can take that to mean in the same manner that a prisoner is a \"guest\" of the state, if you wish). Therefore the page must rely on the browser to play nice. If the user wants to run a browser that doesn't play nice, or customize their existing browser to do so, that is always their option. You can <strong>never</strong> <em>force</em> a browser to do anything. <em>Nothing</em> you can do will be able to stop the user from performing a given activity with their browser if they really want to, once they view a page on their local machine. More than that, most recent browsers have facilities already built in to make it very easy for the user to override the normal behavior when something seems out of the ordinary.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17600/"
] |
I'm trying to expand navigation options of the context menu on certain elements (specifically, `h1` and `h2` tags)
I want to prevent the browser's default action when right-clicking on those elements.
I found nice information at [this page](http://ajaxcookbook.org/disable-browser-context-menu/).
However, I couldn't find how to disable the context menu for certain elements. Does someone know how to do it?
I'm using prototype as my javascript API.
|
This will prevent the context menu from appearing on a particular element
```
$(it).observe("contextmenu", function(e){
e.stop();
});
```
So, for example stop all H1/H2 tags from showing a context menu
```
$$('h1, h2').each(function(it){
$(it).observe("contextmenu", function(e){
e.stop();
});
})
```
|
277,942 |
<p>I am attempting to create a struts2 component using freemarker. I created an <code>ftl</code> file with code like this:</p>
<pre><code><script type="text/javascript" src="${parameters.library?default('')}"></script>
</code></pre>
<p>Which is expecting a parameter named <code>library</code> to be passed to the component. If the parameter is absent then it defaults to a blank <code>String</code>.</p>
<p>On my JSP page, I am referring to the component like this:</p>
<pre><code><s:component template="mytemplate.ftl">
<s:param name="library" value="/scripts/mylibrary.js"/>
</s:component>
</code></pre>
<p>Unfortunately, the value for the library parameter is not being set. It is always a blank <code>String</code>.</p>
<p>I am using the advice from this <a href="http://www.vitarara.org/cms/struts_2_cookbook/creating_a_ui_component" rel="nofollow noreferrer">tutorial</a> and it seems as if the <code>s:param</code> tag should pass the parameter into the template and make it available. What am I missing here? </p>
<p>Does anyone have some experience building these components that could shed some light?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 286226,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<p>I eventually ran across some syntax in the docs that works. I have to refer to the parameter like this:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"${parameters.get('library')?default('')}\">\n</script>\n</code></pre>\n"
},
{
"answer_id": 1763400,
"author": "Kirti Teja",
"author_id": 214599,
"author_profile": "https://Stackoverflow.com/users/214599",
"pm_score": 4,
"selected": true,
"text": "<p>send the param with single quotes</p>\n\n<pre><code><s:component template=\"mytemplate.ftl\">\n <s:param name=\"library\" value=\"'/scripts/mylibrary.js'\"/>\n</s:component>\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27439/"
] |
I am attempting to create a struts2 component using freemarker. I created an `ftl` file with code like this:
```
<script type="text/javascript" src="${parameters.library?default('')}"></script>
```
Which is expecting a parameter named `library` to be passed to the component. If the parameter is absent then it defaults to a blank `String`.
On my JSP page, I am referring to the component like this:
```
<s:component template="mytemplate.ftl">
<s:param name="library" value="/scripts/mylibrary.js"/>
</s:component>
```
Unfortunately, the value for the library parameter is not being set. It is always a blank `String`.
I am using the advice from this [tutorial](http://www.vitarara.org/cms/struts_2_cookbook/creating_a_ui_component) and it seems as if the `s:param` tag should pass the parameter into the template and make it available. What am I missing here?
Does anyone have some experience building these components that could shed some light?
Thanks.
|
send the param with single quotes
```
<s:component template="mytemplate.ftl">
<s:param name="library" value="'/scripts/mylibrary.js'"/>
</s:component>
```
|
277,944 |
<p>I have to read a binary file in a legacy format with Java. </p>
<p>In a nutshell the file has a header consisting of several integers, bytes and fixed-length char arrays, followed by a list of records which also consist of integers and chars.</p>
<p>In any other language I would create <code>struct</code>s (C/C++) or <code>record</code>s (Pascal/Delphi) which are byte-by-byte representations of the header and the record. Then I'd read <code>sizeof(header)</code> bytes into a header variable and do the same for the records.</p>
<p>Something like this: (Delphi)</p>
<pre><code>type
THeader = record
Version: Integer;
Type: Byte;
BeginOfData: Integer;
ID: array[0..15] of Char;
end;
...
procedure ReadData(S: TStream);
var
Header: THeader;
begin
S.ReadBuffer(Header, SizeOf(THeader));
...
end;
</code></pre>
<p>What is the best way to do something similar with Java? Do I have to read every single value on its own or is there any other way to do this kind of "block-read"?</p>
|
[
{
"answer_id": 277961,
"author": "Arvind",
"author_id": 11541,
"author_profile": "https://Stackoverflow.com/users/11541",
"pm_score": 2,
"selected": false,
"text": "<p>I guess FileInputStream lets you read in bytes. So, opening the file with FileInputStream and read in the sizeof(header). I am assuming that the header has a fixed format and size. I don't see that mentioned in the initial post, but assuming that is the case as it would get much more complex if the header has optional args and different sizes.</p>\n\n<p>Once you have the info, there can be a header class in which you assign the contents of the buffer that you've already read. And then parse the records in a similar fashion.</p>\n"
},
{
"answer_id": 277992,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 4,
"selected": false,
"text": "<p>You could use the DataInputStream class as follows:</p>\n\n<pre><code>DataInputStream in = new DataInputStream(new BufferedInputStream(\n new FileInputStream(\"filename\")));\nint x = in.readInt();\ndouble y = in.readDouble();\n\netc.\n</code></pre>\n\n<p>Once you get these values you can do with them as you please. Look up the java.io.DataInputStream class in the API for more info.</p>\n"
},
{
"answer_id": 277995,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": 1,
"selected": false,
"text": "<p>In the past I used DataInputStream to read data of arbitrary types in a specified order. This will not allow you to easily account for big-endian/little-endian issues.</p>\n\n<p>As of 1.4 the java.nio.Buffer family might be the way to go, but it seems that the your code might actually be more complicated. These classes do have support for handling endian issues.</p>\n"
},
{
"answer_id": 278021,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 6,
"selected": true,
"text": "<p>To my knowledge, Java forces you to read a file as bytes rather than being able to block read. If you were serializing Java objects, it'd be a different story.</p>\n\n<p>The other examples shown use the <a href=\"http://java.sun.com/javase/6/docs/api/java/io/DataInputStream.html\" rel=\"noreferrer\">DataInputStream</a> class with a File, but you can also use a shortcut: The <a href=\"http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html\" rel=\"noreferrer\">RandomAccessFile</a> class:</p>\n\n<pre><code>RandomAccessFile in = new RandomAccessFile(\"filename\", \"r\");\nint version = in.readInt();\nbyte type = in.readByte();\nint beginOfData = in.readInt();\nbyte[] tempId;\nin.read(tempId, 0, 16);\nString id = new String(tempId);\n</code></pre>\n\n<p>Note that you could turn the responce objects into a class, if that would make it easier.</p>\n"
},
{
"answer_id": 278224,
"author": "Thomas Jones-Low",
"author_id": 23030,
"author_profile": "https://Stackoverflow.com/users/23030",
"pm_score": 1,
"selected": false,
"text": "<p>A while ago I found <a href=\"http://www.webservicessummit.com/Articles/MadhuOct2005_1.htm\" rel=\"nofollow noreferrer\">this article</a> on using reflection and parsing to read binary data. In this case, the author is using reflection to read the java binary .class files. But if you are reading the data into a class file, it may be of some help. </p>\n"
},
{
"answer_id": 278254,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 3,
"selected": false,
"text": "<p>I may have misunderstood you, but it seems to me you're creating in-memory structures you hope will be a byte-per-byte accurate representation of what you want to read from hard-disk, then copy the whole stuff onto memory and manipulate thence?</p>\n\n<p>If that's indeed the case, you're playing a very dangerous game. At least in C, the standard doesn't enforce things like padding or aligning of members of a struct. Not to mention things like big/small endianness or parity bits... So even if your code happens to run it's very non-portable and risky - you depend on the compiler's creator not changing its mind on future versions.</p>\n\n<p>Better to create an automaton to both validate the structure being read (byte per byte) from HD is valid, and filling an in-memory structure if it's indeed OK. You may loose some milliseconds (not so much as it may seem for modern OSes do a lot of disk read caching) though you gain platform and compiler independence. Plus, your code will be easily ported to another language.</p>\n\n<p>Post Edit: In a way I sympathize with you. In the good-ol' days of DOS/Win3.11, I once created a C program to read BMP files. And used exactly the same technique. Everything was nice until I tried to compile it for Windows - oops!! Int was now 32 bits long, rather than 16! When I tried to compile on Linux, discovered gcc had very different rules for bit fields allocation than Microsoft C (6.0!). I had to resort to macro tricks to make it portable...</p>\n"
},
{
"answer_id": 278284,
"author": "Javamann",
"author_id": 10166,
"author_profile": "https://Stackoverflow.com/users/10166",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a link to read byte using a ByteBuffer (Java NIO)</p>\n\n<p><a href=\"http://exampledepot.com/egs/java.nio/ReadChannel.html\" rel=\"nofollow noreferrer\">http://exampledepot.com/egs/java.nio/ReadChannel.html</a></p>\n"
},
{
"answer_id": 278299,
"author": "John Montgomery",
"author_id": 5868,
"author_profile": "https://Stackoverflow.com/users/5868",
"pm_score": 2,
"selected": false,
"text": "<p>As other people mention DataInputStream and Buffers are probably the low-level API's you are after for dealing with binary data in java.</p>\n\n<p>However you probably want something like <a href=\"http://construct.wikispaces.com/\" rel=\"nofollow noreferrer\">Construct</a> (wiki page has good examples too: <a href=\"http://en.wikipedia.org/wiki/Construct_(python_library))\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Construct_(python_library)</a>, but for Java.</p>\n\n<p>I don't know of any (Java versions) off hand, but taking that approach (declaratively specifying the struct in code) would probably be the right way to go. With a suitable <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow noreferrer\">fluent interface</a> in Java it would probably be quite similar to a DSL.</p>\n\n<p>EDIT: bit of googling reveals this:</p>\n\n<p><a href=\"http://javolution.org/api/javolution/io/Struct.html\" rel=\"nofollow noreferrer\">http://javolution.org/api/javolution/io/Struct.html</a></p>\n\n<p>Which might be the kind of thing you are looking for. I have no idea whether it works or is any good, but it looks like a sensible place to start.</p>\n"
},
{
"answer_id": 822868,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've written up a technique to do this sort of thing in java - similar to the old C-like idiom of reading bit-fields. Note it is just a start but could be expanded upon.</p>\n\n<p><a href=\"http://codify.flansite.com/2009/05/c-struct-like-parsing-of-binary-data-with-java/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 1266690,
"author": "Wilfred Springer",
"author_id": 136476,
"author_profile": "https://Stackoverflow.com/users/136476",
"pm_score": 4,
"selected": false,
"text": "<p>If you would be using <a href=\"https://github.com/preon/preon\" rel=\"noreferrer\">Preon</a>, then all you would have to do is this:</p>\n\n<pre><code>public class Header {\n @BoundNumber int version;\n @BoundNumber byte type;\n @BoundNumber int beginOfData;\n @BoundString(size=\"15\") String id;\n}\n</code></pre>\n\n<p>Once you have this, you create Codec using a single line:</p>\n\n<pre><code>Codec<Header> codec = Codecs.create(Header.class);\n</code></pre>\n\n<p>And you use the Codec like this:</p>\n\n<pre><code>Header header = Codecs.decode(codec, file);\n</code></pre>\n"
},
{
"answer_id": 2378996,
"author": "anonymous",
"author_id": 277778,
"author_profile": "https://Stackoverflow.com/users/277778",
"pm_score": 2,
"selected": false,
"text": "<p>I would create an object that wraps around a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/nio/ByteBuffer.html\" rel=\"nofollow noreferrer\">ByteBuffer</a> representation of the data and provide getters to read directly from the buffer. In this way, you avoid copying data from the buffer to primitive types. Furthermore, you could use a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/nio/MappedByteBuffer.html\" rel=\"nofollow noreferrer\">MappedByteBuffer</a> to get the byte buffer. If your binary data is complex, you can model it using classes and give each class a sliced version of your buffer.</p>\n\n<pre><code>class SomeHeader {\n private final ByteBuffer buf;\n SomeHeader( ByteBuffer fileBuffer){\n // you may need to set limits accordingly before\n // fileBuffer.limit(...)\n this.buf = fileBuffer.slice();\n // you may need to skip the sliced region\n // fileBuffer.position(endPos)\n }\n public short getVersion(){\n return buf.getShort(POSITION_OF_VERSION_IN_BUFFER);\n }\n}\n</code></pre>\n\n<p>Also useful are the <a href=\"http://www.javafaq.nu/java-example-code-342.html\" rel=\"nofollow noreferrer\">methods for reading unsigned values</a> from byte buffers.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 8353652,
"author": "Ko-Chih Wu",
"author_id": 296291,
"author_profile": "https://Stackoverflow.com/users/296291",
"pm_score": 3,
"selected": false,
"text": "<p>I used Javolution and javastruct, both handles the conversion between bytes and objects.</p>\n\n<p><a href=\"http://javolution.org/target/site/apidocs/javolution/io/Struct.html\" rel=\"noreferrer\">Javolution</a> provides classes that represent C types. All you need to do is to write a class that describes the C structure. For example, from the C header file,</p>\n\n<pre><code>struct Date {\n unsigned short year;\n unsigned byte month;\n unsigned byte day;\n};\n</code></pre>\n\n<p>should be translated into:</p>\n\n<pre><code>public static class Date extends Struct {\n public final Unsigned16 year = new Unsigned16();\n public final Unsigned8 month = new Unsigned8();\n public final Unsigned8 day = new Unsigned8();\n}\n</code></pre>\n\n<p>Then call <code>setByteBuffer</code> to initialize the object:</p>\n\n<pre><code>Date date = new Date();\ndate.setByteBuffer(ByteBuffer.wrap(bytes), 0);\n</code></pre>\n\n<p><a href=\"http://code.google.com/p/javastruct/wiki/HowToUseJavaStruct\" rel=\"noreferrer\">javastruct</a> uses annotation to define fields in a C structure.</p>\n\n<pre><code>@StructClass\npublic class Foo{\n\n @StructField(order = 0)\n public byte b;\n\n @StructField(order = 1)\n public int i;\n}\n</code></pre>\n\n<p>To initialize an object:</p>\n\n<pre><code>Foo f2 = new Foo();\nJavaStruct.unpack(f2, b);\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
I have to read a binary file in a legacy format with Java.
In a nutshell the file has a header consisting of several integers, bytes and fixed-length char arrays, followed by a list of records which also consist of integers and chars.
In any other language I would create `struct`s (C/C++) or `record`s (Pascal/Delphi) which are byte-by-byte representations of the header and the record. Then I'd read `sizeof(header)` bytes into a header variable and do the same for the records.
Something like this: (Delphi)
```
type
THeader = record
Version: Integer;
Type: Byte;
BeginOfData: Integer;
ID: array[0..15] of Char;
end;
...
procedure ReadData(S: TStream);
var
Header: THeader;
begin
S.ReadBuffer(Header, SizeOf(THeader));
...
end;
```
What is the best way to do something similar with Java? Do I have to read every single value on its own or is there any other way to do this kind of "block-read"?
|
To my knowledge, Java forces you to read a file as bytes rather than being able to block read. If you were serializing Java objects, it'd be a different story.
The other examples shown use the [DataInputStream](http://java.sun.com/javase/6/docs/api/java/io/DataInputStream.html) class with a File, but you can also use a shortcut: The [RandomAccessFile](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html) class:
```
RandomAccessFile in = new RandomAccessFile("filename", "r");
int version = in.readInt();
byte type = in.readByte();
int beginOfData = in.readInt();
byte[] tempId;
in.read(tempId, 0, 16);
String id = new String(tempId);
```
Note that you could turn the responce objects into a class, if that would make it easier.
|
277,953 |
<p>I have a table of events with a recorded start and end time as a MySQL DATETIME object (in the format <code>YYYY-MM-DD HH:MM:SS</code>. I want to find all events that occur in a specific date range. However, events can span multiple days (and go outside of my date range, but I want to return them if they even overlap by 1 second or more with my date range).</p>
<p>Suggestions?</p>
|
[
{
"answer_id": 277967,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT *\nFROM table\nWHERE startdate >= 'starting date' AND startdate < 'ending date'\n OR enddate >= 'starting date' AND enddate < 'ending date'\n</code></pre>\n\n<p>should work for you.</p>\n\n<p>Make sure you specify 'starting date' and 'ending date' with the time included.</p>\n\n<pre><code>'2008-01-01 00:00:00'' AND '2008-01-31 23:59:59'\n</code></pre>\n\n<p>This will help to avoid errors where dates are the same, but your time falls within the interval by a few hours, minutes, or seconds.</p>\n"
},
{
"answer_id": 277968,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": true,
"text": "<p>This will find every event that is completely contained inside the range:</p>\n\n<pre><code>SELECT * FROM table WHERE start_date BETWEEN start_of_range AND end_of_range \n AND stop_date BETWEEN start_of_range AND end_of_range\n</code></pre>\n\n<p>This will find any events where any part of the event overlaps any part of the range:</p>\n\n<pre><code>SELECT * FROM table WHERE start_date <= end_of_range \n AND stop_date >= start_of_range\n</code></pre>\n"
},
{
"answer_id": 277976,
"author": "Ilya",
"author_id": 7566,
"author_profile": "https://Stackoverflow.com/users/7566",
"pm_score": 1,
"selected": false,
"text": "<p>Basically, you can use regular comparisons -- the ones above should work -- the trick is to check all the different cases that can occur.</p>\n\n<p>A) events with an ending date within the range</p>\n\n<p>B) events with a starting date within the range</p>\n\n<p>C) events with both starting and ending dates within the range </p>\n\n<p>D) events with both starting and ending dates <em>outside</em> the range, but overlapping it</p>\n\n<p>Robert's answer is a good one, but it doesn't take into account case D, where the event starts before the range and ends after the range.</p>\n"
},
{
"answer_id": 277994,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "<p>The answers by @Bill the Lizard and @Robert Gamble are correct for the question as asked, but I do wonder if you're asking what you think you are... If you're looking for overlapping events then you need to take into account events longer than your search range.</p>\n\n<pre><code> Monday Tuesday Wednesday Thursday\n\nSearch: |-----------|\n\nShopping |-----| Found OK\nEating |--------| Found OK\nStack Overflow |---------------------------------| Not found!\n</code></pre>\n\n<p>If you wanted to include SO, you'd do:</p>\n\n<p><code>SELECT * FROM table WHERE (start_date < end_of_range AND end_date > start_of_range)</code></p>\n"
},
{
"answer_id": 372657,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Llya, Roberts answer with,</p>\n\n<p>SELECT * FROM table WHERE start_date <= end_of_range \n AND stop_date >= start_of_range</p>\n\n<p>works fine with,</p>\n\n<p>D) events with both starting and ending dates outside the range, but overlapping it</p>\n\n<p>??</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
I have a table of events with a recorded start and end time as a MySQL DATETIME object (in the format `YYYY-MM-DD HH:MM:SS`. I want to find all events that occur in a specific date range. However, events can span multiple days (and go outside of my date range, but I want to return them if they even overlap by 1 second or more with my date range).
Suggestions?
|
This will find every event that is completely contained inside the range:
```
SELECT * FROM table WHERE start_date BETWEEN start_of_range AND end_of_range
AND stop_date BETWEEN start_of_range AND end_of_range
```
This will find any events where any part of the event overlaps any part of the range:
```
SELECT * FROM table WHERE start_date <= end_of_range
AND stop_date >= start_of_range
```
|
277,965 |
<p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p>
<p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p>
<pre><code>if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
</code></pre>
<p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p>
<pre><code>{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
</code></pre>
<p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p>
<p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p>
<pre><code>handle_extractTag(self, dom, anotherObject)
# Do something
</code></pre>
<p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p>
<p>Cheers</p>
|
[
{
"answer_id": 277972,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "<p>To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg</p>\n\n<pre><code>class MyHandler(object):\n def handle_extractTitle(self, dom):\n # do something\n\n def handle_extractMetaTags(self, dom):\n # do something\n\n def handle(self, type, dom):\n func = getattr(self, 'handle_%s' % type, None)\n if func is None:\n raise Exception(\"No handler for type %r\" % type)\n return func(dom)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> handler = MyHandler()\n handler.handle('extractTitle', dom)\n</code></pre>\n\n<p><strong>Update:</strong> </p>\n\n<p>When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the *args and **kwargs syntax to pass through all received arguments. The handle method then becomes:</p>\n\n<pre><code>def handle(self, type, *args, **kwargs):\n func = getattr(self, 'handle_%s' % type, None)\n if func is None:\n raise Exception(\"No handler for type %r\" % type)\n return func(*args, **kwargs)\n</code></pre>\n"
},
{
"answer_id": 277978,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on how many if statements we're talking about; if it's a very small number, then it will be more efficient than using a dictionary.</p>\n\n<p>However, as always, I strongly advice you to do whatever makes your code look cleaner until experience and profiling tell you that a specific block of code needs to be optimized.</p>\n"
},
{
"answer_id": 277980,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 1,
"selected": false,
"text": "<p>Your use of the dictionary is not quite correct. In your implementation, all methods will be called and all the useless one discarded. What is usually done is more something like:</p>\n\n<pre><code>switch_dict = {'extractTitle': extractTitle, \n 'extractMetaTags': extractMetaTags}\nswitch_dict[type](dom)\n</code></pre>\n\n<p>And that way is facter and more extensible if you have a large (or variable) number of items.</p>\n"
},
{
"answer_id": 277981,
"author": "Marcos Lara",
"author_id": 30626,
"author_profile": "https://Stackoverflow.com/users/30626",
"pm_score": 2,
"selected": false,
"text": "<p>With your code you're running your functions all get called.</p>\n\n<pre>\nhandlers = {\n'extractTitle': extractTitle, \n'extractMetaTags': extractMetaTags\n}\n\nhandlers[type](dom)\n</pre>\n\n<p>Would work like your original <code>if</code> code.</p>\n"
},
{
"answer_id": 278006,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>The efficiency question is barely relevant. The dictionary lookup is done with a simple hashing technique, the if-statements have to be evaluated one at a time. Dictionaries tend to be quicker.</p>\n\n<p>I suggest that you actually have polymorphic objects that do extractions from the DOM.</p>\n\n<p>It's not clear how <code>type</code> gets set, but it sure looks like it might be a family of related objects, not a simple string.</p>\n\n<pre><code>class ExtractTitle( object ):\n def process( dom ):\n return something\n\nclass ExtractMetaTags( object ):\n def process( dom ):\n return something\n</code></pre>\n\n<p>Instead of setting type=\"extractTitle\", you'd do this.</p>\n\n<pre><code>type= ExtractTitle() # or ExtractMetaTags() or ExtractWhatever()\ntype.process( dom )\n</code></pre>\n\n<p>Then, you wouldn't be building this particular dictionary or if-statement.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
I am writing a script at the moment that will grab certain information from HTML using dom4j.
Since Python/Jython does not have a native **switch** statement I decided to use a whole bunch of **if** statements that call the appropriate method, like below:
```
if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
```
I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:
```
{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
```
I know that each time I run the script the dictionary will be built, but at the same time if I were to use the **if** statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?
**Update:** @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.
```
handle_extractTag(self, dom, anotherObject)
# Do something
```
How would you make the appropriate changes to the **handle** method to implemented this? Hope you know what I mean :)
Cheers
|
To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg
```
class MyHandler(object):
def handle_extractTitle(self, dom):
# do something
def handle_extractMetaTags(self, dom):
# do something
def handle(self, type, dom):
func = getattr(self, 'handle_%s' % type, None)
if func is None:
raise Exception("No handler for type %r" % type)
return func(dom)
```
Usage:
```
handler = MyHandler()
handler.handle('extractTitle', dom)
```
**Update:**
When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the \*args and \*\*kwargs syntax to pass through all received arguments. The handle method then becomes:
```
def handle(self, type, *args, **kwargs):
func = getattr(self, 'handle_%s' % type, None)
if func is None:
raise Exception("No handler for type %r" % type)
return func(*args, **kwargs)
```
|
277,996 |
<p>Do you know of a JAXB setting to prevent <strong>standalone="yes"</strong> from being generated in the resulting XML?</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
</code></pre>
|
[
{
"answer_id": 352107,
"author": "Sam",
"author_id": 37575,
"author_profile": "https://Stackoverflow.com/users/37575",
"pm_score": 7,
"selected": true,
"text": "<p>This property:</p>\n<pre class=\"lang-java prettyprint-override\"><code>marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false);\n</code></pre>\n<p>...can be used to have no:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n</code></pre>\n<p>However, I wouldn't consider this best practice.</p>\n"
},
{
"answer_id": 391234,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "<p>If you make document dependent on <code>DOCTYPE</code> (e.g. use named entities) then it will stop being standalone, thus <code>standalone=\"yes\"</code> won't be allowed in XML declaration.</p>\n\n<p>However standalone XML can be used anywhere, while non-standalone is problematic for XML parsers that don't load externals. </p>\n\n<p>I don't see how this declaration could be a problem, other than for interoperability with software that doesn't support XML, but some horrible regex soup.</p>\n"
},
{
"answer_id": 4067474,
"author": "so_mv",
"author_id": 186858,
"author_profile": "https://Stackoverflow.com/users/186858",
"pm_score": 7,
"selected": false,
"text": "<p>in JAXB that is part of JDK1.6</p>\n<pre class=\"lang-java prettyprint-override\"><code>marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);\n</code></pre>\n"
},
{
"answer_id": 5431542,
"author": "WarFox",
"author_id": 598444,
"author_profile": "https://Stackoverflow.com/users/598444",
"pm_score": 6,
"selected": false,
"text": "<p>You can either use</p>\n<pre class=\"lang-java prettyprint-override\"><code>marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);\n</code></pre>\n<p>or</p>\n<pre class=\"lang-java prettyprint-override\"><code>marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false)\n</code></pre>\n<p>to disable the default XML declaration, and then add your custom XML declaration,</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="UTF-8"?>\n</code></pre>\n<p>by</p>\n<pre class=\"lang-java prettyprint-override\"><code>marshaller.setProperty("com.sun.xml.bind.xmlHeaders",\n "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>");\n</code></pre>\n<p>to the generated xml, thus avoiding the <strong>standalone="yes"</strong> property.</p>\n"
},
{
"answer_id": 38872445,
"author": "Debasis Das",
"author_id": 5280559,
"author_profile": "https://Stackoverflow.com/users/5280559",
"pm_score": 2,
"selected": false,
"text": "<pre><code>jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\njaxbMarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\", \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"no\\\"?>\");\n</code></pre>\n\n<p>This worked for me with JDK1.7. standalone=\\\"no\\\" can be removed to get only rest of the xml part</p>\n"
},
{
"answer_id": 39628056,
"author": "Ari",
"author_id": 3741495,
"author_profile": "https://Stackoverflow.com/users/3741495",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have a high enough \"reputation\" to have the \"privilege\" to comment. ;-)</p>\n\n<p>@Debasis, note that the property you've specified:</p>\n\n<pre><code>\"com.sun.xml.internal.bind.xmlHeaders\"\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>\"com.sun.xml.bind.xmlHeaders\" (without the \"internal\", which are not meant to be used by the public)\n</code></pre>\n\n<p>If I use the \"internal\" property as you did, I get a <em>javax.xml.bind.PropertyException</em></p>\n"
},
{
"answer_id": 40464942,
"author": "benez",
"author_id": 3583589,
"author_profile": "https://Stackoverflow.com/users/3583589",
"pm_score": 3,
"selected": false,
"text": "<p>just if someone else is still struggeling with this problem, you may consider using</p>\n\n<pre><code>marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n</code></pre>\n\n<p>to remove all of the XML declaration and just write your own <code>String</code> at the beginning of your output stream / method</p>\n"
},
{
"answer_id": 43756759,
"author": "eddo",
"author_id": 5888756,
"author_profile": "https://Stackoverflow.com/users/5888756",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using only the default javax.xml package, you could set the JAXB_FRAGMENT option of the marshaller to 'true' (this omits the default xml processing instruction) and use the writeProcessingInstruction method of the XMLStreamWriter to insert your own:</p>\n\n<pre><code>xmlStreamWriter.writeProcessingInstruction(\"xml\", \"version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"\");\njaxbMarshaller.setProperty( Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\njaxbMarshaller.marshal(object, xmlStreamWriter);\nxmlStreamWriter.writeEndDocument();\n</code></pre>\n"
},
{
"answer_id": 49759995,
"author": "William Funchal Pereira",
"author_id": 7237534,
"author_profile": "https://Stackoverflow.com/users/7237534",
"pm_score": 2,
"selected": false,
"text": "<p>You can use:\n marshaller.setProperty(\"jaxb.fragment\", Boolean.TRUE);</p>\n\n<p>It works for me on Java 8</p>\n"
},
{
"answer_id": 54620205,
"author": "Alisha Setia",
"author_id": 8160374,
"author_profile": "https://Stackoverflow.com/users/8160374",
"pm_score": 1,
"selected": false,
"text": "<p>In case you are getting property exception, add the following configuration: </p>\n\n<pre><code>jaxbMarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\",\n \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\njaxbMarshaller.setProperty(\"com.sun.xml.internal.bind.xmlDeclaration\", Boolean.FALSE);\njaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); \n</code></pre>\n"
},
{
"answer_id": 57382362,
"author": "Bernardo Mello",
"author_id": 10185475,
"author_profile": "https://Stackoverflow.com/users/10185475",
"pm_score": 2,
"selected": false,
"text": "<p>just try</p>\n\n<pre><code>private String marshaling2(Object object) throws JAXBException, XMLStreamException {\n JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());\n Marshaller jaxbMarshaller = jaxbContext.createMarshaller();\n jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);\n jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n StringWriter writer = new StringWriter();\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n jaxbMarshaller.marshal(object, writer);\n return writer.toString();\n }\n</code></pre>\n"
},
{
"answer_id": 59061847,
"author": "Cesar",
"author_id": 5428711,
"author_profile": "https://Stackoverflow.com/users/5428711",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using Java 1.8 and JAXB 2.3.1</p>\n\n<p>First, be sure to be using java 1.8 in pom.xml</p>\n\n<pre><code><maven.compiler.source>1.8</maven.compiler.source>\n<maven.compiler.target>1.8</maven.compiler.target>\n</code></pre>\n\n<p>Then in source code I used: (the key was the internal part)</p>\n\n<pre><code>// remove standalone=yes\nmarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);\nmarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\", \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n</code></pre>\n"
},
{
"answer_id": 60774183,
"author": "Baked Inhalf",
"author_id": 3302747,
"author_profile": "https://Stackoverflow.com/users/3302747",
"pm_score": 0,
"selected": false,
"text": "<p>If you have <code><?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?></code> </p>\n\n<p>but want this: <code><?xml version=\"1.0\" encoding=\"UTF-8\"?></code></p>\n\n<p>Just do:</p>\n\n<pre><code>marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\nmarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\", \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9707/"
] |
Do you know of a JAXB setting to prevent **standalone="yes"** from being generated in the resulting XML?
```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
```
|
This property:
```java
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false);
```
...can be used to have no:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
```
However, I wouldn't consider this best practice.
|
277,999 |
<p>I know that to find all the <code>.h</code> files I need to use:</p>
<pre><code>find . -name "*.h"
</code></pre>
<p>but how to find all the <code>.h</code> AND <code>.cpp</code> files?</p>
|
[
{
"answer_id": 278002,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 7,
"selected": true,
"text": "<pre><code>find . -name \\*.h -print -o -name \\*.cpp -print\n</code></pre>\n\n<p>or</p>\n\n<pre><code>find . \\( -name \\*.h -o -name \\*.cpp \\) -print\n</code></pre>\n"
},
{
"answer_id": 278018,
"author": "Philluminati",
"author_id": 25466,
"author_profile": "https://Stackoverflow.com/users/25466",
"pm_score": 4,
"selected": false,
"text": "<pre><code>find -name \"*.h\" -or -name \"*.cpp\"\n</code></pre>\n\n<p>(edited to protect the asterisks which were interpreted as formatting)</p>\n"
},
{
"answer_id": 278181,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/277999/how-to-use-the-unix-find-command-to-find-all-the-cpp-and-h-files#278002\">Paul Tomblin</a> Has Already provided a terrific answer, but I thought I saw a pattern in what you were doing. </p>\n\n<p>Chances are you'll be using find to generate a file list to process with grep one day, and for such task there exists a much more user friendly tool, <a href=\"http://petdance.com/ack/\" rel=\"nofollow noreferrer\">Ack</a></p>\n\n<p>Works on any system that supports perl, and searching through all C++ related files in a directory recursively for a given string is as simple as</p>\n\n<pre><code>ack \"int\\s+foo\" --cpp \n</code></pre>\n\n<p><code>\"--cpp\"</code> by default matches <code>.cpp .cc .cxx .m .hpp .hh .h .hxx</code> files </p>\n\n<p>(It also skips repository dirs by default so wont match on files that happen to look like files in them.) </p>\n"
},
{
"answer_id": 3858879,
"author": "Lyle Snodgrass",
"author_id": 466203,
"author_profile": "https://Stackoverflow.com/users/466203",
"pm_score": 2,
"selected": false,
"text": "<pre><code>find . -regex \".*\\.[cChH]\\(pp\\)?\" -print\n</code></pre>\n\n<p>This tested fine for me in cygwin.</p>\n"
},
{
"answer_id": 25174706,
"author": "northteam",
"author_id": 712919,
"author_profile": "https://Stackoverflow.com/users/712919",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>find</code> in this short form:</p>\n\n<pre><code>find \\( -name '*.cpp' -o -name '*.h' \\) -print\n</code></pre>\n\n<p><code>-print</code> can be omitted. Using <code>-o</code> just between expressions is especially useful when you want to find multiple types of files and do one same job (let's say calculating md5sum).</p>\n"
},
{
"answer_id": 29963360,
"author": "mdup",
"author_id": 899752,
"author_profile": "https://Stackoverflow.com/users/899752",
"pm_score": 3,
"selected": false,
"text": "<p>A short, clear way to do it with <code>find</code> is:</p>\n\n<pre><code>find . -regex '.*\\.\\(cpp\\|h\\)'\n</code></pre>\n\n<p>From the man page for <code>-regex</code>: \"This is a match on the whole path, not a search.\" Hence the need to prefix with <code>.*</code> to match the beginning of the path <code>./dir1/dir2/...</code> before the filename.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I know that to find all the `.h` files I need to use:
```
find . -name "*.h"
```
but how to find all the `.h` AND `.cpp` files?
|
```
find . -name \*.h -print -o -name \*.cpp -print
```
or
```
find . \( -name \*.h -o -name \*.cpp \) -print
```
|
278,034 |
<p>I have an authentication script (<strong><code>CheckLogin.aspx</code></strong>), and if any of the credentials do not match my application will redirect (via <strong><code>Server.Transfer</code></strong>) to the access denied page (<strong><code>forbidden.aspx</code></strong>). Each time my script runs,it gets an <strong><code>InvalidOperationException: Failed to map the path '/forbidden.aspx'</code></strong>. Here is a mockup of my applications file structure:</p>
<pre><code><root>
..default.aspx
..forbidden.aspx
..<inc>
....scripts.js
..<auth>
....CheckLogin.aspx
</code></pre>
<p>As you can see, the <strong><code>CheckLogin.aspx</code></strong> page is in a folder inside the root, and the <strong><code>forbidden.aspx</code></strong> page is inside the root itself. The path I am telling my application to redirect to is <strong><code>/forbidden.aspx</code></strong>.</p>
|
[
{
"answer_id": 278042,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 3,
"selected": true,
"text": "<p>Sometimes you have to precede the page path with a tilde to indicate the root directory:</p>\n\n<pre><code>'~/forbidden.aspx'\n</code></pre>\n"
},
{
"answer_id": 278044,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using \"~/...\" to make sure all your paths are relative? </p>\n\n<p>By the way, you should just set up page access via Web.config, by using the <code><location></code> tags. That way you can have some sort of role-based access, without much custom code.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
I have an authentication script (**`CheckLogin.aspx`**), and if any of the credentials do not match my application will redirect (via **`Server.Transfer`**) to the access denied page (**`forbidden.aspx`**). Each time my script runs,it gets an **`InvalidOperationException: Failed to map the path '/forbidden.aspx'`**. Here is a mockup of my applications file structure:
```
<root>
..default.aspx
..forbidden.aspx
..<inc>
....scripts.js
..<auth>
....CheckLogin.aspx
```
As you can see, the **`CheckLogin.aspx`** page is in a folder inside the root, and the **`forbidden.aspx`** page is inside the root itself. The path I am telling my application to redirect to is **`/forbidden.aspx`**.
|
Sometimes you have to precede the page path with a tilde to indicate the root directory:
```
'~/forbidden.aspx'
```
|
278,037 |
<p>I'm working with a third party to integrate some of our systems with theirs and they provide us with a SOAP interface to make certain requests and changes in their connected systems. The problem for me is that they do not supply a WSDL-file for me to work against. If I had a WSDL-file it would be a simple matter just to run the supplied .NET command (wsdl.exe) and generate a proxy class to interact with the service.</p>
<p>Is there an "easy" way to do this without a WSDL-file? I have all the functions that we can access and what parameters I need to send and what I should expect in return.</p>
<p>Is it common to have a SOAP-service without WSDL-files? (I'm asking this since we're going to add more external systems into the mix in the future)</p>
<p>Has anyone done a proxy-class or any other form of client against a WDSL-less service and have any good pointers on how to do it?</p>
|
[
{
"answer_id": 278072,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't built a SOAP interface without access to a WSDL file, but the format is <a href=\"http://www.w3.org/TR/wsdl\" rel=\"nofollow noreferrer\">fairly well-documented</a>. Your best bet might be to create a simplified WSDL file of your own that reflects what you know of the service you're subscribing to....</p>\n\n<p>If you decide to go this route, an <a href=\"https://stackoverflow.com/questions/152023/wsdl-validator\">existing stackoverflow question</a> points at some tools for validating your WSDL.</p>\n"
},
{
"answer_id": 278074,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 2,
"selected": false,
"text": "<p>If you write a class that derives from <code>System.Web.Services.Protocols.SoapHttpClientProtocol</code> (and has the correct attributes, e.g., <code>WebServiceBinding</code>, <code>SoapDocumentMethod</code>, etc. applied to it and its methods), you can fairly easily call SOAP methods without needing the WSDL file.</p>\n\n<p>The easiest way to do this would probably be to write your own ASP.NET web service that replicates the third party's SOAP API, generate a proxy class from it, then manually edit the file to ensure that the URL, namespaces, method names, parameter types, etc. are correct for the third-party API you want to call.</p>\n"
},
{
"answer_id": 413347,
"author": "SpoBo",
"author_id": 48417,
"author_profile": "https://Stackoverflow.com/users/48417",
"pm_score": 1,
"selected": false,
"text": "<p>the code here is in VB.NET but I think you'll get the idea. The following is a client that invokes the 'processConfirmation' method and it expects a response (MyBase.SendRequestResponse).</p>\n\n<pre><code>Imports Microsoft.Web.Services3\nImports Microsoft.Web.Services3.Addressing\nImports Microsoft.Web.Services3.Messaging\n\nNamespace Logic\n Public Class HTTPClient\n Inherits Soapclient\n\n Sub New(ByVal destination As EndpointReference)\n MyBase.Destination = destination\n End Sub\n\n <SoapMethod(\"processConfirmation\")> _\n Public Function processConfirmation(ByVal envelope As SoapEnvelope) As SoapEnvelope\n Return MyBase.SendRequestResponse(\"processConfirmation\", envelope)\n End Function\n End Class\nEnd Namespace\n</code></pre>\n\n<p>And you use it by doing the following:</p>\n\n<pre><code>Dim hc As New HTTPClient(New Microsoft.Web.Services3.Addressing.EndpointReference(New System.Uri(\"http://whatever.srv\")))\n\nDim envelope As New Microsoft.Web.Services3.SoapEnvelope\nDim doc As New Xml.XmlDocument\ndoc.LoadXml(\"<hey>there</hey>\")\nenvelope.SetBodyObject(doc)\n\nDim return_envelope As Microsoft.Web.Services3.SoapEnvelope = hc.processConfirmation(envelope)\n</code></pre>\n\n<p>I think this should work .... success!</p>\n"
},
{
"answer_id": 3708132,
"author": "Manikant Thakur",
"author_id": 447255,
"author_profile": "https://Stackoverflow.com/users/447255",
"pm_score": 3,
"selected": false,
"text": "<pre><code>string EndPoints = \"http://203.189.91.127:7777/services/spm/spm\";\n\nstring New_Xml_Request_String = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"><soapenv:Body><OTA_AirLowFareSearchRQ EchoToken=\\\"0\\\" SequenceNmbr=\\\"0\\\" TransactionIdentifier=\\\"0\\\" xmlns=\\\"http://www.opentravel.org/OTA/2003/05\\\"><POS xmlns=\\\"http://www.opentravel.org/OTA/2003/05\\\"><Source AgentSine=\\\"\\\" PseudoCityCode=\\\"NPCK\\\" TerminalID=\\\"1\\\"><RequestorID ID=\\\"\\\"/></Source><YatraRequests><YatraRequest DoNotHitCache=\\\"true\\\" DoNotCache=\\\"false\\\" MidOfficeAgentID=\\\"\\\" AffiliateID=\\\"\\\" YatraRequestTypeCode=\\\"SMPA\\\"/></YatraRequests></POS><TravelerInfoSummary><AirTravelerAvail><PassengerTypeQuantity Code=\\\"ADT\\\" Quantity=\\\"1\\\"/><PassengerTypeQuantity Code=\\\"CHD\\\" Quantity=\\\"1\\\"/><PassengerTypeQuantity Code=\\\"INF\\\" Quantity=\\\"1\\\"/></AirTravelerAvail></TravelerInfoSummary> <SpecificFlightInfo><Airline Code=\\\"\\\"/></SpecificFlightInfo><OriginDestinationInformation><DepartureDateTime>\" + DateTime.Now.ToString(\"o\").Remove(19, 14) + \"</DepartureDateTime><OriginLocation CodeContext=\\\"IATA\\\" LocationCode=\\\"DEL\\\">\" + Source + \"</OriginLocation><DestinationLocation CodeContext=\\\"IATA\\\" LocationCode=\\\"BOM\\\">\" + Destincation + \"</DestinationLocation></OriginDestinationInformation><TravelPreferences><CabinPref Cabin=\\\"Economy\\\"/></TravelPreferences></OTA_AirLowFareSearchRQ></soapenv:Body></soapenv:Envelope>\";\n\n\n protected string HttpSOAPRequest_Test(string xmlfile, string proxy)\n {\n try\n {\n System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\n doc.InnerXml = xmlfile.ToString();\n HttpWebRequest req = (HttpWebRequest)WebRequest.Create(EndPoints);\n req.Timeout = 100000000;\n if (proxy != null)\n req.Proxy = new WebProxy(proxy, true);\n req.Headers.Add(\"SOAPAction\", \"\");\n req.ContentType = \"application/soap+xml;charset=\\\"utf-8\\\"\";\n req.Accept = \"application/x-www-form-urlencoded\"; //\"application/soap+xml\";\n req.Method = \"POST\";\n Stream stm = req.GetRequestStream();\n doc.Save(stm);\n stm.Close();\n WebResponse resp = req.GetResponse();\n stm = resp.GetResponseStream();\n StreamReader r = new StreamReader(stm);\n string myd = r.ReadToEnd();\n return myd;\n }\n\n catch (Exception se)\n {\n throw new Exception(\"Error Occurred in AuditAdapter.getXMLDocumentFromXMLTemplate()\", se);\n }\n }\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26746/"
] |
I'm working with a third party to integrate some of our systems with theirs and they provide us with a SOAP interface to make certain requests and changes in their connected systems. The problem for me is that they do not supply a WSDL-file for me to work against. If I had a WSDL-file it would be a simple matter just to run the supplied .NET command (wsdl.exe) and generate a proxy class to interact with the service.
Is there an "easy" way to do this without a WSDL-file? I have all the functions that we can access and what parameters I need to send and what I should expect in return.
Is it common to have a SOAP-service without WSDL-files? (I'm asking this since we're going to add more external systems into the mix in the future)
Has anyone done a proxy-class or any other form of client against a WDSL-less service and have any good pointers on how to do it?
|
```
string EndPoints = "http://203.189.91.127:7777/services/spm/spm";
string New_Xml_Request_String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body><OTA_AirLowFareSearchRQ EchoToken=\"0\" SequenceNmbr=\"0\" TransactionIdentifier=\"0\" xmlns=\"http://www.opentravel.org/OTA/2003/05\"><POS xmlns=\"http://www.opentravel.org/OTA/2003/05\"><Source AgentSine=\"\" PseudoCityCode=\"NPCK\" TerminalID=\"1\"><RequestorID ID=\"\"/></Source><YatraRequests><YatraRequest DoNotHitCache=\"true\" DoNotCache=\"false\" MidOfficeAgentID=\"\" AffiliateID=\"\" YatraRequestTypeCode=\"SMPA\"/></YatraRequests></POS><TravelerInfoSummary><AirTravelerAvail><PassengerTypeQuantity Code=\"ADT\" Quantity=\"1\"/><PassengerTypeQuantity Code=\"CHD\" Quantity=\"1\"/><PassengerTypeQuantity Code=\"INF\" Quantity=\"1\"/></AirTravelerAvail></TravelerInfoSummary> <SpecificFlightInfo><Airline Code=\"\"/></SpecificFlightInfo><OriginDestinationInformation><DepartureDateTime>" + DateTime.Now.ToString("o").Remove(19, 14) + "</DepartureDateTime><OriginLocation CodeContext=\"IATA\" LocationCode=\"DEL\">" + Source + "</OriginLocation><DestinationLocation CodeContext=\"IATA\" LocationCode=\"BOM\">" + Destincation + "</DestinationLocation></OriginDestinationInformation><TravelPreferences><CabinPref Cabin=\"Economy\"/></TravelPreferences></OTA_AirLowFareSearchRQ></soapenv:Body></soapenv:Envelope>";
protected string HttpSOAPRequest_Test(string xmlfile, string proxy)
{
try
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.InnerXml = xmlfile.ToString();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(EndPoints);
req.Timeout = 100000000;
if (proxy != null)
req.Proxy = new WebProxy(proxy, true);
req.Headers.Add("SOAPAction", "");
req.ContentType = "application/soap+xml;charset=\"utf-8\"";
req.Accept = "application/x-www-form-urlencoded"; //"application/soap+xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
string myd = r.ReadToEnd();
return myd;
}
catch (Exception se)
{
throw new Exception("Error Occurred in AuditAdapter.getXMLDocumentFromXMLTemplate()", se);
}
}
```
|
278,039 |
<p>I have a timely operation that runs on a background thread. While running, I currently put the cursor in a wait state:</p>
<pre><code>Mouse.OverrideCursor = Cursors.Wait
</code></pre>
<p>I just implemented a feature that allows the user to click a "Cancel" button if they're tired of waiting. However, some users may not realize they can do this (despite the cancel button being the only active control during the process) because they mouse cursor is an hourglass.</p>
<p>I've seen programs use a cursor that shows the hourglass and has an arrow pointer attached as well. How to I set the mouse cursor to this state? I looked through the .NET documentation and could not find this cursor.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 278050,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "<p>I think you should use a \"AppStarting\" property of \"System.Windows.Forms.Cursros\" class.</p>\n"
},
{
"answer_id": 278052,
"author": "Martin",
"author_id": 8157,
"author_profile": "https://Stackoverflow.com/users/8157",
"pm_score": 5,
"selected": true,
"text": "<pre><code>Me.Cursor = Cursors.AppStarting\n</code></pre>\n"
},
{
"answer_id": 278058,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect the \"mouse cursor + hourglass\" is <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.cursors.appstarting.aspx\" rel=\"nofollow noreferrer\">Cursors.AppStarting</a>. Of course you'd ideally want the normal hourglass for the rest of the UI, and that cursor just for the cancel button, but...</p>\n"
},
{
"answer_id": 278146,
"author": "Javier Suero Santos",
"author_id": 34432,
"author_profile": "https://Stackoverflow.com/users/34432",
"pm_score": 0,
"selected": false,
"text": "<p>May be you should also change the background colour (or some graphical clue) of the cancel button in order to make the user realize the cancelation is posible .</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
I have a timely operation that runs on a background thread. While running, I currently put the cursor in a wait state:
```
Mouse.OverrideCursor = Cursors.Wait
```
I just implemented a feature that allows the user to click a "Cancel" button if they're tired of waiting. However, some users may not realize they can do this (despite the cancel button being the only active control during the process) because they mouse cursor is an hourglass.
I've seen programs use a cursor that shows the hourglass and has an arrow pointer attached as well. How to I set the mouse cursor to this state? I looked through the .NET documentation and could not find this cursor.
Thanks!
|
```
Me.Cursor = Cursors.AppStarting
```
|
278,046 |
<p>Are there any free tools to help simplify working with an NHibernate project in .NET 3.5? Primarily, I'm looking for some kind of code and config file generator to automate some of the more tedious parts of working with NHibernate.</p>
|
[
{
"answer_id": 278065,
"author": "Mark Struzinski",
"author_id": 1284,
"author_profile": "https://Stackoverflow.com/users/1284",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://altinoren.com/activewriter/\" rel=\"nofollow noreferrer\">ActiveWriter</a> is a plugin to Visual Studio that generates some files for NHibernate, but I haven't had a chance to dig into it yet.</p>\n"
},
{
"answer_id": 278114,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.mygenerationsoftware.com/portal/Home/tabid/36/Default.aspx\" rel=\"nofollow noreferrer\">MyGeneration</a> has some <a href=\"http://www.mygenerationsoftware.com/templatelibrary/default.aspx\" rel=\"nofollow noreferrer\">nHibernate tempates</a> for code generation.</p>\n\n<p>There used to be some for the free version of Code-Smith too, but I don't think they have been updated in a while.</p>\n"
},
{
"answer_id": 278154,
"author": "Christian Dalager",
"author_id": 11239,
"author_profile": "https://Stackoverflow.com/users/11239",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://ayende.com/Blog/archive/2007/06/02/NHibernate-Query-Analyzer-for-NHibernate-1.2-GA.aspx\" rel=\"nofollow noreferrer\">NHibernate Query Analyzer</a> is a must for constructing queries. It's not for configuration, I know, but a must when trying to get your head around HQL.</p>\n"
},
{
"answer_id": 278193,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "<p>What about an <a href=\"http://www.castleproject.org/activerecord/index.html\" rel=\"nofollow noreferrer\">active record implementation</a> with attribute-based definition on top of nhibernate?</p>\n"
},
{
"answer_id": 280349,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://code.google.com/p/fluent-nhibernate/\" rel=\"nofollow noreferrer\">Fluent-NHibernate</a> presents an alternative way of writing your mapping, that for example is more refactor friendly than the standard XML approach.</p>\n\n<p>Example:</p>\n\n<pre><code>public CustomerMap : ClassMap<Customer>\n{\n public CustomerMap()\n {\n Id(x => x.ID);\n Map(x => x.Name);\n Map(x => x.Credit);\n HasMany<Product>(x => x.Products)\n .AsBag();\n Component<Address>(x => x.Address, m => \n { \n m.Map(x => x.AddressLine1); \n m.Map(x => x.AddressLine2); \n m.Map(x => x.CityName); \n m.Map(x => x.CountryName); \n });\n}\n</code></pre>\n"
},
{
"answer_id": 286144,
"author": "David P",
"author_id": 13145,
"author_profile": "https://Stackoverflow.com/users/13145",
"pm_score": 2,
"selected": false,
"text": "<p>Keep an eye out for Oren (Ayende)'s NHhibernate Profiler:</p>\n\n<p><a href=\"http://ayende.com/Blog/archive/2008/11/04/nh-prof-a-guided-tour.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2008/11/04/nh-prof-a-guided-tour.aspx</a></p>\n\n<p>It is not yet released but it looks very promising.</p>\n"
},
{
"answer_id": 398947,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>David Hayden has put together <a href=\"http://www.olegsych.com/2007/12/text-template-transformation-toolkit/\" rel=\"nofollow noreferrer\">T4 Templates</a> that generate sample Fluent NHibernate Mapping Classes.</p>\n\n<p><a href=\"http://codebetter.com/blogs/david.hayden/archive/2008/12/14/t4-templates-for-fluent-nhibernate.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/david.hayden/archive/2008/12/14/t4-templates-for-fluent-nhibernate.aspx</a></p>\n"
},
{
"answer_id": 2522734,
"author": "Guy Fomi",
"author_id": 302454,
"author_profile": "https://Stackoverflow.com/users/302454",
"pm_score": 2,
"selected": false,
"text": "<p>what about NConstruct Lite, a small powerfull tool to generating mapping files and Entities...</p>\n"
},
{
"answer_id": 3968129,
"author": "pvolders",
"author_id": 480421,
"author_profile": "https://Stackoverflow.com/users/480421",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at: <a href=\"http://www.dpulpo.com\" rel=\"nofollow\">dPulpo</a>, a datalayer generation tool that generates NHibernate mapping files, C# entity classes and your SQL database. There is a Visual Studio plugin and it's currently in beta and free for download.</p>\n"
},
{
"answer_id": 6018103,
"author": "Myles J",
"author_id": 236573,
"author_profile": "https://Stackoverflow.com/users/236573",
"pm_score": 0,
"selected": false,
"text": "<p>The latest version of LLBLGen is able to generate sample Fluent NHibernate Mapping Classes and entities.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
Are there any free tools to help simplify working with an NHibernate project in .NET 3.5? Primarily, I'm looking for some kind of code and config file generator to automate some of the more tedious parts of working with NHibernate.
|
[Fluent-NHibernate](http://code.google.com/p/fluent-nhibernate/) presents an alternative way of writing your mapping, that for example is more refactor friendly than the standard XML approach.
Example:
```
public CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
Id(x => x.ID);
Map(x => x.Name);
Map(x => x.Credit);
HasMany<Product>(x => x.Products)
.AsBag();
Component<Address>(x => x.Address, m =>
{
m.Map(x => x.AddressLine1);
m.Map(x => x.AddressLine2);
m.Map(x => x.CityName);
m.Map(x => x.CountryName);
});
}
```
|
278,062 |
<p>I've got a cool piece of code taken from a VC++ project which gets complete information of the hard disk drive WITHOUT using WMI (since WMI has got its own problems).</p>
<p>I ask those of you who are comfortable with API functions to try to convert this VB6 code into VB.NET (or C#) and help A LOT of people who are in great need of this utility class.</p>
<p>I've spent lots of time and searched the entire net to find ways to get the actual model and serial number of HDD and eventually found this one, if only it were in .NET...</p>
<p>Here is the code and sorry about its formatting problems, just paste it into VB6 IDE:</p>
<pre><code>Option Explicit
''// Antonio Giuliana, 2001-2003
''// Costanti per l'individuazione della versione di OS
Private Const VER_PLATFORM_WIN32S = 0
Private Const VER_PLATFORM_WIN32_WINDOWS = 1
Private Const VER_PLATFORM_WIN32_NT = 2
''// Costanti per la comunicazione con il driver IDE
Private Const DFP_RECEIVE_DRIVE_DATA = &H7C088
''// Costanti per la CreateFile
Private Const FILE_SHARE_READ = &H1
Private Const FILE_SHARE_WRITE = &H2
Private Const GENERIC_READ = &H80000000
Private Const GENERIC_WRITE = &H40000000
Private Const OPEN_EXISTING = 3
Private Const CREATE_NEW = 1
''// Enumerazione dei comandi per la CmnGetHDData
Private Enum HDINFO
HD_MODEL_NUMBER
HD_SERIAL_NUMBER
HD_FIRMWARE_REVISION
End Enum
''// Struttura per l'individuazione della versione di OS
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
''// Struttura per il campo irDriveRegs della struttura SENDCMDINPARAMS
Private Type IDEREGS
bFeaturesReg As Byte
bSectorCountReg As Byte
bSectorNumberReg As Byte
bCylLowReg As Byte
bCylHighReg As Byte
bDriveHeadReg As Byte
bCommandReg As Byte
bReserved As Byte
End Type
''// Struttura per l'I/O dei comandi al driver IDE
Private Type SENDCMDINPARAMS
cBufferSize As Long
irDriveRegs As IDEREGS
bDriveNumber As Byte
bReserved(1 To 3) As Byte
dwReserved(1 To 4) As Long
End Type
''// Struttura per il campo DStatus della struttura SENDCMDOUTPARAMS
Private Type DRIVERSTATUS
bDriveError As Byte
bIDEStatus As Byte
bReserved(1 To 2) As Byte
dwReserved(1 To 2) As Long
End Type
''// Struttura per l'I/O dei comandi al driver IDE
Private Type SENDCMDOUTPARAMS
cBufferSize As Long
DStatus As DRIVERSTATUS ''// ovvero DriverStatus
bBuffer(1 To 512) As Byte
End Type
''// Per ottenere la versione del SO
Private Declare Function GetVersionEx _
Lib "kernel32" Alias "GetVersionExA" _
(lpVersionInformation As OSVERSIONINFO) As Long
''// Per ottenere un handle al device IDE
Private Declare Function CreateFile _
Lib "kernel32" Alias "CreateFileA" _
(ByVal lpFileName As String, _
ByVal dwDesiredAccess As Long, _
ByVal dwShareMode As Long, _
ByVal lpSecurityAttributes As Long, _
ByVal dwCreationDisposition As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal hTemplateFile As Long) As Long
''// Per chiudere l'handle del device IDE
Private Declare Function CloseHandle _
Lib "kernel32" _
(ByVal hObject As Long) As Long
''// Per comunicare con il driver IDE
Private Declare Function DeviceIoControl _
Lib "kernel32" _
(ByVal hDevice As Long, _
ByVal dwIoControlCode As Long, _
lpInBuffer As Any, _
ByVal nInBufferSize As Long, _
lpOutBuffer As Any, _
ByVal nOutBufferSize As Long, _
lpBytesReturned As Long, _
ByVal lpOverlapped As Long) As Long
''// Per azzerare buffer di scambio dati
Private Declare Sub ZeroMemory _
Lib "kernel32" Alias "RtlZeroMemory" _
(dest As Any, _
ByVal numBytes As Long)
''// Per copiare porzioni di memoria
Private Declare Sub CopyMemory _
Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
Private Declare Function GetLastError _
Lib "kernel32" () As Long
Private mvarCurrentDrive As Byte ''// Drive corrente
Private mvarPlatform As String ''// Piattaforma usata
Public Property Get Copyright() As String
''// Copyright
Copyright = "HDSN Vrs. 1.00, (C) Antonio Giuliana, 2001-2003"
End Property
''// Metodo GetModelNumber
Public Function GetModelNumber() As String
''// Ottiene il ModelNumber
GetModelNumber = CmnGetHDData(HD_MODEL_NUMBER)
End Function
''// Metodo GetSerialNumber
Public Function GetSerialNumber() As String
''// Ottiene il SerialNumber
GetSerialNumber = CmnGetHDData(HD_SERIAL_NUMBER)
End Function
''// Metodo GetFirmwareRevision
Public Function GetFirmwareRevision() As String
''// Ottiene la FirmwareRevision
GetFirmwareRevision = CmnGetHDData(HD_FIRMWARE_REVISION)
End Function
''// Proprieta' CurrentDrive
Public Property Let CurrentDrive(ByVal vData As Byte)
''// Controllo numero di drive fisico IDE
If vData < 0 Or vData > 3 Then
Err.Raise 10000, , "Illegal drive number" ''// IDE drive 0..3
End If
''// Nuovo drive da considerare
mvarCurrentDrive = vData
End Property
''// Proprieta' CurrentDrive
Public Property Get CurrentDrive() As Byte
''// Restituisce drive fisico corrente (IDE 0..3)
CurrentDrive = mvarCurrentDrive
End Property
''// Proprieta' Platform
Public Property Get Platform() As String
''// Restituisce tipo OS
Platform = mvarPlatform
End Property
Private Sub Class_Initialize()
''// Individuazione del tipo di OS
Dim OS As OSVERSIONINFO
OS.dwOSVersionInfoSize = Len(OS)
Call GetVersionEx(OS)
mvarPlatform = "Unk"
Select Case OS.dwPlatformId
Case Is = VER_PLATFORM_WIN32S
mvarPlatform = "32S" ''// Win32S
Case Is = VER_PLATFORM_WIN32_WINDOWS
If OS.dwMinorVersion = 0 Then
mvarPlatform = "W95" ''// Win 95
Else
mvarPlatform = "W98" ''// Win 98
End If
Case Is = VER_PLATFORM_WIN32_NT
mvarPlatform = "WNT" ''// Win NT/2000
End Select
End Sub
Private Function CmnGetHDData(hdi As HDINFO) As String
''// Rilevazione proprieta' IDE
Dim bin As SENDCMDINPARAMS
Dim bout As SENDCMDOUTPARAMS
Dim hdh As Long
Dim br As Long
Dim ix As Long
Dim hddfr As Long
Dim hddln As Long
Dim s As String
Select Case hdi ''// Selezione tipo caratteristica richiesta
Case HD_MODEL_NUMBER
hddfr = 55 ''// Posizione nel buffer del ModelNumber
hddln = 40 ''// Lunghezza nel buffer del ModelNumber
Case HD_SERIAL_NUMBER
hddfr = 21 ''// Posizione nel buffer del SerialNumber
hddln = 20 ''// Lunghezza nel buffer del SerialNumber
Case HD_FIRMWARE_REVISION
hddfr = 47 ''// Posizione nel buffer del FirmwareRevision
hddln = 8 ''// Lunghezza nel buffer del FirmwareRevision
Case Else
Err.Raise 10001, "Illegal HD Data type"
End Select
Select Case mvarPlatform
Case "WNT"
''// Per Win NT/2000 apertura handle al drive fisico
hdh = CreateFile("\\.\PhysicalDrive" & mvarCurrentDrive, _
GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, _
0, OPEN_EXISTING, 0, 0)
Case "W95", "W98"
''// Per Win 9X apertura handle al driver SMART
''// (in \WINDOWS\SYSTEM da spostare in \WINDOWS\SYSTEM\IOSUBSYS)
''// che comunica con il driver IDE
hdh = CreateFile("\\.\Smartvsd", _
0, 0, 0, CREATE_NEW, 0, 0)
Case Else
''// Piattaforma non supportata (Win32S)
Err.Raise 10002, , "Illegal platform (only WNT, W98 or W95)"
End Select
''// Controllo validità handle
If hdh = 0 Then
Err.Raise 10003, , "Error on CreateFile"
End If
''// Azzeramento strutture per l'I/O da driver
ZeroMemory bin, Len(bin)
ZeroMemory bout, Len(bout)
''// Preparazione parametri struttura di richiesta al driver
With bin
.bDriveNumber = mvarCurrentDrive
.cBufferSize = 512
With .irDriveRegs
If (mvarCurrentDrive And 1) Then
.bDriveHeadReg = &HB0
Else
.bDriveHeadReg = &HA0
End If
.bCommandReg = &HEC
.bSectorCountReg = 1
.bSectorNumberReg = 1
End With
End With
''// Richiesta al driver
DeviceIoControl hdh, DFP_RECEIVE_DRIVE_DATA, _
bin, Len(bin), bout, Len(bout), br, 0
''// Formazione stringa di risposta
''// da buffer di uscita
''// L'ordine dei byte e' invertito
s = ""
For ix = hddfr To hddfr + hddln - 1 Step 2
If bout.bBuffer(ix + 1) = 0 Then Exit For
s = s & Chr(bout.bBuffer(ix + 1))
If bout.bBuffer(ix) = 0 Then Exit For
s = s & Chr(bout.bBuffer(ix))
Next ix
''// Chiusura handle
CloseHandle hdh
''// Restituzione informazione richiesta
CmnGetHDData = Trim(s)
End Function
</code></pre>
|
[
{
"answer_id": 278124,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>That's a lot of code to wade through for someone who doesn't understand the spoken language used in the comments. </p>\n\n<p>I will says this: Anywhere in that code you see the <code>Type</code> keyword you probably want to use <code>Structure</code> instead, the syntax used for Properties in .Net is a little different, function calls require parentheses, and VB.Net doesn't have an 'Any' type (maybe <code>System.IntPtr</code> instead? not sure).</p>\n\n<p>Most of the rest of the syntax in VB.Net is the same, and so you might have better luck making the fixes I've already mentioned and then addressing each error (or type of error) you get when building the resulting code individually.</p>\n"
},
{
"answer_id": 278134,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah, I know VB6 but the problem is with the API function declarations and the attributes required to pass those structures (types) to them. That's where I don't have the time to spend!\nIf you have an automated VB6 to VB.NET tool and VB6 itself, please save the code as a VB6 project and do convert the code. I don't have my VB6 around.</p>\n"
},
{
"answer_id": 278167,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry I don't have time to convert it for you, but if nobody else comes up with the code, you could do worse than take a look at <a href=\"http://www.pinvoke.net\" rel=\"nofollow noreferrer\">http://www.pinvoke.net</a>. Your VB6 code has to call Windows API functions to do the work, and VB.NET code has to do the same. It will call the same API functions.</p>\n\n<p>For example, <a href=\"http://www.pinvoke.net/default.aspx/kernel32/DeviceIoControl.html\" rel=\"nofollow noreferrer\">here</a> is the page for DeviceIoControl.</p>\n\n<p>But if you wait long enough, somebody else might just have the code to hand :-)</p>\n"
},
{
"answer_id": 278187,
"author": "masfenix",
"author_id": 36212,
"author_profile": "https://Stackoverflow.com/users/36212",
"pm_score": -1,
"selected": false,
"text": "<p>You can get this data of WMI. Let me get you an example</p>\n"
},
{
"answer_id": 278195,
"author": "masfenix",
"author_id": 36212,
"author_profile": "https://Stackoverflow.com/users/36212",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Try\nDim Searcher_P As New ManagementObjectSearcher(\"root\\CIMV2\", \"SELECT * FROM Win32_PhysicalMedia\")\nFor Each queryObj As ManagementObject In Searcher_P.Get()\nIf queryObj(\"SerialNumber\").ToString.Trim = \"Y2S0RKFE\" Then\nMe.Cursor = Cursors.Default\nReturn True\nEnd If\nNext\nCatch ex As Exception\nMessageBox.Show(\"An error occurred while querying for WMI data: Win32_PhysicalMedia \" & ex.Message)\nEnd Try\n\nTry\nDim Searcher_L As New ManagementObjectSearcher(\"root\\CIMV2\", \"SELECT * FROM Win32_LogicalDisk WHERE DeviceID = 'C:'\")\nFor Each queryObj As ManagementObject In Searcher_L.Get()\nIf queryObj(\"VolumeSerialNumber\").ToString.Trim = \"226C1A0B\" Then\nMe.Cursor = Cursors.Default\nReturn True\nEnd If\nNext\nCatch ex As Exception\nMessageBox.Show(\"An error occurred while querying for WMI data: VolumeSerialNumber \" & ex.Message)\nReturn False\nEnd Try\n</code></pre>\n"
},
{
"answer_id": 287270,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I found it! Here is the equivalent VB.NET code. It's not exactly the converted version of the VB6 code, but does the same thing. Enjoy!</p>\n\n<pre><code>Public Class HDDInfo\n#Region \" Declatrations \"\nPrivate Declare Function CreateFile Lib \"kernel32\" Alias \"CreateFileA\" (ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal lpSecurityAttributes As Integer, ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer, ByVal hTemplateFile As Integer) As Integer\n<System.Runtime.InteropServices.DllImport(\"kernel32.dll\")> _\nPrivate Shared Function CloseHandle(ByVal hObject As Integer) As Integer\nEnd Function\n<System.Runtime.InteropServices.DllImport(\"kernel32.dll\")> _\nPrivate Shared Function DeviceIoControl(ByVal hDevice As Integer, ByVal dwIoControlCode As Integer, <[In](), Out()> ByVal lpInBuffer As SENDCMDINPARAMS, ByVal lpInBufferSize As Integer, <[In](), Out()> ByVal lpOutBuffer As SENDCMDOUTPARAMS, ByVal lpOutBufferSize As Integer, _\n ByRef lpBytesReturned As Integer, ByVal lpOverlapped As Integer) As Integer\nEnd Function\nPrivate Const FILE_SHARE_READ As Short = &H1\nPrivate Const FILE_SHARE_WRITE As Short = &H2\nPrivate Const GENERIC_READ As Integer = &H80000000\nPrivate Const GENERIC_WRITE As Integer = &H40000000\nPrivate Const OPEN_EXISTING As Short = 3\nPrivate Const CREATE_NEW As Short = 1\nPrivate Const VER_PLATFORM_WIN32_NT As Integer = 2\nPrivate Const DFP_RECEIVE_DRIVE_DATA As Integer = &H7C088\nPrivate Const INVALID_HANDLE_VALUE As Integer = -1\n#End Region\n#Region \" Classes \"\n<StructLayout(LayoutKind.Sequential, Size:=8)> _\nPrivate Class IDEREGS\n Public Features As Byte\n Public SectorCount As Byte\n Public SectorNumber As Byte\n Public CylinderLow As Byte\n Public CylinderHigh As Byte\n Public DriveHead As Byte\n Public Command As Byte\n Public Reserved As Byte\nEnd Class\n<StructLayout(LayoutKind.Sequential, Size:=32)> _\nPrivate Class SENDCMDINPARAMS\n Public BufferSize As Integer\n Public DriveRegs As IDEREGS\n Public DriveNumber As Byte\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)> _\n Public Reserved As Byte()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=4)> _\n Public Reserved2 As Integer()\n Public Sub New()\n DriveRegs = New IDEREGS()\n Reserved = New Byte(2) {}\n Reserved2 = New Integer(3) {}\n End Sub\nEnd Class\n<StructLayout(LayoutKind.Sequential, Size:=12)> _\nPrivate Class DRIVERSTATUS\n Public DriveError As Byte\n Public IDEStatus As Byte\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _\n Public Reserved As Byte()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _\n Public Reserved2 As Integer()\n Public Sub New()\n Reserved = New Byte(1) {}\n Reserved2 = New Integer(1) {}\n End Sub\nEnd Class\n<StructLayout(LayoutKind.Sequential)> _\nPrivate Class IDSECTOR\n Public GenConfig As Short\n Public NumberCylinders As Short\n Public Reserved As Short\n Public NumberHeads As Short\n Public BytesPerTrack As Short\n Public BytesPerSector As Short\n Public SectorsPerTrack As Short\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)> _\n Public VendorUnique As Short()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)> _\n Public SerialNumber As Char()\n Public BufferClass As Short\n Public BufferSize As Short\n Public ECCSize As Short\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=8)> _\n Public FirmwareRevision As Char()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=40)> _\n Public ModelNumber As Char()\n Public MoreVendorUnique As Short\n Public DoubleWordIO As Short\n Public Capabilities As Short\n Public Reserved1 As Short\n Public PIOTiming As Short\n Public DMATiming As Short\n Public BS As Short\n Public NumberCurrentCyls As Short\n Public NumberCurrentHeads As Short\n Public NumberCurrentSectorsPerTrack As Short\n Public CurrentSectorCapacity As Integer\n Public MultipleSectorCapacity As Short\n Public MultipleSectorStuff As Short\n Public TotalAddressableSectors As Integer\n Public SingleWordDMA As Short\n Public MultiWordDMA As Short\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=382)> _\n Public Reserved2 As Byte()\nEnd Class\n<StructLayout(LayoutKind.Sequential)> _\nPrivate Class SENDCMDOUTPARAMS\n Public BufferSize As Integer\n Public Status As DRIVERSTATUS\n Public IDS As IDSECTOR\n Public Sub New()\n Status = New DRIVERSTATUS()\n IDS = New IDSECTOR()\n End Sub\nEnd Class\n#End Region\n#Region \" Methods and Functions \"\nPrivate Shared Function SwapChars(ByVal chars As Char()) As String\n For i As Integer = 0 To chars.Length - 2 Step 2\n Dim t As Char\n t = chars(i)\n chars(i) = chars(i + 1)\n chars(i + 1) = t\n Next\n Dim s As New String(chars)\n Return s\nEnd Function\nPublic Shared Function GetHDDInfoString() As String\n Dim serialNumber As String = \" \", model As String = \" \", firmware As String = \" \"\n Dim handle As Integer, returnSize As Integer = 0\n Dim driveNumber As Integer = 0\n Dim sci As New SENDCMDINPARAMS()\n Dim sco As New SENDCMDOUTPARAMS()\n\n If Environment.OSVersion.Platform = PlatformID.Win32NT Then\n handle = CreateFile(\"\\\\.\\PhysicalDrive\" & \"0\", GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n Else\n handle = CreateFile(\"\\\\.\\Smartvsd\", 0, 0, 0, CREATE_NEW, 0, 0)\n End If\n If handle <> INVALID_HANDLE_VALUE Then\n sci.DriveNumber = CByte(driveNumber)\n sci.BufferSize = Marshal.SizeOf(sco)\n sci.DriveRegs.DriveHead = CByte((&HA0 Or driveNumber << 4))\n sci.DriveRegs.Command = &HEC\n sci.DriveRegs.SectorCount = 1\n sci.DriveRegs.SectorNumber = 1\n If DeviceIoControl(handle, DFP_RECEIVE_DRIVE_DATA, sci, Marshal.SizeOf(sci), sco, Marshal.SizeOf(sco), _\n returnSize, 0) <> 0 Then\n serialNumber = SwapChars(sco.IDS.SerialNumber)\n model = SwapChars(sco.IDS.ModelNumber)\n firmware = SwapChars(sco.IDS.FirmwareRevision)\n End If\n CloseHandle(handle)\n End If\n Return model.Trim & \" \" & serialNumber.Trim\nEnd Function\n#End Region\nEnd Class\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've got a cool piece of code taken from a VC++ project which gets complete information of the hard disk drive WITHOUT using WMI (since WMI has got its own problems).
I ask those of you who are comfortable with API functions to try to convert this VB6 code into VB.NET (or C#) and help A LOT of people who are in great need of this utility class.
I've spent lots of time and searched the entire net to find ways to get the actual model and serial number of HDD and eventually found this one, if only it were in .NET...
Here is the code and sorry about its formatting problems, just paste it into VB6 IDE:
```
Option Explicit
''// Antonio Giuliana, 2001-2003
''// Costanti per l'individuazione della versione di OS
Private Const VER_PLATFORM_WIN32S = 0
Private Const VER_PLATFORM_WIN32_WINDOWS = 1
Private Const VER_PLATFORM_WIN32_NT = 2
''// Costanti per la comunicazione con il driver IDE
Private Const DFP_RECEIVE_DRIVE_DATA = &H7C088
''// Costanti per la CreateFile
Private Const FILE_SHARE_READ = &H1
Private Const FILE_SHARE_WRITE = &H2
Private Const GENERIC_READ = &H80000000
Private Const GENERIC_WRITE = &H40000000
Private Const OPEN_EXISTING = 3
Private Const CREATE_NEW = 1
''// Enumerazione dei comandi per la CmnGetHDData
Private Enum HDINFO
HD_MODEL_NUMBER
HD_SERIAL_NUMBER
HD_FIRMWARE_REVISION
End Enum
''// Struttura per l'individuazione della versione di OS
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
''// Struttura per il campo irDriveRegs della struttura SENDCMDINPARAMS
Private Type IDEREGS
bFeaturesReg As Byte
bSectorCountReg As Byte
bSectorNumberReg As Byte
bCylLowReg As Byte
bCylHighReg As Byte
bDriveHeadReg As Byte
bCommandReg As Byte
bReserved As Byte
End Type
''// Struttura per l'I/O dei comandi al driver IDE
Private Type SENDCMDINPARAMS
cBufferSize As Long
irDriveRegs As IDEREGS
bDriveNumber As Byte
bReserved(1 To 3) As Byte
dwReserved(1 To 4) As Long
End Type
''// Struttura per il campo DStatus della struttura SENDCMDOUTPARAMS
Private Type DRIVERSTATUS
bDriveError As Byte
bIDEStatus As Byte
bReserved(1 To 2) As Byte
dwReserved(1 To 2) As Long
End Type
''// Struttura per l'I/O dei comandi al driver IDE
Private Type SENDCMDOUTPARAMS
cBufferSize As Long
DStatus As DRIVERSTATUS ''// ovvero DriverStatus
bBuffer(1 To 512) As Byte
End Type
''// Per ottenere la versione del SO
Private Declare Function GetVersionEx _
Lib "kernel32" Alias "GetVersionExA" _
(lpVersionInformation As OSVERSIONINFO) As Long
''// Per ottenere un handle al device IDE
Private Declare Function CreateFile _
Lib "kernel32" Alias "CreateFileA" _
(ByVal lpFileName As String, _
ByVal dwDesiredAccess As Long, _
ByVal dwShareMode As Long, _
ByVal lpSecurityAttributes As Long, _
ByVal dwCreationDisposition As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal hTemplateFile As Long) As Long
''// Per chiudere l'handle del device IDE
Private Declare Function CloseHandle _
Lib "kernel32" _
(ByVal hObject As Long) As Long
''// Per comunicare con il driver IDE
Private Declare Function DeviceIoControl _
Lib "kernel32" _
(ByVal hDevice As Long, _
ByVal dwIoControlCode As Long, _
lpInBuffer As Any, _
ByVal nInBufferSize As Long, _
lpOutBuffer As Any, _
ByVal nOutBufferSize As Long, _
lpBytesReturned As Long, _
ByVal lpOverlapped As Long) As Long
''// Per azzerare buffer di scambio dati
Private Declare Sub ZeroMemory _
Lib "kernel32" Alias "RtlZeroMemory" _
(dest As Any, _
ByVal numBytes As Long)
''// Per copiare porzioni di memoria
Private Declare Sub CopyMemory _
Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
Private Declare Function GetLastError _
Lib "kernel32" () As Long
Private mvarCurrentDrive As Byte ''// Drive corrente
Private mvarPlatform As String ''// Piattaforma usata
Public Property Get Copyright() As String
''// Copyright
Copyright = "HDSN Vrs. 1.00, (C) Antonio Giuliana, 2001-2003"
End Property
''// Metodo GetModelNumber
Public Function GetModelNumber() As String
''// Ottiene il ModelNumber
GetModelNumber = CmnGetHDData(HD_MODEL_NUMBER)
End Function
''// Metodo GetSerialNumber
Public Function GetSerialNumber() As String
''// Ottiene il SerialNumber
GetSerialNumber = CmnGetHDData(HD_SERIAL_NUMBER)
End Function
''// Metodo GetFirmwareRevision
Public Function GetFirmwareRevision() As String
''// Ottiene la FirmwareRevision
GetFirmwareRevision = CmnGetHDData(HD_FIRMWARE_REVISION)
End Function
''// Proprieta' CurrentDrive
Public Property Let CurrentDrive(ByVal vData As Byte)
''// Controllo numero di drive fisico IDE
If vData < 0 Or vData > 3 Then
Err.Raise 10000, , "Illegal drive number" ''// IDE drive 0..3
End If
''// Nuovo drive da considerare
mvarCurrentDrive = vData
End Property
''// Proprieta' CurrentDrive
Public Property Get CurrentDrive() As Byte
''// Restituisce drive fisico corrente (IDE 0..3)
CurrentDrive = mvarCurrentDrive
End Property
''// Proprieta' Platform
Public Property Get Platform() As String
''// Restituisce tipo OS
Platform = mvarPlatform
End Property
Private Sub Class_Initialize()
''// Individuazione del tipo di OS
Dim OS As OSVERSIONINFO
OS.dwOSVersionInfoSize = Len(OS)
Call GetVersionEx(OS)
mvarPlatform = "Unk"
Select Case OS.dwPlatformId
Case Is = VER_PLATFORM_WIN32S
mvarPlatform = "32S" ''// Win32S
Case Is = VER_PLATFORM_WIN32_WINDOWS
If OS.dwMinorVersion = 0 Then
mvarPlatform = "W95" ''// Win 95
Else
mvarPlatform = "W98" ''// Win 98
End If
Case Is = VER_PLATFORM_WIN32_NT
mvarPlatform = "WNT" ''// Win NT/2000
End Select
End Sub
Private Function CmnGetHDData(hdi As HDINFO) As String
''// Rilevazione proprieta' IDE
Dim bin As SENDCMDINPARAMS
Dim bout As SENDCMDOUTPARAMS
Dim hdh As Long
Dim br As Long
Dim ix As Long
Dim hddfr As Long
Dim hddln As Long
Dim s As String
Select Case hdi ''// Selezione tipo caratteristica richiesta
Case HD_MODEL_NUMBER
hddfr = 55 ''// Posizione nel buffer del ModelNumber
hddln = 40 ''// Lunghezza nel buffer del ModelNumber
Case HD_SERIAL_NUMBER
hddfr = 21 ''// Posizione nel buffer del SerialNumber
hddln = 20 ''// Lunghezza nel buffer del SerialNumber
Case HD_FIRMWARE_REVISION
hddfr = 47 ''// Posizione nel buffer del FirmwareRevision
hddln = 8 ''// Lunghezza nel buffer del FirmwareRevision
Case Else
Err.Raise 10001, "Illegal HD Data type"
End Select
Select Case mvarPlatform
Case "WNT"
''// Per Win NT/2000 apertura handle al drive fisico
hdh = CreateFile("\\.\PhysicalDrive" & mvarCurrentDrive, _
GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, _
0, OPEN_EXISTING, 0, 0)
Case "W95", "W98"
''// Per Win 9X apertura handle al driver SMART
''// (in \WINDOWS\SYSTEM da spostare in \WINDOWS\SYSTEM\IOSUBSYS)
''// che comunica con il driver IDE
hdh = CreateFile("\\.\Smartvsd", _
0, 0, 0, CREATE_NEW, 0, 0)
Case Else
''// Piattaforma non supportata (Win32S)
Err.Raise 10002, , "Illegal platform (only WNT, W98 or W95)"
End Select
''// Controllo validità handle
If hdh = 0 Then
Err.Raise 10003, , "Error on CreateFile"
End If
''// Azzeramento strutture per l'I/O da driver
ZeroMemory bin, Len(bin)
ZeroMemory bout, Len(bout)
''// Preparazione parametri struttura di richiesta al driver
With bin
.bDriveNumber = mvarCurrentDrive
.cBufferSize = 512
With .irDriveRegs
If (mvarCurrentDrive And 1) Then
.bDriveHeadReg = &HB0
Else
.bDriveHeadReg = &HA0
End If
.bCommandReg = &HEC
.bSectorCountReg = 1
.bSectorNumberReg = 1
End With
End With
''// Richiesta al driver
DeviceIoControl hdh, DFP_RECEIVE_DRIVE_DATA, _
bin, Len(bin), bout, Len(bout), br, 0
''// Formazione stringa di risposta
''// da buffer di uscita
''// L'ordine dei byte e' invertito
s = ""
For ix = hddfr To hddfr + hddln - 1 Step 2
If bout.bBuffer(ix + 1) = 0 Then Exit For
s = s & Chr(bout.bBuffer(ix + 1))
If bout.bBuffer(ix) = 0 Then Exit For
s = s & Chr(bout.bBuffer(ix))
Next ix
''// Chiusura handle
CloseHandle hdh
''// Restituzione informazione richiesta
CmnGetHDData = Trim(s)
End Function
```
|
I found it! Here is the equivalent VB.NET code. It's not exactly the converted version of the VB6 code, but does the same thing. Enjoy!
```
Public Class HDDInfo
#Region " Declatrations "
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal lpSecurityAttributes As Integer, ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer, ByVal hTemplateFile As Integer) As Integer
<System.Runtime.InteropServices.DllImport("kernel32.dll")> _
Private Shared Function CloseHandle(ByVal hObject As Integer) As Integer
End Function
<System.Runtime.InteropServices.DllImport("kernel32.dll")> _
Private Shared Function DeviceIoControl(ByVal hDevice As Integer, ByVal dwIoControlCode As Integer, <[In](), Out()> ByVal lpInBuffer As SENDCMDINPARAMS, ByVal lpInBufferSize As Integer, <[In](), Out()> ByVal lpOutBuffer As SENDCMDOUTPARAMS, ByVal lpOutBufferSize As Integer, _
ByRef lpBytesReturned As Integer, ByVal lpOverlapped As Integer) As Integer
End Function
Private Const FILE_SHARE_READ As Short = &H1
Private Const FILE_SHARE_WRITE As Short = &H2
Private Const GENERIC_READ As Integer = &H80000000
Private Const GENERIC_WRITE As Integer = &H40000000
Private Const OPEN_EXISTING As Short = 3
Private Const CREATE_NEW As Short = 1
Private Const VER_PLATFORM_WIN32_NT As Integer = 2
Private Const DFP_RECEIVE_DRIVE_DATA As Integer = &H7C088
Private Const INVALID_HANDLE_VALUE As Integer = -1
#End Region
#Region " Classes "
<StructLayout(LayoutKind.Sequential, Size:=8)> _
Private Class IDEREGS
Public Features As Byte
Public SectorCount As Byte
Public SectorNumber As Byte
Public CylinderLow As Byte
Public CylinderHigh As Byte
Public DriveHead As Byte
Public Command As Byte
Public Reserved As Byte
End Class
<StructLayout(LayoutKind.Sequential, Size:=32)> _
Private Class SENDCMDINPARAMS
Public BufferSize As Integer
Public DriveRegs As IDEREGS
Public DriveNumber As Byte
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)> _
Public Reserved As Byte()
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=4)> _
Public Reserved2 As Integer()
Public Sub New()
DriveRegs = New IDEREGS()
Reserved = New Byte(2) {}
Reserved2 = New Integer(3) {}
End Sub
End Class
<StructLayout(LayoutKind.Sequential, Size:=12)> _
Private Class DRIVERSTATUS
Public DriveError As Byte
Public IDEStatus As Byte
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _
Public Reserved As Byte()
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _
Public Reserved2 As Integer()
Public Sub New()
Reserved = New Byte(1) {}
Reserved2 = New Integer(1) {}
End Sub
End Class
<StructLayout(LayoutKind.Sequential)> _
Private Class IDSECTOR
Public GenConfig As Short
Public NumberCylinders As Short
Public Reserved As Short
Public NumberHeads As Short
Public BytesPerTrack As Short
Public BytesPerSector As Short
Public SectorsPerTrack As Short
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)> _
Public VendorUnique As Short()
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)> _
Public SerialNumber As Char()
Public BufferClass As Short
Public BufferSize As Short
Public ECCSize As Short
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=8)> _
Public FirmwareRevision As Char()
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=40)> _
Public ModelNumber As Char()
Public MoreVendorUnique As Short
Public DoubleWordIO As Short
Public Capabilities As Short
Public Reserved1 As Short
Public PIOTiming As Short
Public DMATiming As Short
Public BS As Short
Public NumberCurrentCyls As Short
Public NumberCurrentHeads As Short
Public NumberCurrentSectorsPerTrack As Short
Public CurrentSectorCapacity As Integer
Public MultipleSectorCapacity As Short
Public MultipleSectorStuff As Short
Public TotalAddressableSectors As Integer
Public SingleWordDMA As Short
Public MultiWordDMA As Short
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=382)> _
Public Reserved2 As Byte()
End Class
<StructLayout(LayoutKind.Sequential)> _
Private Class SENDCMDOUTPARAMS
Public BufferSize As Integer
Public Status As DRIVERSTATUS
Public IDS As IDSECTOR
Public Sub New()
Status = New DRIVERSTATUS()
IDS = New IDSECTOR()
End Sub
End Class
#End Region
#Region " Methods and Functions "
Private Shared Function SwapChars(ByVal chars As Char()) As String
For i As Integer = 0 To chars.Length - 2 Step 2
Dim t As Char
t = chars(i)
chars(i) = chars(i + 1)
chars(i + 1) = t
Next
Dim s As New String(chars)
Return s
End Function
Public Shared Function GetHDDInfoString() As String
Dim serialNumber As String = " ", model As String = " ", firmware As String = " "
Dim handle As Integer, returnSize As Integer = 0
Dim driveNumber As Integer = 0
Dim sci As New SENDCMDINPARAMS()
Dim sco As New SENDCMDOUTPARAMS()
If Environment.OSVersion.Platform = PlatformID.Win32NT Then
handle = CreateFile("\\.\PhysicalDrive" & "0", GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)
Else
handle = CreateFile("\\.\Smartvsd", 0, 0, 0, CREATE_NEW, 0, 0)
End If
If handle <> INVALID_HANDLE_VALUE Then
sci.DriveNumber = CByte(driveNumber)
sci.BufferSize = Marshal.SizeOf(sco)
sci.DriveRegs.DriveHead = CByte((&HA0 Or driveNumber << 4))
sci.DriveRegs.Command = &HEC
sci.DriveRegs.SectorCount = 1
sci.DriveRegs.SectorNumber = 1
If DeviceIoControl(handle, DFP_RECEIVE_DRIVE_DATA, sci, Marshal.SizeOf(sci), sco, Marshal.SizeOf(sco), _
returnSize, 0) <> 0 Then
serialNumber = SwapChars(sco.IDS.SerialNumber)
model = SwapChars(sco.IDS.ModelNumber)
firmware = SwapChars(sco.IDS.FirmwareRevision)
End If
CloseHandle(handle)
End If
Return model.Trim & " " & serialNumber.Trim
End Function
#End Region
End Class
```
|
278,068 |
<p>I have an image that I want to show some 'spotlights' on, like they do on TV. The rest of the image should be darker than the original, and the person that I'm spotlighting should be normal. I have the x,y and radius of the spotlight, but I'm not sure how to change the brightness at that location. </p>
<p>Also, if I have two spotlights and they intersect, the intersection should be brighter than either of the spotlights. </p>
|
[
{
"answer_id": 278113,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>A simple way is to convert the color to HSL, lower L to darken, increase to lighten, then convert back to RGB and set the pixel.</p>\n\n<p><a href=\"http://www.mpa-garching.mpg.de/MPA-GRAPHICS/hsl-rgb.html\" rel=\"nofollow noreferrer\">http://www.mpa-garching.mpg.de/MPA-GRAPHICS/hsl-rgb.html</a></p>\n"
},
{
"answer_id": 278261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Use RescaleOp on the original image and subimages. Given that you have a buffered image (called biDest) that contains the image, call RescaleOp(0.6, 0, null) on it to make it darker. Then, to add a (rectangular) spotlight, call the following:</p>\n\n<pre><code> public void spotLight(int x, int y, int w, int h)\n {\n BufferedImage i = biDest.getSubimage(x, y, w, h);\n\n RescaleOp rescale = new RescaleOp(SPOTLIGHT_BRIGHTNESS, 0, null);\n rescale.filter(i, i);\n\n repaint();\n }\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an image that I want to show some 'spotlights' on, like they do on TV. The rest of the image should be darker than the original, and the person that I'm spotlighting should be normal. I have the x,y and radius of the spotlight, but I'm not sure how to change the brightness at that location.
Also, if I have two spotlights and they intersect, the intersection should be brighter than either of the spotlights.
|
Use RescaleOp on the original image and subimages. Given that you have a buffered image (called biDest) that contains the image, call RescaleOp(0.6, 0, null) on it to make it darker. Then, to add a (rectangular) spotlight, call the following:
```
public void spotLight(int x, int y, int w, int h)
{
BufferedImage i = biDest.getSubimage(x, y, w, h);
RescaleOp rescale = new RescaleOp(SPOTLIGHT_BRIGHTNESS, 0, null);
rescale.filter(i, i);
repaint();
}
```
|
278,071 |
<p>I want to get the overall total CPU usage for an application in C#. I've found many ways to dig into the properties of processes, but I only want the CPU usage of the processes, and the total CPU like you get in the TaskManager.</p>
<p>How do I do that?</p>
|
[
{
"answer_id": 278088,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": false,
"text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter(VS.80).aspx\" rel=\"noreferrer\">PerformanceCounter</a> class from <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.aspx\" rel=\"noreferrer\">System.Diagnostics</a>.</p>\n\n<p>Initialize like this:</p>\n\n<pre><code>PerformanceCounter cpuCounter;\nPerformanceCounter ramCounter;\n\ncpuCounter = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\");\nramCounter = new PerformanceCounter(\"Memory\", \"Available MBytes\");\n</code></pre>\n\n<p>Consume like this: </p>\n\n<pre><code>public string getCurrentCpuUsage(){\n return cpuCounter.NextValue()+\"%\";\n}\n\npublic string getAvailableRAM(){\n return ramCounter.NextValue()+\"MB\";\n} \n</code></pre>\n"
},
{
"answer_id": 278103,
"author": "Tarks",
"author_id": 398,
"author_profile": "https://Stackoverflow.com/users/398",
"pm_score": 3,
"selected": false,
"text": "<p>CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.</p>\n"
},
{
"answer_id": 278153,
"author": "adparadox",
"author_id": 1962,
"author_profile": "https://Stackoverflow.com/users/1962",
"pm_score": 3,
"selected": false,
"text": "<p>You can use WMI to get CPU percentage information. You can even log into a remote computer if you have the correct permissions. Look at <a href=\"http://www.csharphelp.com/archives2/archive334.html\" rel=\"nofollow noreferrer\">http://www.csharphelp.com/archives2/archive334.html</a> to get an idea of what you can accomplish.</p>\n\n<p>Also helpful might be the MSDN reference for the <a href=\"http://msdn.microsoft.com/en-us/library/aa394372%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">Win32_Process</a> namespace.</p>\n\n<p>See also a CodeProject example <a href=\"http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx\" rel=\"nofollow noreferrer\">How To: (Almost) Everything In WMI via C#</a>.</p>\n"
},
{
"answer_id": 278505,
"author": "xoxo",
"author_id": 36243,
"author_profile": "https://Stackoverflow.com/users/36243",
"pm_score": 4,
"selected": false,
"text": "<p>It's OK, I got it! Thanks for your help!</p>\n\n<p>Here is the code to do it:</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n selectedServer = \"JS000943\";\n listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());\n}\n\nprivate static int GetProcessorIdleTime(string selectedServer)\n{\n try\n {\n var searcher = new\n ManagementObjectSearcher\n (@\"\\\\\"+ selectedServer +@\"\\root\\CIMV2\",\n \"SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\\\"_Total\\\"\");\n\n ManagementObjectCollection collection = searcher.Get();\n ManagementObject queryObj = collection.Cast<ManagementObject>().First();\n\n return Convert.ToInt32(queryObj[\"PercentIdleTime\"]);\n }\n catch (ManagementException e)\n {\n MessageBox.Show(\"An error occurred while querying for WMI data: \" + e.Message);\n }\n return -1;\n}\n</code></pre>\n"
},
{
"answer_id": 6168408,
"author": "Khalid Rahaman",
"author_id": 55688,
"author_profile": "https://Stackoverflow.com/users/55688",
"pm_score": 6,
"selected": false,
"text": "<p>A little more than was requsted but I use the extra timer code to track and alert if CPU usage is 90% or higher for a sustained period of 1 minute or longer.</p>\n\n<pre><code>public class Form1\n{\n\n int totalHits = 0;\n\n public object getCPUCounter()\n {\n\n PerformanceCounter cpuCounter = new PerformanceCounter();\n cpuCounter.CategoryName = \"Processor\";\n cpuCounter.CounterName = \"% Processor Time\";\n cpuCounter.InstanceName = \"_Total\";\n\n // will always start at 0\n dynamic firstValue = cpuCounter.NextValue();\n System.Threading.Thread.Sleep(1000);\n // now matches task manager reading\n dynamic secondValue = cpuCounter.NextValue();\n\n return secondValue;\n\n }\n\n\n private void Timer1_Tick(Object sender, EventArgs e)\n {\n int cpuPercent = (int)getCPUCounter();\n if (cpuPercent >= 90)\n {\n totalHits = totalHits + 1;\n if (totalHits == 60)\n {\n Interaction.MsgBox(\"ALERT 90% usage for 1 minute\");\n totalHits = 0;\n } \n }\n else\n {\n totalHits = 0;\n }\n Label1.Text = cpuPercent + \" % CPU\";\n //Label2.Text = getRAMCounter() + \" RAM Free\";\n Label3.Text = totalHits + \" seconds over 20% usage\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10233124,
"author": "Colin Breame",
"author_id": 641452,
"author_profile": "https://Stackoverflow.com/users/641452",
"pm_score": 2,
"selected": false,
"text": "<p>This class automatically polls the counter every 1 seconds and is also thread safe:</p>\n\n<pre><code>public class ProcessorUsage\n{\n const float sampleFrequencyMillis = 1000;\n\n protected object syncLock = new object();\n protected PerformanceCounter counter;\n protected float lastSample;\n protected DateTime lastSampleTime;\n\n /// <summary>\n /// \n /// </summary>\n public ProcessorUsage()\n {\n this.counter = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\", true);\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <returns></returns>\n public float GetCurrentValue()\n {\n if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)\n {\n lock (syncLock)\n {\n if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)\n {\n lastSample = counter.NextValue();\n lastSampleTime = DateTime.UtcNow;\n }\n }\n }\n\n return lastSample;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11891139,
"author": "MtnManChris",
"author_id": 1588638,
"author_profile": "https://Stackoverflow.com/users/1588638",
"pm_score": 4,
"selected": false,
"text": "<p>After spending some time reading over a couple different threads that seemed pretty complicated I came up with this. I needed it for an 8 core machine where I wanted to monitor SQL server. For the code below then I passed in \"sqlservr\" as appName.</p>\n\n<pre><code>private static void RunTest(string appName)\n{\n bool done = false;\n PerformanceCounter total_cpu = new PerformanceCounter(\"Process\", \"% Processor Time\", \"_Total\");\n PerformanceCounter process_cpu = new PerformanceCounter(\"Process\", \"% Processor Time\", appName);\n while (!done)\n {\n float t = total_cpu.NextValue();\n float p = process_cpu.NextValue();\n Console.WriteLine(String.Format(\"_Total = {0} App = {1} {2}%\\n\", t, p, p / t * 100));\n System.Threading.Thread.Sleep(1000);\n }\n}\n</code></pre>\n\n<p>It seems to correctly measure the % of CPU being used by SQL on my 8 core server.</p>\n"
},
{
"answer_id": 17749478,
"author": "atconway",
"author_id": 410937,
"author_profile": "https://Stackoverflow.com/users/410937",
"pm_score": 0,
"selected": false,
"text": "<p>I did not like having to add in the 1 second stall to all of the <code>PerformanceCounter</code> solutions. Instead I chose to use a <code>WMI</code> solution. The reason the 1 second wait/stall exists is to allow the reading to be accurate when using a <code>PerformanceCounter</code>. However if you calling this method often and refreshing this information, I'd advise not to constantly have to incur that delay... even if thinking of doing an async process to get it.</p>\n\n<p>I started with the snippet from here <a href=\"https://stackoverflow.com/questions/9777661/returning-cpu-usage-in-wmi-using-c-sharp\">Returning CPU usage in WMI using C#</a> and added a full explanation of the solution on my blog post below: </p>\n\n<p><a href=\"http://allen-conway-dotnet.blogspot.com/2013/07/get-cpu-usage-across-all-cores-in-c.html\" rel=\"nofollow noreferrer\">Get CPU Usage Across All Cores In C# Using WMI</a></p>\n"
},
{
"answer_id": 18574155,
"author": "Jay Byford-Rew",
"author_id": 2739967,
"author_profile": "https://Stackoverflow.com/users/2739967",
"pm_score": 2,
"selected": false,
"text": "<p>This seems to work for me, an example for waiting until the processor reaches a certain percentage</p>\n\n<pre><code>var cpuCounter = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\");\nint usage = (int) cpuCounter.NextValue();\nwhile (usage == 0 || usage > 80)\n{\n Thread.Sleep(250);\n usage = (int)cpuCounter.NextValue();\n}\n</code></pre>\n"
},
{
"answer_id": 60514868,
"author": "araad1992",
"author_id": 3276211,
"author_profile": "https://Stackoverflow.com/users/3276211",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public int GetCpuUsage()\n{\n var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);\n cpuCounter.NextValue();\n System.Threading.Thread.Sleep(1000); //This avoid that answer always 0\n return (int)cpuCounter.NextValue();\n}\n</code></pre>\n<p>Original information in this link <a href=\"https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/\" rel=\"nofollow noreferrer\">https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/</a></p>\n"
},
{
"answer_id": 72249902,
"author": "AecorSoft",
"author_id": 9382225,
"author_profile": "https://Stackoverflow.com/users/9382225",
"pm_score": 1,
"selected": false,
"text": "<p>For those who still could not get the total CPU usage figure which matches Task Manager, you should use this statement:</p>\n<pre><code>new PerformanceCounter("Processor Information", "% Processor Utility", "_Total");\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to get the overall total CPU usage for an application in C#. I've found many ways to dig into the properties of processes, but I only want the CPU usage of the processes, and the total CPU like you get in the TaskManager.
How do I do that?
|
You can use the [PerformanceCounter](http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter(VS.80).aspx) class from [System.Diagnostics](http://msdn.microsoft.com/en-us/library/system.diagnostics.aspx).
Initialize like this:
```
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
```
Consume like this:
```
public string getCurrentCpuUsage(){
return cpuCounter.NextValue()+"%";
}
public string getAvailableRAM(){
return ramCounter.NextValue()+"MB";
}
```
|
278,075 |
<p>I am monitoring a folder with a .net filewatcher for certain kind of files(*.mbxml). I am using the created event of filewatcher for it. Once the created event fires I have to move this file to another folder. The problem with this approach is that the created event is fired as soon as the file copying starts. So if the file is taking too long to copy to the folder being watched, the code that moves the file fails. I've searched and the only solution I found on the net was that you move the file within a try-catch block and keep trying until the whole file is copied. I don't like this solution, it would've been better if the created event was fired once the whole file had finished copying or there was a separate event for it. Is there another way of achieving this?</p>
|
[
{
"answer_id": 278083,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Are you able to change the program which is creating the files? If so, change it to create them in one folder and then move them (atomically) to a different folder - or use a different extension (anything you can track, really).</p>\n"
},
{
"answer_id": 278115,
"author": "h0st1le",
"author_id": 26170,
"author_profile": "https://Stackoverflow.com/users/26170",
"pm_score": 3,
"selected": true,
"text": "<p>i have yet to see this done in anyway except with a try catch block. usually on the oncreate event i set a bool that try's to open the file. this determines if the rest of the code proceeds, if there is another way i would be interested as well.</p>\n\n<pre><code> private static bool creationComplete(string fileName)\n {\n // if the file can be opened it is no longer locked and now available\n try\n {\n using (FileStream inputStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))\n {\n return true;\n }\n }\n catch (IOException)\n {\n return false;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 278144,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried moving the file using BinaryReader and BinaryWriter? You can probably read the file as it's being copied and write it a a slower pace so your move doesn't beat the speed at which the other process creates the file. You could also insert some wait time in between reads. Once you make the last read and verify the file creation is finished you can then delete it.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 278159,
"author": "hova",
"author_id": 2170,
"author_profile": "https://Stackoverflow.com/users/2170",
"pm_score": 1,
"selected": false,
"text": "<p>The whole reason a try/catch solution is used, is because the only way to know if the other program is finished writing to the file is for the file open() call to SUCCEED. That is a FAILURE is the definition of the file still being written to.</p>\n\n<p>Typically in your situation a while() loop is used with a thread.sleep timer in it, which keeps trying until either A) timeout or B) success.</p>\n"
},
{
"answer_id": 278171,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 0,
"selected": false,
"text": "<p>If I recall correctly, the FileWatcher raises several events per IO on a given file/folder. You may be able to narrow down the FileSystemEventArgs associated with completion. It may be necessary to defer to checking if the file is accessible, but I would think it a less desirable solution.</p>\n"
},
{
"answer_id": 278175,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 2,
"selected": false,
"text": "<p>From:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx</a></p>\n\n<p>\"Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher. \"</p>\n\n<p>How time sensitive are your requirements for moving the file?</p>\n\n<p>If you don't like the idea of trying to move it, catching exceptions, and repeating until you get a success you could take a slightly different approach.</p>\n\n<p>How about once you receive a Created event, you begin monitoring the file's last write time. Once a certain time has passed since the last write time, say two seconds, you can try moving the file then. You'll probably find there a lot less 'failed' moves, but the end result will be the same.</p>\n"
},
{
"answer_id": 278177,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 2,
"selected": false,
"text": "<p>Watch for the on created event but wait for the last write time change event. When the file is done being copied the last write time is updated. Since you are moving the files, you can probably just handle the last write time change event.</p>\n"
},
{
"answer_id": 278201,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 2,
"selected": false,
"text": "<p>you could make your code simpler by just inheriting from FileSystemWatcher and fireing your own FileReady Event, like so:</p>\n\n<pre><code>public class CustomFileSystemWatcher : System.IO.FileSystemWatcher\n{\n public CustomFileSystemWatcher()\n {\n this.Created += new FileSystemEventHandler(CustomFileSystemWatcher_Created);\n }\n\n\n private void CustomFileSystemWatcher_Created(object sender, FileSystemEventArgs e)\n {\n ThreadPool.QueueUserWorkItem((n) => { WaitFileReady(e); });\n }\n\n private void WaitFileReady(FileSystemEventArgs e)\n {\n while (true)\n {\n try\n {\n using (FileStream fs = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))\n {\n //exit\n break;\n }\n }\n catch (Exception)\n {\n //wait if you like\n Thread.Sleep(100);\n }\n }\n OnFileReady(e);\n }\n\n public event FileSystemEventHandler FileReady;\n\n protected virtual void OnFileReady(FileSystemEventArgs e)\n {\n if (this.EnableRaisingEvents && FileReady != null) FileReady(this, e);\n }\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25125/"
] |
I am monitoring a folder with a .net filewatcher for certain kind of files(\*.mbxml). I am using the created event of filewatcher for it. Once the created event fires I have to move this file to another folder. The problem with this approach is that the created event is fired as soon as the file copying starts. So if the file is taking too long to copy to the folder being watched, the code that moves the file fails. I've searched and the only solution I found on the net was that you move the file within a try-catch block and keep trying until the whole file is copied. I don't like this solution, it would've been better if the created event was fired once the whole file had finished copying or there was a separate event for it. Is there another way of achieving this?
|
i have yet to see this done in anyway except with a try catch block. usually on the oncreate event i set a bool that try's to open the file. this determines if the rest of the code proceeds, if there is another way i would be interested as well.
```
private static bool creationComplete(string fileName)
{
// if the file can be opened it is no longer locked and now available
try
{
using (FileStream inputStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
```
|
278,081 |
<p>I've been using Git on Windows (msysgit) to track changes for some design work I've been doing.</p>
<p>Today I've been working on a different PC (with remote repo <code>brian</code>) and I'm now trying to merge the edits done today back into my regular local version on my laptop.</p>
<p>On my laptop, I've used <code>git pull brian master</code> to pull the changes into my local version. Everything was fine apart from the main InDesign document - this shows as a conflict.</p>
<p>The version on the PC (<code>brian</code>) is the latest one that I want to keep but I don't know what commands tells the repo to use this one. </p>
<p>I tried directly copying the file across onto my laptop but this seems to break the whole merge process.</p>
<p>Can anyone point me in the right direction?</p>
|
[
{
"answer_id": 278207,
"author": "VolkA",
"author_id": 25472,
"author_profile": "https://Stackoverflow.com/users/25472",
"pm_score": 7,
"selected": false,
"text": "<p>You have to resolve the conflict manually (copying the file over) and then commit the file (no matter if you copied it over or used the local version) like this</p>\n\n<pre><code>git commit -a -m \"Fix merge conflict in test.foo\"\n</code></pre>\n\n<p>Git normally autocommits after merging, but when it detects conflicts it cannot solve by itself, it applies all patches it figured out and leaves the rest for you to resolve and commit manually. The <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-merge.html\" rel=\"noreferrer\">Git Merge Man Page</a>, the <a href=\"http://git.or.cz/course/svn.html#merge\" rel=\"noreferrer\">Git-SVN Crash Course</a> or <a href=\"http://www.bluishcoder.co.nz/2007/09/git-binary-files-and-cherry-picking.html\" rel=\"noreferrer\">this</a> blog entry might shed some light on how it's supposed to work.</p>\n\n<p><strong>Edit:</strong> See the post below, you don't actually have to copy the files yourself, but can use </p>\n\n<pre><code>git checkout --ours -- path/to/file.txt\ngit checkout --theirs -- path/to/file.txt\n</code></pre>\n\n<p>to select the version of the file you want. Copying / editing the file will only be necessary if you want a mix of both versions.</p>\n\n<p>Please mark mipadis answer as the correct one.</p>\n"
},
{
"answer_id": 1162085,
"author": "Brian Webster",
"author_id": 23324,
"author_profile": "https://Stackoverflow.com/users/23324",
"pm_score": 3,
"selected": false,
"text": "<p>I came across a similar problem (wanting to pull a commit that included some binary files which caused conflicts when merged), but came across a different solution that can be done entirely using git (i.e. not having to manually copy files over). I figured I'd include it here so at the very least I can remember it the next time I need it. :) The steps look like this:</p>\n\n<pre><code>% git fetch\n</code></pre>\n\n<p>This fetches the latest commit(s) from the remote repository (you may need to specify a remote branch name, depending on your setup), but doesn't try to merge them. It records the the commit in FETCH_HEAD</p>\n\n<pre><code>% git checkout FETCH_HEAD stuff/to/update\n</code></pre>\n\n<p>This takes the copy of the binary files I want and overwrites what's in the working tree with the version fetched from the remote branch. git doesn't try to do any merging, so you just end up with an exact copy of the binary file from the remote branch. Once that's done, you can add/commit the new copy just like normal. </p>\n"
},
{
"answer_id": 1321855,
"author": "RobM",
"author_id": 83100,
"author_profile": "https://Stackoverflow.com/users/83100",
"pm_score": 7,
"selected": false,
"text": "<p>You can also overcome this problem with</p>\n\n<pre><code>git mergetool\n</code></pre>\n\n<p>which causes <code>git</code> to create local copies of the conflicted binary and spawn your default editor on them:</p>\n\n<ul>\n<li><code>{conflicted}.HEAD</code></li>\n<li><code>{conflicted}</code></li>\n<li><code>{conflicted}.REMOTE</code></li>\n</ul>\n\n<p>Obviously you can't usefully edit binaries files in a text editor. Instead you copy the new <code>{conflicted}.REMOTE</code> file over <code>{conflicted}</code> without closing the editor. Then when you do close the editor <code>git</code> will see that the undecorated working-copy has been changed and your merge conflict is resolved in the usual way.</p>\n"
},
{
"answer_id": 2163895,
"author": "Joshua Flanagan",
"author_id": 156533,
"author_profile": "https://Stackoverflow.com/users/156533",
"pm_score": 4,
"selected": false,
"text": "<p>To resolve by keeping the version in your current branch (ignore the version from the branch you are merging in), just add and commit the file:</p>\n\n<pre><code>git commit -a\n</code></pre>\n\n<p>To resolve by overwriting the version in your current branch with the version from the branch you are merging in, you need to retrieve that version into your working directory first, and then add/commit it:</p>\n\n<pre><code>git checkout otherbranch theconflictedfile\ngit commit -a\n</code></pre>\n\n<p><a href=\"http://www.lostechies.com/blogs/joshuaflanagan/archive/2010/01/28/how-to-resolve-a-binary-file-conflict-with-git.aspx\" rel=\"noreferrer\">Explained in more detail</a></p>\n"
},
{
"answer_id": 2163926,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 11,
"selected": true,
"text": "<p><code>git checkout</code> accepts an <code>--ours</code> or <code>--theirs</code> option for cases like this. So if you have a merge conflict, and you know you just want the file from the branch you are merging in, you can do:</p>\n\n<pre><code>$ git checkout --theirs -- path/to/conflicted-file.txt\n</code></pre>\n\n<p>to use that version of the file. Likewise, if you know you want your version (not the one being merged in) you can use</p>\n\n<pre><code>$ git checkout --ours -- path/to/conflicted-file.txt\n</code></pre>\n"
},
{
"answer_id": 16826359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>From the <a href=\"http://git-scm.com/docs/git-checkout\" rel=\"noreferrer\"><code>git checkout</code> docs</a></p>\n\n<blockquote>\n <p><code>git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...</code> </p>\n \n <p><strong><code>--ours</code></strong><br>\n <strong><code>--theirs</code></strong><br>\n When checking out paths from the index, check out stage #2 (<code>ours</code>) or #3 (<code>theirs</code>) for unmerged paths.</p>\n \n <p>The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using <code>-f</code> will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using <code>--ours</code> or <code>--theirs</code>. With <code>-m</code>, changes made to the working tree file can be discarded to re-create the original conflicted merge result.</p>\n</blockquote>\n"
},
{
"answer_id": 27097132,
"author": "kris",
"author_id": 1290746,
"author_profile": "https://Stackoverflow.com/users/1290746",
"pm_score": 4,
"selected": false,
"text": "<p>mipadi's answer didn't quite work for me, I needed to do this :</p>\n\n<blockquote>\n <p>git checkout --ours path/to/file.bin</p>\n</blockquote>\n\n<p>or, to keep the version being merged in:</p>\n\n<blockquote>\n <p>git checkout --theirs path/to/file.bin</p>\n</blockquote>\n\n<p>then</p>\n\n<blockquote>\n <p>git add path/to/file.bin</p>\n</blockquote>\n\n<p>And then I was able to do \"git mergetool\" again and continue onto the next conflict.</p>\n"
},
{
"answer_id": 27174410,
"author": "BoJohDoh",
"author_id": 2191079,
"author_profile": "https://Stackoverflow.com/users/2191079",
"pm_score": 1,
"selected": false,
"text": "<p>I've come across two strategies for managing diff/merge of binary files with Git on windows.</p>\n\n<ol>\n<li><p>Tortoise git lets you configure diff/merge tools for different file types based on their file extensions. See 2.35.4.3. Diff/Merge Advanced Settings <a href=\"http://tortoisegit.org/docs/tortoisegit/tgit-dug-settings.html\" rel=\"nofollow\">http://tortoisegit.org/docs/tortoisegit/tgit-dug-settings.html</a>. This strategy of course relys on suitable diff/merge tools being available.</p></li>\n<li><p>Using git attributes you can specify a tool/command to convert your binary file to text and then let your default diff/merge tool do it's thing. See <a href=\"http://git-scm.com/book/it/v2/Customizing-Git-Git-Attributes\" rel=\"nofollow\">http://git-scm.com/book/it/v2/Customizing-Git-Git-Attributes</a>. The article even gives an example of using meta data to diff images.</p></li>\n</ol>\n\n<p>I got both strategies to work with binary files of software models, but we went with tortoise git as the configuration was easy.</p>\n"
},
{
"answer_id": 31998378,
"author": "tyoc213",
"author_id": 682603,
"author_profile": "https://Stackoverflow.com/users/682603",
"pm_score": 1,
"selected": false,
"text": "<p>If the binary is <strong>something more than a dll</strong> or something that can be <strong>edited directly</strong> like an image, or a blend file (and you don't need to trash/select one file or the other) a real merge would be some like:</p>\n<p>I suggest searching for a diff tool oriented to what are your binary file, for example, there are some free ones for image files for example</p>\n<ul>\n<li>npm install -g imagediff IIRC from <a href=\"https://github.com/uber/image-diff\" rel=\"nofollow noreferrer\">https://github.com/uber/image-diff</a></li>\n<li>or python <a href=\"https://github.com/kaikuehne/mirror.git\" rel=\"nofollow noreferrer\">https://github.com/kaikuehne/mirror.git</a></li>\n<li>there are others out there</li>\n</ul>\n<p>and compare them.</p>\n<p>If there is no diff tool out there for comparing your files, then if you have the <strong>original generator</strong> of the bin file (that is, <strong>there exist an editor</strong> for it... like blender 3d, you can then manually inspect those files, also see the logs, and ask the other person what you should include)\nand do output of the files with <a href=\"https://git-scm.com/book/es/v2/Git-Tools-Advanced-Merging#_manual_remerge\" rel=\"nofollow noreferrer\">https://git-scm.com/book/es/v2/Git-Tools-Advanced-Merging#_manual_remerge</a></p>\n<pre><code>$ git show :1:hello.blend > hello.common.blend\n$ git show :2:hello.blend > hello.ours.blend\n$ git show :3:hello.blend > hello.theirs.blend\n</code></pre>\n"
},
{
"answer_id": 55248208,
"author": "Sidd Thota",
"author_id": 6441370,
"author_profile": "https://Stackoverflow.com/users/6441370",
"pm_score": 0,
"selected": false,
"text": "<p>I use Git Workflow for Excel - <a href=\"https://www.xltrail.com/blog/git-workflow-for-excel\" rel=\"nofollow noreferrer\">https://www.xltrail.com/blog/git-workflow-for-excel</a> application to resolve most of my binary files related merge issues. This open-source app helps me to resolve issues productively without spending too much time and lets me cherry pick the right version of the file without any confusion.</p>\n"
},
{
"answer_id": 55369549,
"author": "david m lee",
"author_id": 4020917,
"author_profile": "https://Stackoverflow.com/users/4020917",
"pm_score": 2,
"selected": false,
"text": "<p>This procedure is to resolve binary file conflicts after you have submitted a pull request to Github:</p>\n\n<ol>\n<li>So on Github, you found your pull request has a conflict on a binary file.</li>\n<li>Now go back to the same git branch on your local computer.</li>\n<li>You (a) re-make / re-build this binary file again, and (b) commit the resulted binary file to this same git branch.</li>\n<li>Then you push this same git branch again to Github. </li>\n</ol>\n\n<p>On Github, on your pull request, the conflict should disappear.</p>\n"
},
{
"answer_id": 55628454,
"author": "Peter",
"author_id": 1134343,
"author_profile": "https://Stackoverflow.com/users/1134343",
"pm_score": 0,
"selected": false,
"text": "<p>my case seems like a bug.... using git 2.21.0</p>\n\n<p>I did a pull... it complained about binary files:</p>\n\n<pre><code>warning: Cannot merge binary files: <path>\nAuto-merging <path>\nCONFLICT (content): Merge conflict in <path>\nAutomatic merge failed; fix conflicts and then commit the result.\n</code></pre>\n\n<p>And then nothing in any of the answers here resulted in any output that made any sense.</p>\n\n<p>If I look at which file I have now... it's the one I edited. If I do either:</p>\n\n<pre><code>git checkout --theirs -- <path>\ngit checkout --ours -- <path>\n</code></pre>\n\n<p>I get output:</p>\n\n<pre><code>Updated 0 paths from the index\n</code></pre>\n\n<p>and I still have my version of the file. If I rm and then checkout, It'll say 1 instead, but it still gives me my version of the file.</p>\n\n<p>git mergetool says</p>\n\n<pre><code>No files need merging\n</code></pre>\n\n<p>and git status says</p>\n\n<pre><code> All conflicts fixed but you are still merging.\n (use \"git commit\" to conclude merge)\n</code></pre>\n\n<p>One option is to <a href=\"https://stackoverflow.com/questions/927358/how-do-i-undo-the-most-recent-local-commits-in-git\">undo the commit</a>... but I was unlucky and I had many commits, and this bad one was the first. I don't want to waste time repeating that.</p>\n\n<p><strong>so to solve this madness:</strong></p>\n\n<p>I just ran</p>\n\n<pre><code>git commit\n</code></pre>\n\n<p>which loses the remote version, and probably wastes some space storing an extra binary file... then</p>\n\n<pre><code>git checkout <commit where the remote version exists> <path>\n</code></pre>\n\n<p>which gives me back the remote version</p>\n\n<p>then edited the file again...and then commit and push, which again probably means wasting space with another copy of the binary file.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33721/"
] |
I've been using Git on Windows (msysgit) to track changes for some design work I've been doing.
Today I've been working on a different PC (with remote repo `brian`) and I'm now trying to merge the edits done today back into my regular local version on my laptop.
On my laptop, I've used `git pull brian master` to pull the changes into my local version. Everything was fine apart from the main InDesign document - this shows as a conflict.
The version on the PC (`brian`) is the latest one that I want to keep but I don't know what commands tells the repo to use this one.
I tried directly copying the file across onto my laptop but this seems to break the whole merge process.
Can anyone point me in the right direction?
|
`git checkout` accepts an `--ours` or `--theirs` option for cases like this. So if you have a merge conflict, and you know you just want the file from the branch you are merging in, you can do:
```
$ git checkout --theirs -- path/to/conflicted-file.txt
```
to use that version of the file. Likewise, if you know you want your version (not the one being merged in) you can use
```
$ git checkout --ours -- path/to/conflicted-file.txt
```
|
278,089 |
<p>is there a quick way to sort the items of a select element?
Or I have to resort to writing javascript?</p>
<p>Please any ideas.</p>
<pre><code><select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;">
<option value="0"> XXX</option>
<option value="1203">ABC</option>
<option value="1013">MMM</option>
</select>
</code></pre>
|
[
{
"answer_id": 278111,
"author": "Joel Martinez",
"author_id": 5416,
"author_profile": "https://Stackoverflow.com/users/5416",
"pm_score": 1,
"selected": false,
"text": "<p>Yes DOK has the right answer ... either pre-sort the results before you write the HTML (assuming it's dynamic and you are responsible for the output), or you write javascript. </p>\n\n<p>The <a href=\"http://www.w3schools.com/jsref/jsref_sort.asp\" rel=\"nofollow noreferrer\">Javascript Sort</a> method will be your friend here. Simply pull the values out of the select list, then sort it, and put them back :-)</p>\n"
},
{
"answer_id": 278116,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>From the <a href=\"http://www.w3.org/International/questions/qa-select-sorting.en.php\" rel=\"nofollow noreferrer\">W3C FAQ</a>:</p>\n\n<blockquote>\n <p>Although many programming languages have devices like drop-down boxes that have the capability of sorting a list of items before displaying them as part of their functionality, the HTML <select> function has no such capabilities. It lists the <options> in the order received.</p>\n</blockquote>\n\n<p>You'd have to sort them by hand for a static HTML document, or resort to Javascript or some other programmatic sort for a dynamic document.</p>\n"
},
{
"answer_id": 278509,
"author": "Matty",
"author_id": 26241,
"author_profile": "https://Stackoverflow.com/users/26241",
"pm_score": 7,
"selected": true,
"text": "<p>This will do the trick. Just pass it your select element a la: <code>document.getElementById('lstALL')</code> when you need your list sorted.</p>\n\n<pre><code>function sortSelect(selElem) {\n var tmpAry = new Array();\n for (var i=0;i<selElem.options.length;i++) {\n tmpAry[i] = new Array();\n tmpAry[i][0] = selElem.options[i].text;\n tmpAry[i][1] = selElem.options[i].value;\n }\n tmpAry.sort();\n while (selElem.options.length > 0) {\n selElem.options[0] = null;\n }\n for (var i=0;i<tmpAry.length;i++) {\n var op = new Option(tmpAry[i][0], tmpAry[i][1]);\n selElem.options[i] = op;\n }\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 955802,
"author": "Marco Lazzeri",
"author_id": 105403,
"author_profile": "https://Stackoverflow.com/users/105403",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem. Here's the <strong>jQuery solution</strong> I came up with:</p>\n\n<pre><code> var options = jQuery.makeArray(optionElements).\n sort(function(a,b) {\n return (a.innerHTML > b.innerHTML) ? 1 : -1;\n });\n selectElement.html(options);\n</code></pre>\n"
},
{
"answer_id": 2632714,
"author": "Geoff",
"author_id": 306277,
"author_profile": "https://Stackoverflow.com/users/306277",
"pm_score": 0,
"selected": false,
"text": "<p>Not quite as pretty as the JQuery example by Marco but with prototype (i may be missing a more elegant solution) it would be:</p>\n\n<pre><code>function sort_select(select) {\n var options = $A(select.options).sortBy(function(o) { return o.innerHTML });\n select.innerHTML = \"\";\n options.each(function(o) { select.insert(o); } );\n}\n</code></pre>\n\n<p>And then just pass it a select element:</p>\n\n<pre><code>sort_select( $('category-select') );\n</code></pre>\n"
},
{
"answer_id": 5199082,
"author": "Matias P.",
"author_id": 357797,
"author_profile": "https://Stackoverflow.com/users/357797",
"pm_score": 1,
"selected": false,
"text": "<p>Í think this is a better option (I use @Matty's code and improved!):</p>\n\n<pre><code>function sortSelect(selElem, bCase) {\n var tmpAry = new Array();\n bCase = (bCase ? true : false);\n for (var i=0;i<selElem.options.length;i++) {\n tmpAry[i] = new Array();\n tmpAry[i][0] = selElem.options[i].text;\n tmpAry[i][1] = selElem.options[i].value;\n }\n if (bCase)\n tmpAry.sort(function (a, b) {\n var ret = 0;\n var iPos = 0;\n while (ret == 0 && iPos < a.length && iPos < b.length)\n {\n ret = (String(a).toLowerCase().charCodeAt(iPos) - String(b).toLowerCase().charCodeAt(iPos));\n iPos ++;\n }\n if (ret == 0)\n {\n ret = (String(a).length - String(b).length);\n }\n return ret;\n });\n else\n tmpAry.sort();\n while (selElem.options.length > 0) {\n selElem.options[0] = null;\n }\n for (var i=0;i<tmpAry.length;i++) {\n var op = new Option(tmpAry[i][0], tmpAry[i][1]);\n selElem.options[i] = op;\n }\n return;\n }\n</code></pre>\n"
},
{
"answer_id": 5490401,
"author": "mikehowles",
"author_id": 684486,
"author_profile": "https://Stackoverflow.com/users/684486",
"pm_score": 2,
"selected": false,
"text": "<p>Another option:</p>\n\n<pre><code>function sortSelect(elem) {\n var tmpAry = [];\n // Retain selected value before sorting\n var selectedValue = elem[elem.selectedIndex].value;\n // Grab all existing entries\n for (var i=0;i<elem.options.length;i++) tmpAry.push(elem.options[i]);\n // Sort array by text attribute\n tmpAry.sort(function(a,b){ return (a.text < b.text)?-1:1; });\n // Wipe out existing elements\n while (elem.options.length > 0) elem.options[0] = null;\n // Restore sorted elements\n var newSelectedIndex = 0;\n for (var i=0;i<tmpAry.length;i++) {\n elem.options[i] = tmpAry[i];\n if(elem.options[i].value == selectedValue) newSelectedIndex = i;\n }\n elem.selectedIndex = newSelectedIndex; // Set new selected index after sorting\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 6521401,
"author": "Soledad",
"author_id": 821178,
"author_profile": "https://Stackoverflow.com/users/821178",
"pm_score": 1,
"selected": false,
"text": "<p>I used this bubble sort because I wasnt able to order them by the .value in the options array and it was a number. This way I got them properly ordered. I hope it's useful to you too.</p>\n\n<pre><code>function sortSelect(selElem) {\n for (var i=0; i<(selElem.options.length-1); i++)\n for (var j=i+1; j<selElem.options.length; j++)\n if (parseInt(selElem.options[j].value) < parseInt(selElem.options[i].value)) {\n var dummy = new Option(selElem.options[i].text, selElem.options[i].value);\n selElem.options[i] = new Option(selElem.options[j].text, selElem.options[j].value);\n selElem.options[j] = dummy;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7466196,
"author": "Terre Porter",
"author_id": 951920,
"author_profile": "https://Stackoverflow.com/users/951920",
"pm_score": 6,
"selected": false,
"text": "<p>This solution worked very nicely for me using jquery, thought I'd cross reference it here as I found this page before the other one. Someone else might do the same.</p>\n\n<pre><code>$(\"#id\").html($(\"#id option\").sort(function (a, b) {\n return a.text == b.text ? 0 : a.text < b.text ? -1 : 1\n}))\n</code></pre>\n\n<p>from <a href=\"https://stackoverflow.com/questions/667010/sorting-dropdown-list-using-javascript/667198#667198\">Sorting dropdown list using Javascript</a></p>\n"
},
{
"answer_id": 9200431,
"author": "Matt K",
"author_id": 549141,
"author_profile": "https://Stackoverflow.com/users/549141",
"pm_score": 3,
"selected": false,
"text": "<p>Working with the answers provided by Marco Lazzeri and Terre Porter (vote them up if this answer is useful), I came up with a slightly different solution that preserves the selected value (probably doesn't preserve event handlers or attached data, though) using <strong>jQuery</strong>.</p>\n\n<pre><code>// save the selected value for sorting\nvar v = jQuery(\"#id\").val();\n\n// sort the options and select the value that was saved\nj$(\"#id\")\n .html(j$(\"#id option\").sort(function(a,b){\n return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}))\n .val(v);\n</code></pre>\n"
},
{
"answer_id": 12210886,
"author": "jerone",
"author_id": 108448,
"author_profile": "https://Stackoverflow.com/users/108448",
"pm_score": 0,
"selected": false,
"text": "<p>Just another way to do it with jQuery:</p>\n\n<pre><code>// sorting;\nvar selectElm = $(\"select\"),\n selectSorted = selectElm.find(\"option\").toArray().sort(function (a, b) {\n return (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) ? 1 : -1;\n });\nselectElm.empty();\n$.each(selectSorted, function (key, value) {\n selectElm.append(value);\n});\n</code></pre>\n"
},
{
"answer_id": 17703167,
"author": "colinbashbash",
"author_id": 379215,
"author_profile": "https://Stackoverflow.com/users/379215",
"pm_score": 2,
"selected": false,
"text": "<p>I had a similar problem, except I wanted the selected items to show up on top, and I didn't want to clear which items were selected (multi-select list). Mine is jQuery based... </p>\n\n<pre><code>function SortMultiSelect_SelectedTop(slt) {\n var options =\n $(slt).find(\"option\").sort(function (a, b) {\n if (a.selected && !b.selected) return -1;\n if (!a.selected && b.selected) return 1;\n if (a.text < b.text) return -1;\n if (a.text > b.text) return 1;\n return 0;\n });\n $(slt).empty().append(options).scrollTop(0);\n}\n</code></pre>\n\n<p>Without selected on top, it would look like this.</p>\n\n<pre><code>function SortMultiSelect(slt) {\n var options =\n $(slt).find(\"option\").sort(function (a, b) {\n if (a.text < b.text) return -1;\n if (a.text > b.text) return 1;\n return 0;\n });\n $(slt).empty().append(options).scrollTop(0);\n}\n</code></pre>\n"
},
{
"answer_id": 17704336,
"author": "MDEV",
"author_id": 763371,
"author_profile": "https://Stackoverflow.com/users/763371",
"pm_score": 1,
"selected": false,
"text": "<p>I've quickly thrown together one that allows choice of direction (\"asc\" or \"desc\"), whether the comparison should be done on the option value (true or false) and whether or not leading and trailing whitespace should be trimmed before comparison (boolean).</p>\n\n<p>The benefit of this method, is that the selected choice is kept, and all other special properties/triggers should also be kept.</p>\n\n<pre><code>function sortOpts(select,dir,value,trim)\n{\n value = typeof value == 'boolean' ? value : false;\n dir = ['asc','desc'].indexOf(dir) > -1 ? dir : 'asc';\n trim = typeof trim == 'boolean' ? trim : true;\n if(!select) return false;\n var opts = select.getElementsByTagName('option');\n\n var options = [];\n for(var i in opts)\n {\n if(parseInt(i)==i)\n {\n if(trim)\n {\n opts[i].innerHTML = opts[i].innerHTML.replace(/^\\s*(.*)\\s*$/,'$1');\n opts[i].value = opts[i].value.replace(/^\\s*(.*)\\s*$/,'$1');\n }\n options.push(opts[i]);\n }\n }\n options.sort(value ? sortOpts.sortVals : sortOpts.sortText);\n if(dir == 'desc') options.reverse();\n options.reverse();\n for(var i in options)\n {\n select.insertBefore(options[i],select.getElementsByTagName('option')[0]);\n }\n}\nsortOpts.sortText = function(a,b) {\n return a.innerHTML > b.innerHTML ? 1 : -1;\n}\nsortOpts.sortVals = function(a,b) {\n return a.value > b.value ? 1 : -1;\n}\n</code></pre>\n"
},
{
"answer_id": 19463371,
"author": "Tony Chiboucas",
"author_id": 1589379,
"author_profile": "https://Stackoverflow.com/users/1589379",
"pm_score": 2,
"selected": false,
"text": "<p>This is a a recompilation of my 3 favorite answers on this board:</p>\n\n<ul>\n<li>jOk's best and simplest answer.</li>\n<li>Terry Porter's easy jQuery method.</li>\n<li>SmokeyPHP's configurable function.</li>\n</ul>\n\n<p>The results are an easy to use, and easily configurable function. </p>\n\n<p>First argument can be a select object, the ID of a select object, or an array with at least 2 dimensions.</p>\n\n<p>Second argument is optional. Defaults to sorting by option text, index 0. Can be passed any other index so sort on that. Can be passed 1, or the text \"value\", to sort by value. </p>\n\n<h2>Sort by text examples (all would sort by text):</h2>\n\n<pre><code> sortSelect('select_object_id');\n sortSelect('select_object_id', 0);\n sortSelect(selectObject);\n sortSelect(selectObject, 0);\n</code></pre>\n\n<h2>Sort by value (all would sort by value):</h2>\n\n<pre><code> sortSelect('select_object_id', 'value');\n sortSelect('select_object_id', 1);\n sortSelect(selectObject, 1);\n</code></pre>\n\n<h2>Sort any array by another index:</h2>\n\n<pre><code>var myArray = [\n ['ignored0', 'ignored1', 'Z-sortme2'],\n ['ignored0', 'ignored1', 'A-sortme2'],\n ['ignored0', 'ignored1', 'C-sortme2'],\n];\n\nsortSelect(myArray,2);\n</code></pre>\n\n<p>This last one will sort the array by index-2, the sortme's.</p>\n\n<h1>Main sort function</h1>\n\n<pre><code>function sortSelect(selElem, sortVal) {\n\n // Checks for an object or string. Uses string as ID. \n switch(typeof selElem) {\n case \"string\":\n selElem = document.getElementById(selElem);\n break;\n case \"object\":\n if(selElem==null) return false;\n break;\n default:\n return false;\n }\n\n // Builds the options list.\n var tmpAry = new Array();\n for (var i=0;i<selElem.options.length;i++) {\n tmpAry[i] = new Array();\n tmpAry[i][0] = selElem.options[i].text;\n tmpAry[i][1] = selElem.options[i].value;\n }\n\n // allows sortVal to be optional, defaults to text.\n switch(sortVal) {\n case \"value\": // sort by value\n sortVal = 1;\n break;\n default: // sort by text\n sortVal = 0;\n }\n tmpAry.sort(function(a, b) {\n return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;\n });\n\n // removes all options from the select.\n while (selElem.options.length > 0) {\n selElem.options[0] = null;\n }\n\n // recreates all options with the new order.\n for (var i=0;i<tmpAry.length;i++) {\n var op = new Option(tmpAry[i][0], tmpAry[i][1]);\n selElem.options[i] = op;\n }\n\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 20280085,
"author": "Krishna Kamat",
"author_id": 3048342,
"author_profile": "https://Stackoverflow.com/users/3048342",
"pm_score": 0,
"selected": false,
"text": "<p>Try this...hopefully it will offer you a solution:\n </p>\n\n<pre><code>function sortlist_name()\n{\n\n var lb = document.getElementById('mylist');\n arrTexts = new Array();\n newTexts = new Array();\n txt = new Array();\n newArray =new Array();\n for(i=0; i<lb.length; i++)\n {\n arrTexts[i] = lb.options[i].text;\n }\n for(i=0;i<arrTexts.length; i++)\n {\n str = arrTexts[i].split(\" -> \");\n newTexts[i] = str[1]+' -> '+str[0];\n }\n newTexts.sort();\n for(i=0;i<newTexts.length; i++)\n {\n txt = newTexts[i].split(' -> ');\n newArray[i] = txt[1]+' -> '+txt[0];\n }\n for(i=0; i<lb.length; i++)\n {\n lb.options[i].text = newArray[i];\n lb.options[i].value = newArray[i];\n }\n}\n/***********revrse by name******/\nfunction sortreverse_name()\n{\n\n var lb = document.getElementById('mylist');\n arrTexts = new Array();\n newTexts = new Array();\n txt = new Array();\n newArray =new Array();\n for(i=0; i<lb.length; i++)\n {\n arrTexts[i] = lb.options[i].text;\n }\n for(i=0;i<arrTexts.length; i++)\n {\n str = arrTexts[i].split(\" -> \");\n newTexts[i] = str[1]+' -> '+str[0];\n }\n newTexts.reverse();\n for(i=0;i<newTexts.length; i++)\n {\n txt = newTexts[i].split(' -> ');\n newArray[i] = txt[1]+' -> '+txt[0];\n }\n for(i=0; i<lb.length; i++)\n {\n lb.options[i].text = newArray[i];\n lb.options[i].value = newArray[i];\n }\n}\n\nfunction sortlist_id() {\nvar lb = document.getElementById('mylist');\narrTexts = new Array();\n\nfor(i=0; i<lb.length; i++) {\n arrTexts[i] = lb.options[i].text;\n}\n\narrTexts.sort();\n\nfor(i=0; i<lb.length; i++) {\n lb.options[i].text = arrTexts[i];\n lb.options[i].value = arrTexts[i];\n}\n}\n\n/***********revrse by id******/\nfunction sortreverse_id() {\nvar lb = document.getElementById('mylist');\narrTexts = new Array();\n\nfor(i=0; i<lb.length; i++) {\n arrTexts[i] = lb.options[i].text;\n}\n\narrTexts.reverse();\n\nfor(i=0; i<lb.length; i++) {\n lb.options[i].text = arrTexts[i];\n lb.options[i].value = arrTexts[i];\n}\n}\n</script>\n\n\n\n ID<a href=\"javascript:sortlist_id()\"> &#x25B2; </a> <a href=\"javascript:sortreverse_id()\">&#x25BC;</a> | Name<a href=\"javascript:sortlist_name()\"> &#x25B2; </a> <a href=\"javascript:sortreverse_name()\">&#x25BC;</a><br/>\n\n<select name=mylist id=mylist size=8 style='width:150px'>\n\n<option value=\"bill\">4 -> Bill</option>\n<option value=\"carl\">5 -> Carl</option>\n<option value=\"Anton\">1 -> Anton</option>\n<option value=\"mike\">2 -> Mike</option>\n<option value=\"peter\">3 -> Peter</option>\n</select>\n<br>\n</code></pre>\n"
},
{
"answer_id": 24459808,
"author": "RPDeshaies",
"author_id": 1598891,
"author_profile": "https://Stackoverflow.com/users/1598891",
"pm_score": 1,
"selected": false,
"text": "<p>Inspired by @Terre Porter's answer, I think this one is very simple to implement (using jQuery)</p>\n\n<pre><code>var $options = jQuery(\"#my-dropdownlist-id > option\"); \n// or jQuery(\"#my-dropdownlist-id\").find(\"option\")\n\n$options.sort(function(a, b) {\n return a.text == b.text ? 0 : a.text < b.text ? -1 : 1\n})\n</code></pre>\n\n<p>But, for Alpha/Numeric dropdown lists : </p>\n\n<p>Inspired by : <a href=\"https://stackoverflow.com/a/4340339/1598891\">https://stackoverflow.com/a/4340339/1598891</a></p>\n\n<pre><code>var $options = jQuery(dropDownList).find(\"option\");\n\nvar reAlpha = /[^a-zA-Z]/g;\nvar reNumeric = /[^0-9]/g;\n$options.sort(function AlphaNumericSort($a,$b) {\n var a = $a.text;\n var b = $b.text;\n var aAlpha = a.replace(reAlpha, \"\");\n var bAlpha = b.replace(reAlpha, \"\");\n if(aAlpha === bAlpha) {\n var aNumeric = parseInt(a.replace(reNumeric, \"\"), 10);\n var bNumeric = parseInt(b.replace(reNumeric, \"\"), 10);\n return aNumeric === bNumeric ? 0 : aNumeric > bNumeric ? 1 : -1;\n } else {\n return aAlpha > bAlpha ? 1 : -1;\n }\n})\n</code></pre>\n\n<p>Hope it will help</p>\n\n<p><img src=\"https://i.stack.imgur.com/MI8xi.png\" alt=\"First example\">\n<img src=\"https://i.stack.imgur.com/IUtac.png\" alt=\"Second example\"></p>\n"
},
{
"answer_id": 27825253,
"author": "Arijit Basu",
"author_id": 4245458,
"author_profile": "https://Stackoverflow.com/users/4245458",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function call() {\n var x = document.getElementById(\"mySelect\");\n var optionVal = new Array();\n\n for (i = 0; i < x.length; i++) {\n optionVal.push(x.options[i].text);\n }\n\n for (i = x.length; i >= 0; i--) {\n x.remove(i);\n }\n\n optionVal.sort();\n\n for (var i = 0; i < optionVal.length; i++) {\n var opt = optionVal[i];\n var el = document.createElement(\"option\");\n el.textContent = opt;\n el.value = opt;\n x.appendChild(el);\n }\n}\n</code></pre>\n\n<p>The idea is to pullout all the elements of the selectbox into an array , delete the selectbox values to avoid overriding, sort the array and then push back the sorted array into the select box</p>\n"
},
{
"answer_id": 31652966,
"author": "Joel",
"author_id": 3689517,
"author_profile": "https://Stackoverflow.com/users/3689517",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function sortItems(c) {\nvar options = c.options;\nArray.prototype.sort.call(options, function (a, b) {\n var aText = a.text.toLowerCase();\n var bText = b.text.toLowerCase();\n if (aText < bText) {\n return -1;\n } else if (aText > bText) {\n return 1;\n } else {\n return 0;\n }\n});\n}\n\nsortItems(document.getElementById('lstALL'));\n</code></pre>\n"
},
{
"answer_id": 56711000,
"author": "protoEvangelion",
"author_id": 6502003,
"author_profile": "https://Stackoverflow.com/users/6502003",
"pm_score": 3,
"selected": false,
"text": "<h2>Vanilla JS es6 Localization Options Sorting Example</h2>\n\n<pre><code>const optionNodes = Array.from(selectNode.children);\nconst comparator = new Intl.Collator(lang.slice(0, 2)).compare;\n\noptionNodes.sort((a, b) => comparator(a.textContent, b.textContent));\noptionNodes.forEach((option) => selectNode.appendChild(option));\n</code></pre>\n\n<p>My use case was to localize a country select dropdown with locale aware sorting. This was used on 250 + options and was very performant <strong>~10ms</strong> on my machine.</p>\n"
},
{
"answer_id": 57998034,
"author": "Jordan Daigle",
"author_id": 6126481,
"author_profile": "https://Stackoverflow.com/users/6126481",
"pm_score": 0,
"selected": false,
"text": "<p>For those who are looking to sort whether or not there are <a href=\"https://www.w3schools.com/tags/tag_optgroup.asp\" rel=\"nofollow noreferrer\">optgroup</a> :</p>\n\n<pre><code>/**\n * Sorting options \n * and optgroups\n * \n * @param selElem select element\n * @param optionBeforeGroup ?bool if null ignores, if true option appear before group else option appear after group\n */\nfunction sortSelect(selElem, optionBeforeGroup = null) {\n let initialValue = selElem.tagName === \"SELECT\" ? selElem.value : null; \n let allChildrens = Array.prototype.slice.call(selElem.childNodes);\n let childrens = [];\n\n for (let i = 0; i < allChildrens.length; i++) {\n if (allChildrens[i].parentNode === selElem && [\"OPTGROUP\", \"OPTION\"].includes(allChildrens[i].tagName||\"\")) {\n if (allChildrens[i].tagName == \"OPTGROUP\") {\n sortSelect(allChildrens[i]);\n }\n childrens.push(allChildrens[i]);\n }\n }\n\n childrens.sort(function(a, b){\n let x = a.tagName == \"OPTGROUP\" ? a.getAttribute(\"label\") : a.innerHTML;\n let y = b.tagName == \"OPTGROUP\" ? b.getAttribute(\"label\") : b.innerHTML;\n x = typeof x === \"undefined\" || x === null ? \"\" : (x+\"\");\n y = typeof y === \"undefined\" || y === null ? \"\" : (y+\"\");\n\n if (optionBeforeGroup === null) {\n if (x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}\n if (x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}\n } else if (optionBeforeGroup === true) {\n if ((a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}\n if ((a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}\n } else if (optionBeforeGroup === false) {\n if ((a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}\n if ((a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}\n }\n return 0;\n });\n\n if (optionBeforeGroup !== null) {\n childrens.sort(function(a, b){\n if (optionBeforeGroup === true) {\n if (a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") {return -1;}\n if (a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") {return 1;}\n } else {\n if (a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") {return -1;}\n if (a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") {return 1;}\n }\n return 0;\n });\n }\n\n selElem.innerHTML = \"\";\n for (let i = 0; i < childrens.length; i++) {\n selElem.appendChild(childrens[i]);\n }\n\n if (selElem.tagName === \"SELECT\") {\n selElem.value = initialValue;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67861236,
"author": "Bruno L.",
"author_id": 9160102,
"author_profile": "https://Stackoverflow.com/users/9160102",
"pm_score": 0,
"selected": false,
"text": "<p>I think my function is more general for strings or numbers and does not sort the first element if it could mean All.</p>\n<pre><code>/** Check if a string can be parsed as a number. */\nfunction isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) };\n\n/** Sort options of HTML elements. */\nfunction sortOptions(selectElement, exceptFirstOpt=false) {\n\n // List of options.\n var options = selectElement.options;\n // If empty list, do nothing.\n if(!options || options.length==0) return;\n\n // Array.\n var optionsArray = [];\n for (var i = (exceptFirstOpt ? 1 : 0); i < options.length; i++)\n optionsArray.push(options[i]);\n // Sort.\n optionsArray = optionsArray.sort(function (a, b) { \n let v1 = a.innerHTML.toLowerCase();\n let v2 = b.innerHTML.toLowerCase();\n if((v1==undefined || v1 == '') && (v2==undefined || v2 == ''))\n return 0;\n else if(v1==undefined || v1.trim() == '') return 1;\n else if(v2==undefined || v2.trim() == '') return -1;\n\n // If number.\n if(isNumber(v1) && isNumber(v2))\n return parseFloat(v1)>parseFloat(v2);\n\n return v1.localeCompare(v2); \n });\n\n // Update options.\n for (var i = 0; i <= optionsArray.length; i++) \n options[i + (exceptFirstOpt ? 1 : 0)] = optionsArray[i];\n // First option selected by default.\n options[0].selected = true;\n}\n</code></pre>\n"
},
{
"answer_id": 73379064,
"author": "Nathan Sutherland",
"author_id": 4367909,
"author_profile": "https://Stackoverflow.com/users/4367909",
"pm_score": 0,
"selected": false,
"text": "<pre><code>let selectOrDatalist = document.querySelector('#sdl');\n/* optional added option\n selectOrDatalist.insertAdjacentHTML('afterbegin', `<option id="${id}" value="${foo}">${bar}</option>` );\n*/\nselectOrDatalist.append(...[...selectOrDatalist.options].sort((a,b) => a.value.localeCompare(b.value)));\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
is there a quick way to sort the items of a select element?
Or I have to resort to writing javascript?
Please any ideas.
```
<select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;">
<option value="0"> XXX</option>
<option value="1203">ABC</option>
<option value="1013">MMM</option>
</select>
```
|
This will do the trick. Just pass it your select element a la: `document.getElementById('lstALL')` when you need your list sorted.
```
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
```
|
278,101 |
<p>I am using ActiveReports with ASP.NET but I think answer for any similar reporting component will do.</p>
<p>I have two resultset to merge and show in a single report, like:</p>
<pre><code>Table 1:
Name Job Start End
Jack Some service 1992 1997
Jack Some Sales Exp 1998 2007
Jane Some programming 2000 2003
Table 2:
Name Training
Jack Shiny French Certificate
Jane Crappy database certificate
Jane Some courses in management
</code></pre>
<p>And the report should look like:</p>
<pre><code>Jack
Job History:
Some Corp, 1992-1997
Some Sales Exp, 1998-2007
Training History:
Shiny French Certificate
Jane
Job History:
Some programming, 2000-2003
Training History:
Crappy database certificate
Some courses in management
</code></pre>
<p>How should I merge the two tables and how should I design the layout to achieve the report in the given example?</p>
<p>Update:</p>
<p>As you may notice, I am not trying to do this with a single select. I have two datatables as source and I can merge them by hand to get a single data source. I am trying to use grouping but I need two kind of groups for each employee. One for the jobs, and one for the trainings. How can I use groups or sub-reports feature to bind this kind of data (and how should I process the data if necessary)?</p>
|
[
{
"answer_id": 278141,
"author": "agsamek",
"author_id": 33608,
"author_profile": "https://Stackoverflow.com/users/33608",
"pm_score": 1,
"selected": false,
"text": "<p>In general you cannot do it in a single SELECT statement. Most reporting tools offer some kind of \"subreports\" or \"inner sections\" that run on a different SQL question and have some parameters passed from the main report. You could use two subreports and one master report.</p>\n"
},
{
"answer_id": 278162,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<p>You should select this two tables with \"left-join\", create a \"GroupHeader/Footer\" section in report and set \"DataField\" on \"GroupHeader\" section to field, which should be used as grouping.</p>\n\n<p>Look at the samples from ActiveReports, they surely has a sample for grouping.</p>\n"
},
{
"answer_id": 416763,
"author": "Scott Willeke",
"author_id": 51061,
"author_profile": "https://Stackoverflow.com/users/51061",
"pm_score": 3,
"selected": true,
"text": "<p>Use subreports... Create a main report that will have two subreports. One subreport for job history and one subreport for training history. The main report will need a query that will return a list of people. Then for each Person in the detail of the main report, set a parameter on each of the child subreports that will refine the query in those two to list the Job History or Training History for only the current person being displayed in the parent report.</p>\n\n<p>A detailed walkthrough that explains how to do this step by step is on the Data Dynamics website <a href=\"http://www.datadynamics.com/Help/ARNET/ParameterswithSubreports.html\" rel=\"nofollow noreferrer\">here</a>. Some overview information is also <a href=\"http://www.datadynamics.com/forums/539/ShowPost.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
I am using ActiveReports with ASP.NET but I think answer for any similar reporting component will do.
I have two resultset to merge and show in a single report, like:
```
Table 1:
Name Job Start End
Jack Some service 1992 1997
Jack Some Sales Exp 1998 2007
Jane Some programming 2000 2003
Table 2:
Name Training
Jack Shiny French Certificate
Jane Crappy database certificate
Jane Some courses in management
```
And the report should look like:
```
Jack
Job History:
Some Corp, 1992-1997
Some Sales Exp, 1998-2007
Training History:
Shiny French Certificate
Jane
Job History:
Some programming, 2000-2003
Training History:
Crappy database certificate
Some courses in management
```
How should I merge the two tables and how should I design the layout to achieve the report in the given example?
Update:
As you may notice, I am not trying to do this with a single select. I have two datatables as source and I can merge them by hand to get a single data source. I am trying to use grouping but I need two kind of groups for each employee. One for the jobs, and one for the trainings. How can I use groups or sub-reports feature to bind this kind of data (and how should I process the data if necessary)?
|
Use subreports... Create a main report that will have two subreports. One subreport for job history and one subreport for training history. The main report will need a query that will return a list of people. Then for each Person in the detail of the main report, set a parameter on each of the child subreports that will refine the query in those two to list the Job History or Training History for only the current person being displayed in the parent report.
A detailed walkthrough that explains how to do this step by step is on the Data Dynamics website [here](http://www.datadynamics.com/Help/ARNET/ParameterswithSubreports.html). Some overview information is also [here](http://www.datadynamics.com/forums/539/ShowPost.aspx)
|
278,112 |
<p>Is there any c library to get a video from the webcam on linux?</p>
|
[
{
"answer_id": 278117,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": false,
"text": "<p>Your best bet is probably: <a href=\"http://en.wikipedia.org/wiki/Video4Linux\" rel=\"noreferrer\">video4linux (V4L)</a></p>\n\n<p>It's easy to use, and powerful. </p>\n"
},
{
"answer_id": 4025769,
"author": "karlphillip",
"author_id": 176769,
"author_profile": "https://Stackoverflow.com/users/176769",
"pm_score": 4,
"selected": false,
"text": "<p>A lot of us use <a href=\"http://opencv.willowgarage.com/wiki/\">OpenCV</a> (cross-platform Computer Vision library, currently on v2.1)</p>\n\n<p>The following snippet grabs frames from camera, converts them to grayscale and displays them on the screen:</p>\n\n<pre><code>#include <stdio.h>\n#include \"cv.h\"\n#include \"highgui.h\"\n\n\ntypedef IplImage* (*callback_prototype)(IplImage*);\n\n\n/* \n * make_it_gray: custom callback to convert a colored frame to its grayscale version.\n * Remember that you must deallocate the returned IplImage* yourself after calling this function.\n */\nIplImage* make_it_gray(IplImage* frame)\n{\n // Allocate space for a new image\n IplImage* gray_frame = 0;\n gray_frame = cvCreateImage(cvSize(frame->width, frame->height), frame->depth, 1);\n if (!gray_frame)\n {\n fprintf(stderr, \"!!! cvCreateImage failed!\\n\" );\n return NULL;\n }\n\n cvCvtColor(frame, gray_frame, CV_RGB2GRAY);\n return gray_frame; \n}\n\n/*\n * process_video: retrieves frames from camera and executes a callback to do individual frame processing.\n * Keep in mind that if your callback takes too much time to execute, you might loose a few frames from \n * the camera.\n */\nvoid process_video(callback_prototype custom_cb)\n{ \n // Initialize camera\n CvCapture *capture = 0;\n capture = cvCaptureFromCAM(-1);\n if (!capture) \n {\n fprintf(stderr, \"!!! Cannot open initialize webcam!\\n\" );\n return;\n }\n\n // Create a window for the video \n cvNamedWindow(\"result\", CV_WINDOW_AUTOSIZE);\n\n IplImage* frame = 0;\n char key = 0;\n while (key != 27) // ESC\n { \n frame = cvQueryFrame(capture);\n if(!frame) \n {\n fprintf( stderr, \"!!! cvQueryFrame failed!\\n\" );\n break;\n }\n\n // Execute callback on each frame\n IplImage* processed_frame = (*custom_cb)(frame);\n\n // Display processed frame\n cvShowImage(\"result\", processed_frame);\n\n // Release resources\n cvReleaseImage(&processed_frame);\n\n // Exit when user press ESC\n key = cvWaitKey(10);\n }\n\n // Free memory\n cvDestroyWindow(\"result\");\n cvReleaseCapture(&capture);\n}\n\nint main( int argc, char **argv )\n{\n process_video(make_it_gray);\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 40561598,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "<p><strong><code>v4l2</code> official examples</strong></p>\n<p>What you get:</p>\n<ul>\n<li><code>./v4l2grab</code>: capture a few snapshots to files <code>outNNN.ppm</code></li>\n<li><code>./v4l2gl</code>: show video live on a window using an OpenGL texture (immediate rendering, hey!) and raw X11 windowing (plus GLUT's <code>gluLookAt</code> for good measure).</li>\n</ul>\n<p>How to get it on Ubuntu 16.04:</p>\n<pre><code>sudo apt-get install libv4l-dev\nsudo apt-get build-dep libv4l-dev\ngit clone git://linuxtv.org/v4l-utils.git\ncd v4l-utils\n# Matching the installed version of dpkg -s libv4l-dev\ngit checkout v4l-utils-1.10.0\n./bootstrap.sh\n./configure\nmake\n# TODO: fails halfway, but it does not matter for us now.\ncd contrib/tests\nmake\n</code></pre>\n<p>It is also easy to use those examples outside of the Git tree, just copy them out, make relative includes <code>""</code> absolute <code><></code>, and remove <code>config.h</code>. I've done that for you at: <a href=\"https://github.com/cirosantilli/cpp-cheat/tree/09fe73d248f7da2e9c9f3eff2520a143c259f4a6/v4l2\" rel=\"nofollow noreferrer\">https://github.com/cirosantilli/cpp-cheat/tree/09fe73d248f7da2e9c9f3eff2520a143c259f4a6/v4l2</a></p>\n<p><strong>Minimal example from docs</strong></p>\n<p>The docs 4.9.0 contain what appears to be a minimal version of <code>./v4l2grab</code> at <a href=\"https://linuxtv.org/downloads/v4l-dvb-apis-new/uapi/v4l/v4l2grab-example.html\" rel=\"nofollow noreferrer\">https://linuxtv.org/downloads/v4l-dvb-apis-new/uapi/v4l/v4l2grab-example.html</a>. I needed to patch it minimally and I've sent the patch to <a href=\"http://www.spinics.net/lists/linux-media/\" rel=\"nofollow noreferrer\">http://www.spinics.net/lists/linux-media/</a> (their docs live in the Linux kernel tree as rst, neat), where it was dully ignored.</p>\n<p>Usage:</p>\n<pre><code>gcc v4l2grab.c -lv4l2\n./a.out\n</code></pre>\n<p>Patched code:</p>\n<pre><code>/* V4L2 video picture grabber\nCopyright (C) 2009 Mauro Carvalho Chehab <[email protected]>\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation version 2 of the License.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <sys/ioctl.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/mman.h>\n#include <linux/videodev2.h>\n#include <libv4l2.h>\n\n#define CLEAR(x) memset(&(x), 0, sizeof(x))\n\nstruct buffer {\n void *start;\n size_t length;\n};\n\nstatic void xioctl(int fh, int request, void *arg)\n{\n int r;\n\n do {\n r = v4l2_ioctl(fh, request, arg);\n } while (r == -1 && ((errno == EINTR) || (errno == EAGAIN)));\n\n if (r == -1) {\n fprintf(stderr, "error %d, %s\\\\n", errno, strerror(errno));\n exit(EXIT_FAILURE);\n }\n}\n\nint main(int argc, char **argv)\n{\n struct v4l2_format fmt;\n struct v4l2_buffer buf;\n struct v4l2_requestbuffers req;\n enum v4l2_buf_type type;\n fd_set fds;\n struct timeval tv;\n int r, fd = -1;\n unsigned int i, n_buffers;\n char *dev_name = "/dev/video0";\n char out_name[256];\n FILE *fout;\n struct buffer *buffers;\n\n fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0);\n if (fd < 0) {\n perror("Cannot open device");\n exit(EXIT_FAILURE);\n }\n\n CLEAR(fmt);\n fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n fmt.fmt.pix.width = 640;\n fmt.fmt.pix.height = 480;\n fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;\n fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;\n xioctl(fd, VIDIOC_S_FMT, &fmt);\n if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_RGB24) {\n printf("Libv4l didn't accept RGB24 format. Can't proceed.\\\\n");\n exit(EXIT_FAILURE);\n }\n if ((fmt.fmt.pix.width != 640) || (fmt.fmt.pix.height != 480))\n printf("Warning: driver is sending image at %dx%d\\\\n",\n fmt.fmt.pix.width, fmt.fmt.pix.height);\n\n CLEAR(req);\n req.count = 2;\n req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n req.memory = V4L2_MEMORY_MMAP;\n xioctl(fd, VIDIOC_REQBUFS, &req);\n\n buffers = calloc(req.count, sizeof(*buffers));\n for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {\n CLEAR(buf);\n\n buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n buf.memory = V4L2_MEMORY_MMAP;\n buf.index = n_buffers;\n\n xioctl(fd, VIDIOC_QUERYBUF, &buf);\n\n buffers[n_buffers].length = buf.length;\n buffers[n_buffers].start = v4l2_mmap(NULL, buf.length,\n PROT_READ | PROT_WRITE, MAP_SHARED,\n fd, buf.m.offset);\n\n if (MAP_FAILED == buffers[n_buffers].start) {\n perror("mmap");\n exit(EXIT_FAILURE);\n }\n }\n\n for (i = 0; i < n_buffers; ++i) {\n CLEAR(buf);\n buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n buf.memory = V4L2_MEMORY_MMAP;\n buf.index = i;\n xioctl(fd, VIDIOC_QBUF, &buf);\n }\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n\n xioctl(fd, VIDIOC_STREAMON, &type);\n for (i = 0; i < 20; i++) {\n do {\n FD_ZERO(&fds);\n FD_SET(fd, &fds);\n\n /* Timeout. */\n tv.tv_sec = 2;\n tv.tv_usec = 0;\n\n r = select(fd + 1, &fds, NULL, NULL, &tv);\n } while ((r == -1 && (errno = EINTR)));\n if (r == -1) {\n perror("select");\n return errno;\n }\n\n CLEAR(buf);\n buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n buf.memory = V4L2_MEMORY_MMAP;\n xioctl(fd, VIDIOC_DQBUF, &buf);\n\n sprintf(out_name, "out%03d.ppm", i);\n fout = fopen(out_name, "w");\n if (!fout) {\n perror("Cannot open image");\n exit(EXIT_FAILURE);\n }\n fprintf(fout, "P6\\n%d %d 255\\n",\n fmt.fmt.pix.width, fmt.fmt.pix.height);\n fwrite(buffers[buf.index].start, buf.bytesused, 1, fout);\n fclose(fout);\n\n xioctl(fd, VIDIOC_QBUF, &buf);\n }\n\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n xioctl(fd, VIDIOC_STREAMOFF, &type);\n for (i = 0; i < n_buffers; ++i)\n v4l2_munmap(buffers[i].start, buffers[i].length);\n v4l2_close(fd);\n\n return 0;\n}\n</code></pre>\n<p><strong>Header only object oriented version for reuse</strong></p>\n<p>Extracted from the example in the docs, but in a form that makes it super easy to reuse.</p>\n<p>common_v4l2.h</p>\n<pre><code>#ifndef COMMON_V4L2_H\n#define COMMON_V4L2_H\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/time.h>\n#include <sys/types.h>\n\n#include <libv4l2.h>\n#include <linux/videodev2.h>\n\n#define COMMON_V4L2_CLEAR(x) memset(&(x), 0, sizeof(x))\n\ntypedef struct {\n void *start;\n size_t length;\n} CommonV4l2_Buffer;\n\ntypedef struct {\n int fd;\n CommonV4l2_Buffer *buffers;\n struct v4l2_buffer buf;\n unsigned int n_buffers;\n} CommonV4l2;\n\nvoid CommonV4l2_xioctl(int fh, unsigned long int request, void *arg)\n{\n int r;\n do {\n r = v4l2_ioctl(fh, request, arg);\n } while (r == -1 && ((errno == EINTR) || (errno == EAGAIN)));\n if (r == -1) {\n fprintf(stderr, "error %d, %s\\n", errno, strerror(errno));\n exit(EXIT_FAILURE);\n }\n}\n\nvoid CommonV4l2_init(CommonV4l2 *this, char *dev_name, unsigned int x_res, unsigned int y_res) {\n enum v4l2_buf_type type;\n struct v4l2_format fmt;\n struct v4l2_requestbuffers req;\n unsigned int i;\n\n this->fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0);\n if (this->fd < 0) {\n perror("Cannot open device");\n exit(EXIT_FAILURE);\n }\n COMMON_V4L2_CLEAR(fmt);\n fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n fmt.fmt.pix.width = x_res;\n fmt.fmt.pix.height = y_res;\n fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;\n fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;\n CommonV4l2_xioctl(this->fd, VIDIOC_S_FMT, &fmt);\n if ((fmt.fmt.pix.width != x_res) || (fmt.fmt.pix.height != y_res))\n printf("Warning: driver is sending image at %dx%d\\n",\n fmt.fmt.pix.width, fmt.fmt.pix.height);\n COMMON_V4L2_CLEAR(req);\n req.count = 2;\n req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n req.memory = V4L2_MEMORY_MMAP;\n CommonV4l2_xioctl(this->fd, VIDIOC_REQBUFS, &req);\n this->buffers = calloc(req.count, sizeof(*this->buffers));\n for (this->n_buffers = 0; this->n_buffers < req.count; ++this->n_buffers) {\n COMMON_V4L2_CLEAR(this->buf);\n this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n this->buf.memory = V4L2_MEMORY_MMAP;\n this->buf.index = this->n_buffers;\n CommonV4l2_xioctl(this->fd, VIDIOC_QUERYBUF, &this->buf);\n this->buffers[this->n_buffers].length = this->buf.length;\n this->buffers[this->n_buffers].start = v4l2_mmap(NULL, this->buf.length,\n PROT_READ | PROT_WRITE, MAP_SHARED, this->fd, this->buf.m.offset);\n if (MAP_FAILED == this->buffers[this->n_buffers].start) {\n perror("mmap");\n exit(EXIT_FAILURE);\n }\n }\n for (i = 0; i < this->n_buffers; ++i) {\n COMMON_V4L2_CLEAR(this->buf);\n this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n this->buf.memory = V4L2_MEMORY_MMAP;\n this->buf.index = i;\n CommonV4l2_xioctl(this->fd, VIDIOC_QBUF, &this->buf);\n }\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n CommonV4l2_xioctl(this->fd, VIDIOC_STREAMON, &type);\n}\n\nvoid CommonV4l2_update_image(CommonV4l2 *this) {\n fd_set fds;\n int r;\n struct timeval tv;\n\n do {\n FD_ZERO(&fds);\n FD_SET(this->fd, &fds);\n\n /* Timeout. */\n tv.tv_sec = 2;\n tv.tv_usec = 0;\n\n r = select(this->fd + 1, &fds, NULL, NULL, &tv);\n } while ((r == -1 && (errno == EINTR)));\n if (r == -1) {\n perror("select");\n exit(EXIT_FAILURE);\n }\n COMMON_V4L2_CLEAR(this->buf);\n this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n this->buf.memory = V4L2_MEMORY_MMAP;\n CommonV4l2_xioctl(this->fd, VIDIOC_DQBUF, &this->buf);\n CommonV4l2_xioctl(this->fd, VIDIOC_QBUF, &this->buf);\n}\n\nchar * CommonV4l2_get_image(CommonV4l2 *this) {\n return ((char *)this->buffers[this->buf.index].start);\n}\n\nsize_t CommonV4l2_get_image_size(CommonV4l2 *this) {\n return this->buffers[this->buf.index].length;\n}\n\nvoid CommonV4l2_deinit(CommonV4l2 *this) {\n unsigned int i;\n enum v4l2_buf_type type;\n\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n CommonV4l2_xioctl(this->fd, VIDIOC_STREAMOFF, &type);\n for (i = 0; i < this->n_buffers; ++i)\n v4l2_munmap(this->buffers[i].start, this->buffers[i].length);\n v4l2_close(this->fd);\n free(this->buffers);\n}\n\n#endif\n</code></pre>\n<p>main.c</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\n#include "common_v4l2.h"\n\nstatic void save_ppm(\n unsigned int i,\n unsigned int x_res,\n unsigned int y_res,\n size_t data_lenght,\n char *data\n) {\n FILE *fout;\n char out_name[256];\n\n sprintf(out_name, "out%03d.ppm", i);\n fout = fopen(out_name, "w");\n if (!fout) {\n perror("error: fopen");\n exit(EXIT_FAILURE);\n }\n fprintf(fout, "P6\\n%d %d 255\\n", x_res, y_res);\n fwrite(data, data_lenght, 1, fout);\n fclose(fout);\n}\n\nint main(void) {\n CommonV4l2 common_v4l2;\n char *dev_name = "/dev/video0";\n struct buffer *buffers;\n unsigned int\n i,\n x_res = 640,\n y_res = 480\n ;\n\n CommonV4l2_init(&common_v4l2, dev_name, x_res, y_res);\n for (i = 0; i < 20; i++) {\n CommonV4l2_update_image(&common_v4l2);\n save_ppm(\n i,\n x_res,\n y_res,\n CommonV4l2_get_image_size(&common_v4l2),\n CommonV4l2_get_image(&common_v4l2)\n );\n }\n CommonV4l2_deinit(&common_v4l2);\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p>Upstream: <a href=\"https://github.com/cirosantilli/cpp-cheat/blob/be5d6444bddab93e95949b3388d92007b5ca916f/v4l2/common_v4l2.h\" rel=\"nofollow noreferrer\">https://github.com/cirosantilli/cpp-cheat/blob/be5d6444bddab93e95949b3388d92007b5ca916f/v4l2/common_v4l2.h</a></p>\n<p><strong>SDL</strong></p>\n<p>Video capture is in their roadmap: <a href=\"https://wiki.libsdl.org/Roadmap\" rel=\"nofollow noreferrer\">https://wiki.libsdl.org/Roadmap</a> and I bet it will wrap v4l on Linux.</p>\n<p>It will be sweet when we get that portability layer, with less bloat than OpenCV.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there any c library to get a video from the webcam on linux?
|
A lot of us use [OpenCV](http://opencv.willowgarage.com/wiki/) (cross-platform Computer Vision library, currently on v2.1)
The following snippet grabs frames from camera, converts them to grayscale and displays them on the screen:
```
#include <stdio.h>
#include "cv.h"
#include "highgui.h"
typedef IplImage* (*callback_prototype)(IplImage*);
/*
* make_it_gray: custom callback to convert a colored frame to its grayscale version.
* Remember that you must deallocate the returned IplImage* yourself after calling this function.
*/
IplImage* make_it_gray(IplImage* frame)
{
// Allocate space for a new image
IplImage* gray_frame = 0;
gray_frame = cvCreateImage(cvSize(frame->width, frame->height), frame->depth, 1);
if (!gray_frame)
{
fprintf(stderr, "!!! cvCreateImage failed!\n" );
return NULL;
}
cvCvtColor(frame, gray_frame, CV_RGB2GRAY);
return gray_frame;
}
/*
* process_video: retrieves frames from camera and executes a callback to do individual frame processing.
* Keep in mind that if your callback takes too much time to execute, you might loose a few frames from
* the camera.
*/
void process_video(callback_prototype custom_cb)
{
// Initialize camera
CvCapture *capture = 0;
capture = cvCaptureFromCAM(-1);
if (!capture)
{
fprintf(stderr, "!!! Cannot open initialize webcam!\n" );
return;
}
// Create a window for the video
cvNamedWindow("result", CV_WINDOW_AUTOSIZE);
IplImage* frame = 0;
char key = 0;
while (key != 27) // ESC
{
frame = cvQueryFrame(capture);
if(!frame)
{
fprintf( stderr, "!!! cvQueryFrame failed!\n" );
break;
}
// Execute callback on each frame
IplImage* processed_frame = (*custom_cb)(frame);
// Display processed frame
cvShowImage("result", processed_frame);
// Release resources
cvReleaseImage(&processed_frame);
// Exit when user press ESC
key = cvWaitKey(10);
}
// Free memory
cvDestroyWindow("result");
cvReleaseCapture(&capture);
}
int main( int argc, char **argv )
{
process_video(make_it_gray);
return 0;
}
```
|
278,121 |
<p>Its my understanding that the recommended approach to localization in WPF is to use the LocBaml tool to extract the localizable items into e.g. a csv file, translate the items into the desired language and regenerate a new sattelite assembly from this csv file. However from my experiments this seems to conflict with the generation of satellite assemblies from resources.resx files since neither is combining the resources into the single resource file but simply override any existing satellite assembly.</p>
<p>Is there a recommended approach (or even better, an existing tool) for doing a "merge" of output from LocBaml /generate and the output of running resgen on a resources.resx file (which is by default done by VS on builds). Are anybody out there tackling the same issues?</p>
|
[
{
"answer_id": 279432,
"author": "Sacha Bruttin",
"author_id": 20761,
"author_profile": "https://Stackoverflow.com/users/20761",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer to use the <a href=\"http://www.codeplex.com/WPFLocalizeExtension\" rel=\"nofollow noreferrer\">WPF Localization Extension</a> project that you can found on <a href=\"http://www.codeplex.com\" rel=\"nofollow noreferrer\">codeplex</a> to localize my WPF project.</p>\n\n<p>It lets you use the same approach than WinForms and is much easier to use than LocBaml.</p>\n"
},
{
"answer_id": 281042,
"author": "soren.enemaerke",
"author_id": 9222,
"author_profile": "https://Stackoverflow.com/users/9222",
"pm_score": 0,
"selected": false,
"text": "<p>Googled around a bit and found this page describing a few ways to use LocBaml which iuncludes a very detailed descripion on how to merge the resources.resx and locbaml generated resources into a single file (using al.exe). </p>\n\n<p><a href=\"http://www.codeproject.com/KB/WPF/WPFUsingLocbaml.aspx#link_29\" rel=\"nofollow noreferrer\" title=\"Localizing WPF using LocBaml\">Localizing WPF using LocBaml</a></p>\n\n<p>The page describes three ways to use LocBaml and I was looking for the last step in approach 3. Lots of good stuff in that article by the way</p>\n"
},
{
"answer_id": 992410,
"author": "Rick Strahl",
"author_id": 11197,
"author_profile": "https://Stackoverflow.com/users/11197",
"pm_score": 3,
"selected": true,
"text": "<p>You have to manually do this generating .resources from LocBaml and then merging the Resx and BAML resources using the Assembly linker. </p>\n\n<p>The process looks something like this:</p>\n\n<pre><code>LocBaml.exe /generate ..\\obj\\WpfLocalization.g.en-US.resources \n /trans:Res\\de.csv /out:de /culture:de\n\nREM Combine resource files w/ Assembly Linker\nal /template:WpfLocalization.exe \n /embed:de\\WpfLocalization.g.de.resources \n /embed:..\\..\\obj\\WpfLocalization.Properties.Resources.de.resources \n /culture:de /out:de\\WpfLocalization.resources.dll\n</code></pre>\n\n<p>(everything on one line in a batch file). </p>\n\n<p>You can put the above in a batch file customized for your project. Remember LocBaml has to in the same folder as your output files. You can add this as a post build task.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9222/"
] |
Its my understanding that the recommended approach to localization in WPF is to use the LocBaml tool to extract the localizable items into e.g. a csv file, translate the items into the desired language and regenerate a new sattelite assembly from this csv file. However from my experiments this seems to conflict with the generation of satellite assemblies from resources.resx files since neither is combining the resources into the single resource file but simply override any existing satellite assembly.
Is there a recommended approach (or even better, an existing tool) for doing a "merge" of output from LocBaml /generate and the output of running resgen on a resources.resx file (which is by default done by VS on builds). Are anybody out there tackling the same issues?
|
You have to manually do this generating .resources from LocBaml and then merging the Resx and BAML resources using the Assembly linker.
The process looks something like this:
```
LocBaml.exe /generate ..\obj\WpfLocalization.g.en-US.resources
/trans:Res\de.csv /out:de /culture:de
REM Combine resource files w/ Assembly Linker
al /template:WpfLocalization.exe
/embed:de\WpfLocalization.g.de.resources
/embed:..\..\obj\WpfLocalization.Properties.Resources.de.resources
/culture:de /out:de\WpfLocalization.resources.dll
```
(everything on one line in a batch file).
You can put the above in a batch file customized for your project. Remember LocBaml has to in the same folder as your output files. You can add this as a post build task.
|
278,122 |
<p>We're using Prototype for all of our Ajax request handling and to keep things simple we simple render HTML content which is then assigned to the appropriate div using the following function:</p>
<pre><code>function ajaxModify(controller, parameters, div_id)
{
var div = $(div_id);
var request = new Ajax.Request
(
controller,
{
method: "post",
parameters: parameters,
onSuccess: function(data) {
div.innerHTML = data.responseText;
},
onFailure: function() {
div.innerHTML = "Information Temporarily Unavailable";
}
}
);
}
</code></pre>
<p>However, I occasionally need to execute Javascript within the HTML response and this method appears incapable of doing that.</p>
<p>I'm trying to keep the list of functions for Ajax calls to a minimum for a number of reasons so if there is a way to modify the existing function without breaking everywhere that it is currently being used or a way to modify the HTML response that will cause any embedded javascript to execute that would great.</p>
<p>By way of note, I've already tried adding "evalJS : 'force'" to the function to see what it would do and it didn't help things any.</p>
|
[
{
"answer_id": 278138,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 5,
"selected": true,
"text": "<p>The parameter is:</p>\n\n<pre><code>evalScripts:true\n</code></pre>\n\n<p>Note that you should be using <strong>Ajax.Updater</strong>, not <strong>Ajax.Request</strong></p>\n\n<p>See: <a href=\"http://www.prototypejs.org/api/ajax/updater\" rel=\"noreferrer\">http://www.prototypejs.org/api/ajax/updater</a></p>\n\n<p>Ajax.Request will only process JavaScript if the response headers are:</p>\n\n<blockquote>\n <p>application/ecmascript,\n application/javascript,\n application/x-ecmascript,\n application/x-javascript,\n text/ecmascript, text/javascript,\n text/x-ecmascript, or\n text/x-javascript</p>\n</blockquote>\n\n<p>Whereas Ajax.Updater will process JS is evalScripts:true is set. Ajax.Request is geared toward data transport, such as getting a JSON response.</p>\n\n<p>Since you are updating HTML you should be using Ajax.Updater anyways.</p>\n"
},
{
"answer_id": 278139,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to do something like this:</p>\n\n<pre><code>div.innerHTML = \"<div onclick='someOtherFunctionTocall();'>\";\n</code></pre>\n\n<p>If you need to execute something at the same time as injecting the HTML, can you modify the signature of ajaxModify() by passing another parameter, which will be the javascript function you're going to execute (if it's not null - which let's you keep it optional, as you surely won't want to execute something on EVERY AJAX response).</p>\n"
},
{
"answer_id": 278152,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 1,
"selected": false,
"text": "<p>Does setting <code>evalScripts: true</code> as an option help?</p>\n"
},
{
"answer_id": 2085392,
"author": "Ray Chakrit",
"author_id": 253112,
"author_profile": "https://Stackoverflow.com/users/253112",
"pm_score": 0,
"selected": false,
"text": "<p>Just execute a custom my_function() after the ajax response</p>\n\n<pre><code>div.innerHTML=...ajax response text...\nmy_function()\n</code></pre>\n\n<p>then execute any function inside the custom my_function() </p>\n\n<pre><code>function my_function() {\n function_1()\n ...\n}\n</code></pre>\n\n<p>Note that my_function() should be somewhere outside the div.innerHTML.</p>\n"
},
{
"answer_id": 4515108,
"author": "yasha",
"author_id": 551889,
"author_profile": "https://Stackoverflow.com/users/551889",
"pm_score": -1,
"selected": false,
"text": "<p>you need to use eval() function to run the javascript in Ajax repose \nthis can be use full to separate the script and run it </p>\n\n<pre> \n\nfunction PaseAjaxResponse(somemixedcode)\n{\n var source = somemixedcode;\n var scripts = new Array();\n while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {\n var s = source.indexOf("<script");\n var s_e = source.indexOf(">", s);\n var e = source.indexOf("</script", s);\n var e_e = source.indexOf(">", e);\n scripts.push(source.substring(s_e+1, e));\n source = source.substring(0, s) + source.substring(e_e+1);\n}\nfor(var x=0; x<scripts.length; x++) {\ntry {\n eval(scripts[x]);\n}\ncatch(ex) {\n}\n}\nreturn source;\n}\n\n</pre>\n\n<p>alliteratively for more information see this\n<a href=\"http://www.yasha.co/Ajax/execute-javascript-on-Ajax-return/article-2.html\" rel=\"nofollow\">http://www.yasha.co/Ajax/execute-javascript-on-Ajax-return/article-2.html</a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
We're using Prototype for all of our Ajax request handling and to keep things simple we simple render HTML content which is then assigned to the appropriate div using the following function:
```
function ajaxModify(controller, parameters, div_id)
{
var div = $(div_id);
var request = new Ajax.Request
(
controller,
{
method: "post",
parameters: parameters,
onSuccess: function(data) {
div.innerHTML = data.responseText;
},
onFailure: function() {
div.innerHTML = "Information Temporarily Unavailable";
}
}
);
}
```
However, I occasionally need to execute Javascript within the HTML response and this method appears incapable of doing that.
I'm trying to keep the list of functions for Ajax calls to a minimum for a number of reasons so if there is a way to modify the existing function without breaking everywhere that it is currently being used or a way to modify the HTML response that will cause any embedded javascript to execute that would great.
By way of note, I've already tried adding "evalJS : 'force'" to the function to see what it would do and it didn't help things any.
|
The parameter is:
```
evalScripts:true
```
Note that you should be using **Ajax.Updater**, not **Ajax.Request**
See: <http://www.prototypejs.org/api/ajax/updater>
Ajax.Request will only process JavaScript if the response headers are:
>
> application/ecmascript,
> application/javascript,
> application/x-ecmascript,
> application/x-javascript,
> text/ecmascript, text/javascript,
> text/x-ecmascript, or
> text/x-javascript
>
>
>
Whereas Ajax.Updater will process JS is evalScripts:true is set. Ajax.Request is geared toward data transport, such as getting a JSON response.
Since you are updating HTML you should be using Ajax.Updater anyways.
|
278,132 |
<p>I need to impersonate myself as a domain user in a ASP.NET application running on VMWare machine. Since the VMWare machine is not itself in the domain, ASP.NET is unable to resolve the user token (specified in web.config). Is there a way to do that?</p>
<p>Thanks in advance,
Petr</p>
|
[
{
"answer_id": 278395,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": -1,
"selected": false,
"text": "<p>This may be the dumb obvious answer, but you could add your VMWare machine to the domain.</p>\n"
},
{
"answer_id": 278434,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 2,
"selected": true,
"text": "<p>I use this class I wrote all the time and it works like a charm!</p>\n\n<pre><code>using System;\nusing System.Security.Principal;\n\n/// <summary>\n/// Changes the security context the application runs under.\n/// </summary>\npublic class ImpersonateHelper : IDisposable\n{\n [System.Runtime.InteropServices.DllImport(\"Kernel32\")]\n private extern static Boolean CloseHandle(IntPtr handle);\n\n private IntPtr _token = IntPtr.Zero;\n private WindowsImpersonationContext _impersonatedUser = null;\n\n public IntPtr Token\n {\n get { return _token; }\n set { _token = value; }\n }\n\n public ImpersonateHelper(IntPtr token)\n {\n _token = token;\n }\n\n /// <summary>\n /// Switch the user to that set by the Token property\n /// </summary>\n public void Impersonate()\n {\n if (_token == IntPtr.Zero)\n _token = WindowsIdentity.GetCurrent().Token;\n\n _impersonatedUser = WindowsIdentity.Impersonate(_token);\n }\n\n /// <summary>\n /// Revert to the identity (user) before Impersonate() was called\n /// </summary>\n public void Undo()\n {\n if (_impersonatedUser != null)\n _impersonatedUser.Undo();\n }\n\n #region IDisposable Members\n private bool _isDisposed;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_isDisposed)\n {\n if (disposing)\n {\n if (_impersonatedUser != null)\n _impersonatedUser.Dispose();\n\n }\n CloseHandle(_token);\n _token = IntPtr.Zero;\n }\n _isDisposed = true;\n }\n\n ~ImpersonateHelper()\n {\n Dispose(false);\n }\n #endregion\n}\n</code></pre>\n\n<p>Then you call it from the client class as:</p>\n\n<pre><code>//Run task as the impersonated user and not as NETWORKSERVICE or ASPNET (in IIS5)\ntry{\n impersonate.Impersonate();\n //Do work that needs to run as domain user here...\n}\nfinally\n{\n //Revert impersonation to NETWORKSERVICE or ASPNET\n if (impersonate != null)\n {\n impersonate.Undo();\n impersonate.Dispose();\n }\n}\n</code></pre>\n\n<p>Good Luck!</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
] |
I need to impersonate myself as a domain user in a ASP.NET application running on VMWare machine. Since the VMWare machine is not itself in the domain, ASP.NET is unable to resolve the user token (specified in web.config). Is there a way to do that?
Thanks in advance,
Petr
|
I use this class I wrote all the time and it works like a charm!
```
using System;
using System.Security.Principal;
/// <summary>
/// Changes the security context the application runs under.
/// </summary>
public class ImpersonateHelper : IDisposable
{
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
private IntPtr _token = IntPtr.Zero;
private WindowsImpersonationContext _impersonatedUser = null;
public IntPtr Token
{
get { return _token; }
set { _token = value; }
}
public ImpersonateHelper(IntPtr token)
{
_token = token;
}
/// <summary>
/// Switch the user to that set by the Token property
/// </summary>
public void Impersonate()
{
if (_token == IntPtr.Zero)
_token = WindowsIdentity.GetCurrent().Token;
_impersonatedUser = WindowsIdentity.Impersonate(_token);
}
/// <summary>
/// Revert to the identity (user) before Impersonate() was called
/// </summary>
public void Undo()
{
if (_impersonatedUser != null)
_impersonatedUser.Undo();
}
#region IDisposable Members
private bool _isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
if (_impersonatedUser != null)
_impersonatedUser.Dispose();
}
CloseHandle(_token);
_token = IntPtr.Zero;
}
_isDisposed = true;
}
~ImpersonateHelper()
{
Dispose(false);
}
#endregion
}
```
Then you call it from the client class as:
```
//Run task as the impersonated user and not as NETWORKSERVICE or ASPNET (in IIS5)
try{
impersonate.Impersonate();
//Do work that needs to run as domain user here...
}
finally
{
//Revert impersonation to NETWORKSERVICE or ASPNET
if (impersonate != null)
{
impersonate.Undo();
impersonate.Dispose();
}
}
```
Good Luck!
|
278,137 |
<p>I am using some custom controls one of which is a tooltip controller that can display images, so I am using th ebelow code to instantiate it:</p>
<pre><code>Image newImage = Image.FromFile(imagePath);
e.ToolTipImage = newImage;
</code></pre>
<p>obviously could inline it but just testing at the moment. The trouble is the image is sometimes the wrong size, is there a way to set the display size. The only way I can currently see is editing the image using GDI+ or something like that. Seems like a lot of extra processing when I am only wanting to adjust display size not affect the actual image.</p>
|
[
{
"answer_id": 278166,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": true,
"text": "<p>Once you have an image object loaded from its source, the Height and Width (and Size, and all ancillary properties) are read-only. Therefore, you are stuck with GDI+ methods for resizing it in RAM and then displaying it accordingly. </p>\n\n<p>There are a lot of approaches you can take, but if you were to encapsulate that out to a library which you could reuse should this problem occur again, you'll be set to go. This isn't exactly optimized (IE, may have some bugs), but should give you an idea of how to approach it:</p>\n\n<pre><code>Image newImage = Image.FromFile(myFilePath);\nSize outputSize = new Size(200, 200);\nBitmap backgroundBitmap = new Bitmap(outputSize.Width, outputSize.Height);\nusing (Bitmap tempBitmap = new Bitmap(newImage))\n{\n using (Graphics g = Graphics.FromImage(backgroundBitmap))\n {\n g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n // Get the set of points that determine our rectangle for resizing.\n Point[] corners = {\n new Point(0, 0),\n new Point(backgroundBitmap.Width, 0),\n new Point(0, backgroundBitmap.Height)\n };\n g.DrawImage(tempBitmap, corners);\n }\n}\nthis.BackgroundImage = backgroundBitmap;\n</code></pre>\n\n<p>I did test this, and it worked. (It created a 200x200 resized version of one of my desktop wallpapers, then set that as the background image of the main form in a scratch WinForms project. You'll need <code>using</code> statements for <code>System.Drawing</code> and <code>System.Drawing.Drawing2D</code>.</p>\n"
},
{
"answer_id": 278225,
"author": "John Dunagan",
"author_id": 28939,
"author_profile": "https://Stackoverflow.com/users/28939",
"pm_score": 0,
"selected": false,
"text": "<p>In Winforms, if you contain the image inside a PictureBox control, the PictureBox control can be set to zoom to a particular height/width, and the image should conform.</p>\n\n<p>At least that's what happened in my Head First C# book when I did the exercise.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
I am using some custom controls one of which is a tooltip controller that can display images, so I am using th ebelow code to instantiate it:
```
Image newImage = Image.FromFile(imagePath);
e.ToolTipImage = newImage;
```
obviously could inline it but just testing at the moment. The trouble is the image is sometimes the wrong size, is there a way to set the display size. The only way I can currently see is editing the image using GDI+ or something like that. Seems like a lot of extra processing when I am only wanting to adjust display size not affect the actual image.
|
Once you have an image object loaded from its source, the Height and Width (and Size, and all ancillary properties) are read-only. Therefore, you are stuck with GDI+ methods for resizing it in RAM and then displaying it accordingly.
There are a lot of approaches you can take, but if you were to encapsulate that out to a library which you could reuse should this problem occur again, you'll be set to go. This isn't exactly optimized (IE, may have some bugs), but should give you an idea of how to approach it:
```
Image newImage = Image.FromFile(myFilePath);
Size outputSize = new Size(200, 200);
Bitmap backgroundBitmap = new Bitmap(outputSize.Width, outputSize.Height);
using (Bitmap tempBitmap = new Bitmap(newImage))
{
using (Graphics g = Graphics.FromImage(backgroundBitmap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Get the set of points that determine our rectangle for resizing.
Point[] corners = {
new Point(0, 0),
new Point(backgroundBitmap.Width, 0),
new Point(0, backgroundBitmap.Height)
};
g.DrawImage(tempBitmap, corners);
}
}
this.BackgroundImage = backgroundBitmap;
```
I did test this, and it worked. (It created a 200x200 resized version of one of my desktop wallpapers, then set that as the background image of the main form in a scratch WinForms project. You'll need `using` statements for `System.Drawing` and `System.Drawing.Drawing2D`.
|
278,160 |
<p>Are there ways to programmatically simulate connection problems (slow connection, response does not complete, connection gets dropped, etc.) when using the HttpWebRequest class?</p>
<p>Thanks</p>
<p>EDIT: To elaborate more, I need this for debugging but would want to turn it into a test eventually. I'm using the async methods BeginGetRequestStream, EndGetRequestStream, BeginGetResponse and EndGetResponse. I have wrapped them all in proper (I hope) Try Catch blocks which log the exceptions that happen.</p>
<p>I know this works for some cases (e.g. when I pull out the network cable). But on some rare occasions (i.e. only when the website I'm requesting is slow) then my system crashes and I get this in the Event Log</p>
<pre><code>Exception: System.Net.WebException
Message: The request was aborted: The connection was closed unexpectedly.
StackTrace: at System.Net.ConnectStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
at System.IO.Compression.DeflateStream.ReadCallback(IAsyncResult baseStreamResult)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.ContextAwareResult.CompleteCallback(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</code></pre>
<p>I am making an assumption it's from HttpWebRequest but then again all my code is wrapped in Try Catch blocks.</p>
<p>Would mocks help in such a case?</p>
|
[
{
"answer_id": 278258,
"author": "ajh1138",
"author_id": 13936,
"author_profile": "https://Stackoverflow.com/users/13936",
"pm_score": 0,
"selected": false,
"text": "<p>If you're in control of the site that's responding to the request, I'd say putting the thread to sleep for a while would simulate a slow response. System.Threading.Thread.Sleep(number of milliseconds)</p>\n\n<p>As for a dropped connection, I can't think of anything programmatic, but I've literally pulled out my network cable to simulate that condition.</p>\n"
},
{
"answer_id": 278263,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 2,
"selected": false,
"text": "<p>If this is for testing purposes - i.e. to inspect your's code behavior, I would suggest to create a class which inherits from from HttpWebRequest/HttpWebResponse, and override the methods you are interested in to behave the way you want - i.e. Thread.Sleep for delays, throw an exceptions, etc.</p>\n"
},
{
"answer_id": 278267,
"author": "Chris Rauber",
"author_id": 25939,
"author_profile": "https://Stackoverflow.com/users/25939",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming you are writing unit tests to cover the code, you could use a mocking framework (I personally prefer <a href=\"http://code.google.com/p/moq/\" rel=\"nofollow noreferrer\">Moq</a>) to mock out the implementation of the HttpWebRequest for any virtual methods on the class. In your mock, you can do your own implementation of how you want the test case to behave.</p>\n"
},
{
"answer_id": 584917,
"author": "David Keaveny",
"author_id": 319980,
"author_profile": "https://Stackoverflow.com/users/319980",
"pm_score": 2,
"selected": false,
"text": "<p>@Chris \nUnfortunately, Microsoft neglected to <a href=\"http://bartling.blogspot.com/2009/01/net-base-class-library-types-not.html\" rel=\"nofollow noreferrer\">make many of the BCL objects easily mockable</a>, as they tend to use abstract classes, and .NET classes are closed by design (in other words, for a method to be overridden by a subclass, it needs to be explicitly marked as virtual), whereas Java is open by design (that is, a subclass can override any method, unless they are marked as final). Using interfaces or marking the methods as virtual would have saved a lot of headaches in the testing space. Microsoft may have the testability religion now (e.g. ASP.NET MVC), but it's a bit late for the BCL.</p>\n\n<p>Typemock Isolator <a href=\"http://blog.typemock.com/2008/07/is-visibility-of-tested-methods.html\" rel=\"nofollow noreferrer\">may be able to help</a>, but I don't believe Moq can, in this case.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8280/"
] |
Are there ways to programmatically simulate connection problems (slow connection, response does not complete, connection gets dropped, etc.) when using the HttpWebRequest class?
Thanks
EDIT: To elaborate more, I need this for debugging but would want to turn it into a test eventually. I'm using the async methods BeginGetRequestStream, EndGetRequestStream, BeginGetResponse and EndGetResponse. I have wrapped them all in proper (I hope) Try Catch blocks which log the exceptions that happen.
I know this works for some cases (e.g. when I pull out the network cable). But on some rare occasions (i.e. only when the website I'm requesting is slow) then my system crashes and I get this in the Event Log
```
Exception: System.Net.WebException
Message: The request was aborted: The connection was closed unexpectedly.
StackTrace: at System.Net.ConnectStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
at System.IO.Compression.DeflateStream.ReadCallback(IAsyncResult baseStreamResult)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.ContextAwareResult.CompleteCallback(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
```
I am making an assumption it's from HttpWebRequest but then again all my code is wrapped in Try Catch blocks.
Would mocks help in such a case?
|
If this is for testing purposes - i.e. to inspect your's code behavior, I would suggest to create a class which inherits from from HttpWebRequest/HttpWebResponse, and override the methods you are interested in to behave the way you want - i.e. Thread.Sleep for delays, throw an exceptions, etc.
|
278,163 |
<p>I need to catch the HTML of a ASP.NET just before it is being sent to the client in order to do last minute string manipulations on it, and then send the modified version to the client.</p>
<p>e.g.</p>
<p>The Page is loaded
Every control has been rendered correctly
The Full html of the page is ready to be transferred back to the client</p>
<p>Is there a way to that in ASP.NET?</p>
|
[
{
"answer_id": 278178,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx\" rel=\"nofollow noreferrer\">HTTPModule</a> to change the html. Here is a <a href=\"http://www.darkside.co.za/archive/2008/03/03/web-page-optmisation-using-httpmodule.aspx\" rel=\"nofollow noreferrer\">sample</a>.</p>\n"
},
{
"answer_id": 278182,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the sequence of events in the ASP.NET page's lifecycle. <a href=\"http://msdn.microsoft.com/en-us/library/dct97kc3.aspx\" rel=\"nofollow noreferrer\">Here's</a> one page that lists the events. It's possible you could find an event to handle that's late enough in the page's lifecycle to make your changes, but still get those changes rendered.</p>\n\n<p>If not, you could always write an HttpModule that processes the HTTP response after the page itself has finished rendering.</p>\n"
},
{
"answer_id": 278191,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think there is a specific event from the page that you can hook into; here is the ASP.Net lifecycle: <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p>\n\n<p>You may want to consider hooking into the prerender event to 'adjust' the values of the controls, or perform some client side edits/callbacks.</p>\n"
},
{
"answer_id": 278230,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Obviously it will be much more efficient if you can coax the desired markup out of ASP.Net in the first place. </p>\n\n<p>With that in mind, have you considered using <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx\" rel=\"nofollow noreferrer\">Control Adapters</a>? They will allow you to over-ride how each of your controls render in the first place, rather than having to modify the string later.</p>\n"
},
{
"answer_id": 288740,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 5,
"selected": true,
"text": "<p>You can override the Render method of your page. Then call the base implementation and supply your HtmlTextWriter object. Here is an example</p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\n StringWriter output = new StringWriter();\n base.Render(new HtmlTextWriter(output));\n //This is the rendered HTML of your page. Feel free to manipulate it.\n string outputAsString = output.ToString();\n\n writer.Write(outputAsString);\n}\n</code></pre>\n"
},
{
"answer_id": 17639722,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 1,
"selected": false,
"text": "<p>Using the <a href=\"https://stackoverflow.com/a/288740/107625\">answer of Atanas Korchev</a> for some days, I discovered that I get JavaScript errors similar to:</p>\n\n<blockquote>\n <p>\"The message received from the server could not be parsed\"</p>\n</blockquote>\n\n<p>When using this in conjunction with an ASP.NET Ajax <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.aspx\" rel=\"nofollow noreferrer\"><code>UpdatePanel</code> control</a>. <a href=\"http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx\" rel=\"nofollow noreferrer\">The reason is described in this blog post</a>.</p>\n\n<p>Basically the <code>UpdatePanel</code> seems to be critical about the exact length of the rendered string being constant. I.e. if you change the string and <em>keep</em> the length, it succeeds, if you change the text so that the string length changes, the above JavaScript error occurs.</p>\n\n<p>My not-perfect-but-working solution was to assume the <code>UpdatePanel</code> always does a POST and filter that away:</p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\n if (IsPostBack || IsCallback)\n {\n base.Render(writer);\n }\n else\n {\n using (var output = new StringWriter())\n {\n base.Render(new HtmlTextWriter(output));\n\n var outputAsString = output.ToString();\n outputAsString = doSomeManipulation(outputAsString);\n\n writer.Write(outputAsString);\n }\n }\n}\n</code></pre>\n\n<p>This works in my scenario but has some drawbacks that may not work for your scenario:</p>\n\n<ul>\n<li>Upon postbacks, no strings are changed.</li>\n<li>The string that the user sees therefore is the unmanipulated one</li>\n<li>The <code>UpdatePanel</code> may fire for NON-postbacks, too.</li>\n</ul>\n\n<p>Still, I hope this helps others who discover a similar issue. Also, <a href=\"http://7daysageek.blogspot.de/2009/03/aspnet-updatepanel-and-overriding.html\" rel=\"nofollow noreferrer\">see this article discussing <code>UpdatePanel</code> and <code>Page.Render</code> in more details</a>.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32582/"
] |
I need to catch the HTML of a ASP.NET just before it is being sent to the client in order to do last minute string manipulations on it, and then send the modified version to the client.
e.g.
The Page is loaded
Every control has been rendered correctly
The Full html of the page is ready to be transferred back to the client
Is there a way to that in ASP.NET?
|
You can override the Render method of your page. Then call the base implementation and supply your HtmlTextWriter object. Here is an example
```
protected override void Render(HtmlTextWriter writer)
{
StringWriter output = new StringWriter();
base.Render(new HtmlTextWriter(output));
//This is the rendered HTML of your page. Feel free to manipulate it.
string outputAsString = output.ToString();
writer.Write(outputAsString);
}
```
|
278,186 |
<p>I've got a simple little WPF app with a TextBox and a WebBrowser control. As I type into the TextBox the WebBrowser updates with its content.</p>
<p>But on each keystroke, when the WebBrowser updates, it makes a click sound. How can I disable the WebBrowser control's refresh click sound?</p>
<p><a href="http://img411.imageshack.us/img411/2296/appbz9.jpg" rel="nofollow noreferrer">WPF TextBox and WebBrowser controls http://img411.imageshack.us/img411/2296/appbz9.jpg</a></p>
<p>My XAML...</p>
<pre><code><TextBox Name="MyTextBox"
...
TextChanged="MyTextBox_TextChanged"
TextWrapping="Wrap"
AcceptsReturn="True"
VerticalScrollBarVisibility="Visible" />
<WebBrowser Name="MyWebBrowser" ... />
</code></pre>
<p>My Visual Basic code...</p>
<pre>
Private Sub MyTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
If Not MyTextBox.Text = String.Empty Then
MyWebBrowser.NavigateToString(MyTextBox.Text)
Else
MyWebBrowser.Source = Nothing
End If
End Sub
</pre>
|
[
{
"answer_id": 278178,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule.aspx\" rel=\"nofollow noreferrer\">HTTPModule</a> to change the html. Here is a <a href=\"http://www.darkside.co.za/archive/2008/03/03/web-page-optmisation-using-httpmodule.aspx\" rel=\"nofollow noreferrer\">sample</a>.</p>\n"
},
{
"answer_id": 278182,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the sequence of events in the ASP.NET page's lifecycle. <a href=\"http://msdn.microsoft.com/en-us/library/dct97kc3.aspx\" rel=\"nofollow noreferrer\">Here's</a> one page that lists the events. It's possible you could find an event to handle that's late enough in the page's lifecycle to make your changes, but still get those changes rendered.</p>\n\n<p>If not, you could always write an HttpModule that processes the HTTP response after the page itself has finished rendering.</p>\n"
},
{
"answer_id": 278191,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think there is a specific event from the page that you can hook into; here is the ASP.Net lifecycle: <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p>\n\n<p>You may want to consider hooking into the prerender event to 'adjust' the values of the controls, or perform some client side edits/callbacks.</p>\n"
},
{
"answer_id": 278230,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Obviously it will be much more efficient if you can coax the desired markup out of ASP.Net in the first place. </p>\n\n<p>With that in mind, have you considered using <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx\" rel=\"nofollow noreferrer\">Control Adapters</a>? They will allow you to over-ride how each of your controls render in the first place, rather than having to modify the string later.</p>\n"
},
{
"answer_id": 288740,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 5,
"selected": true,
"text": "<p>You can override the Render method of your page. Then call the base implementation and supply your HtmlTextWriter object. Here is an example</p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\n StringWriter output = new StringWriter();\n base.Render(new HtmlTextWriter(output));\n //This is the rendered HTML of your page. Feel free to manipulate it.\n string outputAsString = output.ToString();\n\n writer.Write(outputAsString);\n}\n</code></pre>\n"
},
{
"answer_id": 17639722,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 1,
"selected": false,
"text": "<p>Using the <a href=\"https://stackoverflow.com/a/288740/107625\">answer of Atanas Korchev</a> for some days, I discovered that I get JavaScript errors similar to:</p>\n\n<blockquote>\n <p>\"The message received from the server could not be parsed\"</p>\n</blockquote>\n\n<p>When using this in conjunction with an ASP.NET Ajax <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.aspx\" rel=\"nofollow noreferrer\"><code>UpdatePanel</code> control</a>. <a href=\"http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx\" rel=\"nofollow noreferrer\">The reason is described in this blog post</a>.</p>\n\n<p>Basically the <code>UpdatePanel</code> seems to be critical about the exact length of the rendered string being constant. I.e. if you change the string and <em>keep</em> the length, it succeeds, if you change the text so that the string length changes, the above JavaScript error occurs.</p>\n\n<p>My not-perfect-but-working solution was to assume the <code>UpdatePanel</code> always does a POST and filter that away:</p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\n if (IsPostBack || IsCallback)\n {\n base.Render(writer);\n }\n else\n {\n using (var output = new StringWriter())\n {\n base.Render(new HtmlTextWriter(output));\n\n var outputAsString = output.ToString();\n outputAsString = doSomeManipulation(outputAsString);\n\n writer.Write(outputAsString);\n }\n }\n}\n</code></pre>\n\n<p>This works in my scenario but has some drawbacks that may not work for your scenario:</p>\n\n<ul>\n<li>Upon postbacks, no strings are changed.</li>\n<li>The string that the user sees therefore is the unmanipulated one</li>\n<li>The <code>UpdatePanel</code> may fire for NON-postbacks, too.</li>\n</ul>\n\n<p>Still, I hope this helps others who discover a similar issue. Also, <a href=\"http://7daysageek.blogspot.de/2009/03/aspnet-updatepanel-and-overriding.html\" rel=\"nofollow noreferrer\">see this article discussing <code>UpdatePanel</code> and <code>Page.Render</code> in more details</a>.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
I've got a simple little WPF app with a TextBox and a WebBrowser control. As I type into the TextBox the WebBrowser updates with its content.
But on each keystroke, when the WebBrowser updates, it makes a click sound. How can I disable the WebBrowser control's refresh click sound?
[WPF TextBox and WebBrowser controls http://img411.imageshack.us/img411/2296/appbz9.jpg](http://img411.imageshack.us/img411/2296/appbz9.jpg)
My XAML...
```
<TextBox Name="MyTextBox"
...
TextChanged="MyTextBox_TextChanged"
TextWrapping="Wrap"
AcceptsReturn="True"
VerticalScrollBarVisibility="Visible" />
<WebBrowser Name="MyWebBrowser" ... />
```
My Visual Basic code...
```
Private Sub MyTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
If Not MyTextBox.Text = String.Empty Then
MyWebBrowser.NavigateToString(MyTextBox.Text)
Else
MyWebBrowser.Source = Nothing
End If
End Sub
```
|
You can override the Render method of your page. Then call the base implementation and supply your HtmlTextWriter object. Here is an example
```
protected override void Render(HtmlTextWriter writer)
{
StringWriter output = new StringWriter();
base.Render(new HtmlTextWriter(output));
//This is the rendered HTML of your page. Feel free to manipulate it.
string outputAsString = output.ToString();
writer.Write(outputAsString);
}
```
|
278,189 |
<p>What is the string concatenation operator in Oracle SQL? </p>
<p>Are there any "interesting" features I should be careful of? </p>
<p>(This seems obvious, but I couldn't find a previous question asking it). </p>
|
[
{
"answer_id": 278198,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 9,
"selected": true,
"text": "<p>It is <code>||</code>, for example:</p>\n\n<pre><code>select 'Mr ' || ename from emp;\n</code></pre>\n\n<p>The only \"interesting\" feature I can think of is that <code>'x' || null</code> returns <code>'x'</code>, not <code>null</code> as you might perhaps expect.</p>\n"
},
{
"answer_id": 279351,
"author": "Gary Myers",
"author_id": 25714,
"author_profile": "https://Stackoverflow.com/users/25714",
"pm_score": 6,
"selected": false,
"text": "<p>There's also concat, but it doesn't get used much</p>\n\n<pre><code>select concat('a','b') from dual;\n</code></pre>\n"
},
{
"answer_id": 33642495,
"author": "Ankur",
"author_id": 5548870,
"author_profile": "https://Stackoverflow.com/users/5548870",
"pm_score": 3,
"selected": false,
"text": "<pre><code>DECLARE\n a VARCHAR2(30);\n b VARCHAR2(30);\n c VARCHAR2(30);\n BEGIN\n a := ' Abc '; \n b := ' def ';\n c := a || b;\n DBMS_OUTPUT.PUT_LINE(c); \n END;\n</code></pre>\n\n<p>output:: Abc def</p>\n"
},
{
"answer_id": 33647100,
"author": "Fabio Fantoni",
"author_id": 4689391,
"author_profile": "https://Stackoverflow.com/users/4689391",
"pm_score": 4,
"selected": false,
"text": "<p>I would suggest concat when dealing with 2 strings, and || when those strings are more than 2:</p>\n\n<pre><code>select concat(a,b)\n from dual\n</code></pre>\n\n<p>or</p>\n\n<pre><code> select 'a'||'b'||'c'||'d'\n from dual\n</code></pre>\n"
},
{
"answer_id": 60938444,
"author": "Grant Shannon",
"author_id": 6044312,
"author_profile": "https://Stackoverflow.com/users/6044312",
"pm_score": 2,
"selected": false,
"text": "<p>Using <code>CONCAT(CONCAT(,),)</code> worked for me when concatenating more than two strings. </p>\n\n<p>My problem required working with date strings (only) and creating <code>YYYYMMDD</code> from <code>YYYY-MM-DD</code> as follows (i.e. without converting to date format):</p>\n\n<pre><code>CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD\n</code></pre>\n"
},
{
"answer_id": 71880957,
"author": "Du-Lacoste",
"author_id": 3600553,
"author_profile": "https://Stackoverflow.com/users/3600553",
"pm_score": 2,
"selected": false,
"text": "<p>There are two ways to concatenate Strings in <code>Oracle SQL</code>. Either using <code>CONCAT</code> function or <code>||</code> operator.</p>\n<p><code>CONCAT</code> function allows you to concatenate two strings together</p>\n<pre><code>SELECT CONCAT( string1, string2 ) FROM dual;\n</code></pre>\n<p>Since <code>CONCAT</code> function will only <strong>allow you to concatenate two values together</strong>. If you want to concatenate more values than two, you can n<strong>est multiple CONCAT function</strong> calls.</p>\n<pre><code>SELECT CONCAT(CONCAT('A', 'B'),'C') FROM dual;\n</code></pre>\n<p>An alternative to using the <code>CONCAT</code> function would be to use the <strong>||</strong> operator</p>\n<pre><code>SELECT 'My Name' || 'My Age' FROM dual;\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] |
What is the string concatenation operator in Oracle SQL?
Are there any "interesting" features I should be careful of?
(This seems obvious, but I couldn't find a previous question asking it).
|
It is `||`, for example:
```
select 'Mr ' || ename from emp;
```
The only "interesting" feature I can think of is that `'x' || null` returns `'x'`, not `null` as you might perhaps expect.
|
278,192 |
<p>How do I view the history of an individual file with complete details of what has changed?</p>
<p><code>git log -- [filename]</code> shows me the commit history of a file, but how do I see the file content that changed?</p>
|
[
{
"answer_id": 278239,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using the <a href=\"https://git-scm.com/docs/git-gui\" rel=\"nofollow noreferrer\">Git GUI</a> (on Windows):</p>\n<p>Under the <code>Repository</code> menu, you can use <code>Visualize master's History</code>.</p>\n<p>Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.</p>\n"
},
{
"answer_id": 278242,
"author": "VolkA",
"author_id": 25472,
"author_profile": "https://Stackoverflow.com/users/25472",
"pm_score": 11,
"selected": false,
"text": "<p>This lets Git generate the patches for each log entry:</p>\n<pre><code>git log -p -- filename\n</code></pre>\n<p>See <a href=\"https://git-scm.com/docs/git-log\" rel=\"noreferrer\"><code>git help log</code></a> for more options — it can actually do a lot of nice things. :)</p>\n<hr />\n<p>To get just the diff for a specific commit, use</p>\n<pre><code>git show HEAD\n</code></pre>\n<p>or specify any other revision by identifier.</p>\n<hr />\n<p>To browse the changes visually:</p>\n<pre><code>gitk\n</code></pre>\n"
},
{
"answer_id": 280140,
"author": "farktronix",
"author_id": 677,
"author_profile": "https://Stackoverflow.com/users/677",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-whatchanged.html\" rel=\"noreferrer\"><code>git whatchanged -p filename</code></a> is also equivalent to <a href=\"http://git-scm.com/docs/git-log\" rel=\"noreferrer\"><code>git log -p filename</code></a> in this case.</p>\n\n<p>You can also see when a specific line of code inside a file was changed with <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-blame.html\" rel=\"noreferrer\"><code>git blame filename</code></a>. This will print out a short commit id, the author, timestamp, and complete line of code for every line in the file. \nThis is very useful after you've found a bug and you want to know when it was introduced (or who's fault it was).</p>\n"
},
{
"answer_id": 1321962,
"author": "Claudio Acciaresi",
"author_id": 48696,
"author_profile": "https://Stackoverflow.com/users/48696",
"pm_score": 12,
"selected": true,
"text": "<p>For a graphical view, use <a href=\"https://git-scm.com/docs/gitk/\" rel=\"noreferrer\"><code>gitk</code></a>:</p>\n<pre><code>gitk [filename]\n</code></pre>\n<p>To follow the file across file renames:</p>\n<pre><code>gitk --follow [filename]\n</code></pre>\n"
},
{
"answer_id": 3458509,
"author": "yllohy",
"author_id": 417241,
"author_profile": "https://Stackoverflow.com/users/417241",
"pm_score": 6,
"selected": false,
"text": "<p>To show what revision and author last modified each line of a file:</p>\n\n<pre><code>git blame filename\n</code></pre>\n\n<p>or if you want to use the powerful blame GUI:</p>\n\n<pre><code>git gui blame filename\n</code></pre>\n"
},
{
"answer_id": 3737313,
"author": "George Anderson",
"author_id": 47292,
"author_profile": "https://Stackoverflow.com/users/47292",
"pm_score": 4,
"selected": false,
"text": "<p>Or: </p>\n\n<p><code>gitx -- <path/to/filename></code></p>\n\n<p>if you're using <a href=\"http://gitx.frim.nl/\" rel=\"noreferrer\">gitx</a></p>\n"
},
{
"answer_id": 5493663,
"author": "Dan Moulding",
"author_id": 95706,
"author_profile": "https://Stackoverflow.com/users/95706",
"pm_score": 11,
"selected": false,
"text": "<pre><code>git log --follow -p -- path-to-file\n</code></pre>\n<p>This will show the <strong>entire</strong> history of the file (including history beyond renames and with diffs for each change).</p>\n<p>In other words, if the file named <code>bar</code> was once named <code>foo</code>, then <code>git log -p bar</code> (without the <code>--follow</code> option) will only show the file's history up to the point where it was renamed -- it won't show the file's history when it was known as <code>foo</code>. Using <code>git log --follow -p bar</code> will show the file's entire history, including any changes to the file when it was known as <code>foo</code>. The <code>-p</code> option ensures that diffs are included for each change.</p>\n"
},
{
"answer_id": 8336904,
"author": "Malks",
"author_id": 627844,
"author_profile": "https://Stackoverflow.com/users/627844",
"pm_score": 3,
"selected": false,
"text": "<p>The answer I was looking for wasn't here. It was to see changes in files that I'd staged for commit. I.e.,</p>\n<pre><code>git diff --cached\n</code></pre>\n"
},
{
"answer_id": 10929943,
"author": "Falken",
"author_id": 194443,
"author_profile": "https://Stackoverflow.com/users/194443",
"pm_score": 8,
"selected": false,
"text": "<p><strong><a href=\"https://github.com/jonas/tig\" rel=\"noreferrer\"><code>tig</code></a></strong> is a terminal-based viewer with color support similar to the GUI-based <a href=\"https://git-scm.com/docs/gitk\" rel=\"noreferrer\"><code>gitk</code></a>.</p>\n<p>Quick Install:</p>\n<ul>\n<li><strong><a href=\"https://en.wikipedia.org/wiki/APT_(software)\" rel=\"noreferrer\">APT</a></strong>: <code>apt-get install tig</code></li>\n<li><strong><a href=\"https://en.wikipedia.org/wiki/Homebrew_(package_manager)\" rel=\"noreferrer\">Homebrew</a> (OS X)</strong>: <code>$ brew install tig</code></li>\n</ul>\n<p>Use it to view history on a single file: <code>tig [filename]</code></p>\n<p>Or browse the detailed repository history via: <code>tig</code></p>\n"
},
{
"answer_id": 11847622,
"author": "Adi Shavit",
"author_id": 135862,
"author_profile": "https://Stackoverflow.com/users/135862",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to see the whole history of a file, <em>including</em> on <em>all other</em> branches use:</p>\n\n<pre><code>gitk --all <filename>\n</code></pre>\n"
},
{
"answer_id": 13448672,
"author": "Jian",
"author_id": 1205529,
"author_profile": "https://Stackoverflow.com/users/1205529",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote <a href=\"https://github.com/jianli/git-playback\" rel=\"noreferrer\">git-playback</a> for this exact purpose</p>\n\n<pre><code>pip install git-playback\ngit playback [filename]\n</code></pre>\n\n<p>This has the benefit of both displaying the results in the command line (like <code>git log -p</code>) while also letting you step through each commit using the arrow keys (like <code>gitk</code>).</p>\n"
},
{
"answer_id": 13609201,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "<p>With the excellent <a href=\"http://gitextensions.github.io/\" rel=\"nofollow noreferrer\">Git Extensions</a>, you go to a point in the history where the file still existed (if it have been deleted, otherwise just go to HEAD), switch to the <code>File tree</code> tab, right-click on the file and choose <code>File history</code>.</p>\n<p>By default, it follows the file through the renames, and the <code>Blame</code> tab allows to see the name at a given revision.</p>\n<p>It has some minor gotchas, like showing <code>fatal: Not a valid object name</code> in the <code>View</code> tab when clicking on the deletion revision, but I can live with that. :-)</p>\n"
},
{
"answer_id": 13730108,
"author": "John Lawrence Aspden",
"author_id": 254837,
"author_profile": "https://Stackoverflow.com/users/254837",
"pm_score": 6,
"selected": false,
"text": "<p>Summary of other answers after reading through them and playing a bit:</p>\n<p>The usual command line command would be</p>\n<pre><code>git log --follow --all -p dir/file.c\n</code></pre>\n<p>But you can also use either <a href=\"https://git-scm.com/docs/gitk\" rel=\"noreferrer\">gitk</a> (GUI) or tig (text UI) to give much more human-readable ways of looking at it.</p>\n<pre><code>gitk --follow --all -p dir/file.c\n\ntig --follow --all -p dir/file.c\n</code></pre>\n<p>Under <a href=\"https://en.wikipedia.org/wiki/Debian\" rel=\"noreferrer\">Debian</a>/<a href=\"https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29\" rel=\"noreferrer\">Ubuntu</a>, the install command for these lovely tools is as expected:</p>\n<pre><code>sudo apt-get install gitk tig\n</code></pre>\n<p>And I'm currently using:</p>\n<pre><code>alias gdf='gitk --follow --all -p'\n</code></pre>\n<p>so that I can just type <code>gdf dir</code> to get a focussed history of everything in subdirectory <code>dir</code>.</p>\n"
},
{
"answer_id": 14128028,
"author": "AhHatem",
"author_id": 692699,
"author_profile": "https://Stackoverflow.com/users/692699",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using <a href=\"https://en.wikipedia.org/wiki/Eclipse_%28software%29\" rel=\"nofollow noreferrer\">Eclipse</a> with the Git plugin, it has an excellent comparison view with history. Right click the file and select "Compare With" → "History".</p>\n"
},
{
"answer_id": 16654730,
"author": "Lukasz Czerwinski",
"author_id": 330067,
"author_profile": "https://Stackoverflow.com/users/330067",
"pm_score": 2,
"selected": false,
"text": "<p><code>git diff -U <filename></code> give you a unified diff. </p>\n\n<p>It should be colored on red and green. If it's not, run: <code>git config color.ui auto</code> first.</p>\n"
},
{
"answer_id": 17329576,
"author": "Palesz",
"author_id": 88355,
"author_profile": "https://Stackoverflow.com/users/88355",
"pm_score": 5,
"selected": false,
"text": "<p>Add this alias to your .gitconfig:</p>\n\n<pre><code>[alias]\n lg = log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\\n--abbrev-commit --date=relative\n</code></pre>\n\n<p>And use the command like this:</p>\n\n<pre><code>> git lg\n> git lg -- filename\n</code></pre>\n\n<p>The output will look almost exactly the same as the gitk output. Enjoy.</p>\n"
},
{
"answer_id": 17955109,
"author": "Mark Fox",
"author_id": 934195,
"author_profile": "https://Stackoverflow.com/users/934195",
"pm_score": 7,
"selected": false,
"text": "<h2>Sourcetree users</h2>\n<p>If you use Sourcetree to visualize your repository (it's free and quite good) you can right click a file and select <strong>Log Selected</strong></p>\n<p><img src=\"https://i.stack.imgur.com/CHvfE.png\" alt=\"Enter image description here\" /></p>\n<p>The display (below) is much friendlier than <a href=\"https://git-scm.com/docs/gitk\" rel=\"noreferrer\">gitk</a> and most the other options listed. Unfortunately (at this time) there is no easy way to launch this view from the command line — Sourcetree's CLI currently just opens repositories.</p>\n<p><img src=\"https://i.stack.imgur.com/Y9ALz.png\" alt=\"Enter image description here\" /></p>\n"
},
{
"answer_id": 31975658,
"author": "user3885927",
"author_id": 3885927,
"author_profile": "https://Stackoverflow.com/users/3885927",
"pm_score": 3,
"selected": false,
"text": "<p>If you use TortoiseGit you should be able to right click on the file and do <code>TortoiseGit --> Show Log</code>. In the window that pops up, make sure:</p>\n\n<ul>\n<li><p>'<code>Show Whole Project</code>' option is not checked.</p></li>\n<li><p>'<code>All Branches</code>' option is checked.</p></li>\n</ul>\n"
},
{
"answer_id": 31980285,
"author": "jitendrapurohit",
"author_id": 4243217,
"author_profile": "https://Stackoverflow.com/users/4243217",
"pm_score": 4,
"selected": false,
"text": "<p>You can also try this which lists the commits that has changed a specific part of a file (implemented in Git 1.8.4).</p>\n<p>The result returned would be the list of commits that modified this particular part. Command:</p>\n<pre><code>git log --pretty=short -u -L <upperLimit>,<lowerLimit>:<path_to_filename>\n</code></pre>\n<p>where upperLimit is the start line number and lowerLimit is the ending line number of the file.</p>\n<p>More details are at <em><a href=\"http://techpurohit.in/list-some-useful-git-commands\" rel=\"nofollow noreferrer\">http://techpurohit.in/list-some-useful-git-commands</a></em>.</p>\n"
},
{
"answer_id": 33629385,
"author": "lang2",
"author_id": 172265,
"author_profile": "https://Stackoverflow.com/users/172265",
"pm_score": 5,
"selected": false,
"text": "<p>Lately I discovered <code>tig</code> and found it very useful. There are some cases I'd wish it does A or B but most of the time it's rather neat.</p>\n<p>For your case, <code>tig <filename></code> might be what you're looking for.</p>\n<p><a href=\"https://jonas.github.io/tig/\" rel=\"nofollow noreferrer\">https://jonas.github.io/tig/</a></p>\n"
},
{
"answer_id": 37566413,
"author": "Antonín Slejška",
"author_id": 3886962,
"author_profile": "https://Stackoverflow.com/users/3886962",
"pm_score": 3,
"selected": false,
"text": "<p><strong><a href=\"http://www.syntevo.com/smartgit/\" rel=\"noreferrer\">SmartGit</a>:</strong></p>\n\n<ol>\n<li>In the menu enable to display unchanged files: View / Show unchanged files</li>\n<li>Right click the file and select 'Log' or press 'Ctrl-L'</li>\n</ol>\n"
},
{
"answer_id": 56122874,
"author": "foxiris",
"author_id": 2469567,
"author_profile": "https://Stackoverflow.com/users/2469567",
"pm_score": 5,
"selected": false,
"text": "<p>You can use Visual Studio Code with <a href=\"https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens\" rel=\"noreferrer\">GitLens</a>. It's a very powerful tool.</p>\n<p>After having installed GitLens, go to GitLens tab, select <code>FILE HISTORY</code> and you can browse it.</p>\n<p><a href=\"https://i.stack.imgur.com/H0j9A.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/H0j9A.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 60893144,
"author": "oracleif",
"author_id": 8469665,
"author_profile": "https://Stackoverflow.com/users/8469665",
"pm_score": 1,
"selected": false,
"text": "<p>I'm probably about where the OP was when this started, looking for something simple that would let me use <em>git difftool</em> with <em>vimdiff</em> to review changes to files in my repo starting from a specific commit. I wasn't too happy with answers I was finding, so I threw this <strong>git inc</strong>remental <strong>rep</strong>orter (gitincrep) script together and it's been useful to me:</p>\n\n<pre><code>#!/usr/bin/env bash\n\nSTARTWITH=\"${1:-}\"\nshift 1\n\nDFILES=( \"$@\" )\n\nRunDiff()\n{\n GIT1=$1\n GIT2=$2\n shift 2\n\n if [ \"$(git diff $GIT1 $GIT2 \"$@\")\" ]\n then\n git log ${GIT1}..${GIT2}\n git difftool --tool=vimdiff $GIT1 $GIT2 \"$@\"\n fi\n}\n\nOLDVERS=\"\"\nRUNDIFF=\"\"\n\nfor NEWVERS in $(git log --format=format:%h --reverse)\ndo\n if [ \"$RUNDIFF\" ]\n then\n RunDiff $OLDVERS $NEWVERS \"${DFILES[@]}\"\n elif [ \"$OLDVERS\" ]\n then\n if [ \"$NEWVERS\" = \"${STARTWITH:=${NEWVERS}}\" ]\n then\n RUNDIFF=true\n RunDiff $OLDVERS $NEWVERS \"${DFILES[@]}\"\n fi\n fi\n OLDVERS=$NEWVERS\ndone\n\n</code></pre>\n\n<p>Called with no args, this will start from the beginning of the repo history, otherwise it will start with whatever abbreviated commit hash you provide and proceed to the present - you can ctrl-C at any time to exit. Any args after the first will limit the difference reports to include only the files listed among those args (which I think is what the OP wanted, and I'd recommend for all but tiny projects). If you're checking changes to specific files <strong>and</strong> want to start from the beginning, you'll need to provide an empty string for arg1. If you're not a vim user, you can replace <em>vimdiff</em> with your favorite diff tool.</p>\n\n<p>Behavior is to output the commit comments when relevant changes are found and start offering <em>vimdiff</em> runs for each changed file (that's <em>git difftool</em> behavior, but it works here).</p>\n\n<p>This approach is probably pretty naive, but looking through a lot of the solutions here and at a related post, many involved installing new tools on a system where I don't have admin access, with interfaces that had their own learning curve. The above script did what I wanted without dealing with any of that. I'll look into the many excellent suggestions here when I need something more sophisticated - but I think this is directly responsive to the OP.</p>\n"
},
{
"answer_id": 60942056,
"author": "savvyBrar",
"author_id": 2892892,
"author_profile": "https://Stackoverflow.com/users/2892892",
"pm_score": 4,
"selected": false,
"text": "<p>In the <a href=\"https://www.sourcetreeapp.com/\" rel=\"noreferrer\">Sourcetree</a> UI, you can find the history of a file by selecting the 'Log Selected' option in the right click context menu:</p>\n<p><a href=\"https://i.stack.imgur.com/uxBTn.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uxBTn.png\" alt=\"Enter image description here\" /></a></p>\n<p>It would show the history of all the commits.</p>\n"
},
{
"answer_id": 73318457,
"author": "Eng_Farghly",
"author_id": 5661396,
"author_profile": "https://Stackoverflow.com/users/5661396",
"pm_score": 2,
"selected": false,
"text": "<p>To get all commits for a specific file use this command:</p>\n<blockquote>\n<p><code>git rev-list HEAD --oneline FileName</code></p>\n</blockquote>\n<br/>\n<p><em>For example</em></p>\n<blockquote>\n<p><code>git rev-list HEAD --oneline index.html</code></p>\n</blockquote>\n<p>Output</p>\n<pre><code>7a2bb2f update_index_with_alias\n6c03e56 update_changes\ne867142 Revert "add_paragraph"\n</code></pre>\n<p>If you want to view the changes that make on the file</p>\n<blockquote>\n<p><code>git log -p fileName</code></p>\n</blockquote>\n<p>See gif image<a href=\"https://i.stack.imgur.com/DTTgq.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DTTgq.gif\" alt=\"git commits for specific files\" /></a></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36214/"
] |
How do I view the history of an individual file with complete details of what has changed?
`git log -- [filename]` shows me the commit history of a file, but how do I see the file content that changed?
|
For a graphical view, use [`gitk`](https://git-scm.com/docs/gitk/):
```
gitk [filename]
```
To follow the file across file renames:
```
gitk --follow [filename]
```
|
278,215 |
<p>I'm working with an existing XML document which has a structure (in part) like so:</p>
<pre><code><Group>
<Entry>
<Name> Bob </Name>
<ID> 1 </ID>
</Entry>
<Entry>
<Name> Larry </Name>
</Entry>
</Group>
</code></pre>
<p>I'm using LINQ to XML to query the XDocument to retrieve all these entries as follows:</p>
<pre><code>var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string)g.element("Name").Value,
id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
};
</code></pre>
<p>The "ID" elements aren't always there and so my solution to this was the Count() jazz above. But I'm wondering if someone has a better way to do this. I'm still getting comfortable with this new stuff and I suspect that there may be a better way to do this than how I'm currently doing it.</p>
<p>Is there a better/more preferred way to do what I want?</p>
|
[
{
"answer_id": 278233,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "<p>In a similar situation I used an extension method:</p>\n\n<pre><code> public static string OptionalElement(this XElement actionElement, string elementName)\n {\n var element = actionElement.Element(elementName);\n return (element != null) ? element.Value : null;\n }\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code> id = g.OptionalElement(\"ID\") ?? \"none\"\n</code></pre>\n"
},
{
"answer_id": 278250,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>var items = from g in xDocument.Root.Descendants(\"Group\").Elements(\"Entry\")\n let idEl = g.Element(\"ID\")\n select new\n {\n name = (string)g.element(\"Name\").Value,\n id = idEl == null ? \"none\" : idEl.Value;\n };\n</code></pre>\n\n<p>if this barfs, then <code>FirstOrDefault()</code> etc might be useful, else just use an extension method (as already suggested).</p>\n"
},
{
"answer_id": 278365,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx\" rel=\"noreferrer\">XElement</a> actually has <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.op_explicit.aspx\" rel=\"noreferrer\">interesting explicit conversion operators</a> that do the right thing in this case.</p>\n\n<p>So, you rarely actually need to access the <code>.Value</code> property.</p>\n\n<p>This is all you need for your projection:</p>\n\n<pre><code>var items =\n from g in xDocument.Root.Descendants(\"Group\").Elements(\"Entry\")\n select new\n {\n name = (string) g.Element(\"Name\"),\n id = (string) g.Element(\"ID\") ?? \"none\",\n };\n</code></pre>\n\n<p>And if you'd prefer to use the value of <code>ID</code> as an integer in your anonymous type:</p>\n\n<pre><code>var items =\n from g in xDocument.Root.Descendants(\"Group\").Elements(\"Entry\")\n select new\n {\n name = (string) g.Element(\"Name\"),\n id = (int?) g.Element(\"ID\"),\n };\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
] |
I'm working with an existing XML document which has a structure (in part) like so:
```
<Group>
<Entry>
<Name> Bob </Name>
<ID> 1 </ID>
</Entry>
<Entry>
<Name> Larry </Name>
</Entry>
</Group>
```
I'm using LINQ to XML to query the XDocument to retrieve all these entries as follows:
```
var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string)g.element("Name").Value,
id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
};
```
The "ID" elements aren't always there and so my solution to this was the Count() jazz above. But I'm wondering if someone has a better way to do this. I'm still getting comfortable with this new stuff and I suspect that there may be a better way to do this than how I'm currently doing it.
Is there a better/more preferred way to do what I want?
|
[XElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) actually has [interesting explicit conversion operators](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.op_explicit.aspx) that do the right thing in this case.
So, you rarely actually need to access the `.Value` property.
This is all you need for your projection:
```
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (string) g.Element("ID") ?? "none",
};
```
And if you'd prefer to use the value of `ID` as an integer in your anonymous type:
```
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (int?) g.Element("ID"),
};
```
|
278,249 |
<p>We would like to enumerate all strings in a resource file in .NET (resx file). We want this to generate a javascript object containing all these key-value pairs. We do this now for satellite assemblies with code like this (this is VB.NET, but any example code is fine):</p>
<pre><code>Dim rm As ResourceManager
rm = New ResourceManager([resource name], [your assembly])
Dim Rs As ResourceSet
Rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)
For Each Kvp As DictionaryEntry In Rs
[Write out Kvp.Key and Kvp.Value]
Next
</code></pre>
<p>However, we haven't found a way to do this for .resx files yet, sadly. How can we enumerate all localization strings in a resx file?</p>
<p>UPDATE:</p>
<p>Following Dennis Myren's comment and the ideas from <a href="http://blechie.com/WPierce/archive/2007/08/01/Using-Resx-Files-with-a-ResourceManager.aspx" rel="nofollow noreferrer">here</a>, I built a ResXResourceManager. Now I can do the same with .resx files as I did with the embedded resources. Here is the code. Note that Microsoft made a needed constructor private, so I use reflection to access it. You need full trust when using this.</p>
<pre><code>Imports System.Globalization
Imports System.Reflection
Imports System.Resources
Imports System.Windows.Forms
Public Class ResXResourceManager
Inherits ResourceManager
Public Sub New(ByVal BaseName As String, ByVal ResourceDir As String)
Me.New(BaseName, ResourceDir, GetType(ResXResourceSet))
End Sub
Protected Sub New(ByVal BaseName As String, ByVal ResourceDir As String, ByVal UsingResourceSet As Type)
Dim BaseType As Type = Me.GetType().BaseType
Dim Flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance
Dim Constructor As ConstructorInfo = BaseType.GetConstructor(Flags, Nothing, New Type() { GetType(String), GetType(String), GetType(Type) }, Nothing)
Constructor.Invoke(Me, Flags, Nothing, New Object() { BaseName, ResourceDir, UsingResourceSet }, Nothing)
End Sub
Protected Overrides Function GetResourceFileName(ByVal culture As CultureInfo) As String
Dim FileName As String
FileName = MyBase.GetResourceFileName(culture)
If FileName IsNot Nothing AndAlso FileName.Length > 10 Then
Return FileName.Substring(0, FileName.Length - 10) & ".resx"
End If
Return Nothing
End Function
End Class
</code></pre>
|
[
{
"answer_id": 278413,
"author": "baretta",
"author_id": 30052,
"author_profile": "https://Stackoverflow.com/users/30052",
"pm_score": 3,
"selected": true,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.resources.resxresourcereader.aspx\" rel=\"nofollow noreferrer\">System.Resources.ResXResourceReader</a> (it's in System.Windows.Forms.dll)</p>\n"
},
{
"answer_id": 2270904,
"author": "Tony",
"author_id": 274090,
"author_profile": "https://Stackoverflow.com/users/274090",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://tonesdotnetblog.wordpress.com/2010/02/14/string-enumerations-and-resource-files-in-c/\" rel=\"nofollow noreferrer\">http://tonesdotnetblog.wordpress.com/2010/02/14/string-enumerations-and-resource-files-in-c/</a> has an alternative solution that involves putting attributes on enumerations that enable reading strings from resource files. This uses an alternative custom tool.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071/"
] |
We would like to enumerate all strings in a resource file in .NET (resx file). We want this to generate a javascript object containing all these key-value pairs. We do this now for satellite assemblies with code like this (this is VB.NET, but any example code is fine):
```
Dim rm As ResourceManager
rm = New ResourceManager([resource name], [your assembly])
Dim Rs As ResourceSet
Rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)
For Each Kvp As DictionaryEntry In Rs
[Write out Kvp.Key and Kvp.Value]
Next
```
However, we haven't found a way to do this for .resx files yet, sadly. How can we enumerate all localization strings in a resx file?
UPDATE:
Following Dennis Myren's comment and the ideas from [here](http://blechie.com/WPierce/archive/2007/08/01/Using-Resx-Files-with-a-ResourceManager.aspx), I built a ResXResourceManager. Now I can do the same with .resx files as I did with the embedded resources. Here is the code. Note that Microsoft made a needed constructor private, so I use reflection to access it. You need full trust when using this.
```
Imports System.Globalization
Imports System.Reflection
Imports System.Resources
Imports System.Windows.Forms
Public Class ResXResourceManager
Inherits ResourceManager
Public Sub New(ByVal BaseName As String, ByVal ResourceDir As String)
Me.New(BaseName, ResourceDir, GetType(ResXResourceSet))
End Sub
Protected Sub New(ByVal BaseName As String, ByVal ResourceDir As String, ByVal UsingResourceSet As Type)
Dim BaseType As Type = Me.GetType().BaseType
Dim Flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance
Dim Constructor As ConstructorInfo = BaseType.GetConstructor(Flags, Nothing, New Type() { GetType(String), GetType(String), GetType(Type) }, Nothing)
Constructor.Invoke(Me, Flags, Nothing, New Object() { BaseName, ResourceDir, UsingResourceSet }, Nothing)
End Sub
Protected Overrides Function GetResourceFileName(ByVal culture As CultureInfo) As String
Dim FileName As String
FileName = MyBase.GetResourceFileName(culture)
If FileName IsNot Nothing AndAlso FileName.Length > 10 Then
Return FileName.Substring(0, FileName.Length - 10) & ".resx"
End If
Return Nothing
End Function
End Class
```
|
Use [System.Resources.ResXResourceReader](http://msdn.microsoft.com/en-us/library/system.resources.resxresourcereader.aspx) (it's in System.Windows.Forms.dll)
|
278,259 |
<p>I'm trying to write an iterator for results from a PDO statement but I can't find any way of rewinding to the first row. I would like to avoid the overhead of calling fetchAll and storing all the result data.</p>
<pre><code>// first loop works fine
foreach($statement as $result) {
// do something with result
}
// but subsequent loops don't
foreach($statement as $result) {
// never called
}
</code></pre>
<p>Is there some way of reseting the statement or seeking the first row?</p>
|
[
{
"answer_id": 278317,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 1,
"selected": false,
"text": "<p>You'll probably want to take a look at some of the PHP SPL classes that can be extended to provide array-like access to objects. </p>\n\n<ul>\n<li><a href=\"http://us.php.net/spl\" rel=\"nofollow noreferrer\">Standard PHP Library (SPL)</a> I would specifically\nrecommend that you look at the\nArrayIterator, ArrayObject, and\nperhaps the Iterator interface.</li>\n<li><a\nhref=\"http://www.phpbuilder.com/manual/en/language.oop5.iterations.php\" rel=\"nofollow noreferrer\">Simple\nTutorial</a></li>\n<li><a\nhref=\"http://ramikayyali.com/archives/2005/02/25/iterators\" rel=\"nofollow noreferrer\">Another\nQuick Tutorial</a></li>\n</ul>\n"
},
{
"answer_id": 278682,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 5,
"selected": true,
"text": "<p>I'm pretty sure this is database dependent. Because of that, it is something you should try to avoid. However, I think you can achieve what you want by enabling <a href=\"http://www.php.net/pdo-mysql#pdo-mysql.constants\" rel=\"noreferrer\">buffered queries</a>. If that doesn't work, you can always pull the result into an array with <a href=\"http://www.php.net/manual/en/pdostatement.fetchall.php\" rel=\"noreferrer\"><code>fetchAll</code></a>. Both solutions have implications for your applications performance, so think twice about it, if the resultsets are large.</p>\n"
},
{
"answer_id": 278763,
"author": "Exception e",
"author_id": 27541,
"author_profile": "https://Stackoverflow.com/users/27541",
"pm_score": 3,
"selected": false,
"text": "<p>see <a href=\"http://somabo.de/talks/200311_apachecon_php5_and_databases.pdf\" rel=\"nofollow noreferrer\" title=\"presentation\">slide 31 from this presentation</a>, you can do a <code>$statement->rewind()</code> if it applies to a buffered query. If you use mysql, you can emulate buffered queries by using <code>PDO_MYSQL_ATTR_USE_BUFFERED_QUERY</code>:</p>\n\n<pre><code>$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);\n</code></pre>\n\n<p>@NoahGoodrich pointed you to spl. Here is an example that always works:</p>\n\n<pre><code>$it = new ArrayIterator($stmt->fetchAll());\n</code></pre>\n"
},
{
"answer_id": 17102074,
"author": "John K",
"author_id": 969423,
"author_profile": "https://Stackoverflow.com/users/969423",
"pm_score": 3,
"selected": false,
"text": "<p>This little class I wrote wraps a PDOStatement. It only stores the data that is fetched. If this doesn't work, you could move the cache to read and write to a file.</p>\n\n<pre><code>// Wrap a PDOStatement to iterate through all result rows. Uses a \n// local cache to allow rewinding.\nclass PDOStatementIterator implements Iterator\n{\n public\n $stmt,\n $cache,\n $next;\n\n public function __construct($stmt)\n {\n $this->cache = array();\n $this->stmt = $stmt;\n }\n\n public function rewind()\n {\n reset($this->cache);\n $this->next();\n }\n\n public function valid()\n {\n return (FALSE !== $this->next);\n }\n\n public function current()\n {\n return $this->next[1];\n }\n\n public function key()\n {\n return $this->next[0];\n }\n\n public function next()\n {\n // Try to get the next element in our data cache.\n $this->next = each($this->cache);\n\n // Past the end of the data cache\n if (FALSE === $this->next)\n {\n // Fetch the next row of data\n $row = $this->stmt->fetch(PDO::FETCH_ASSOC);\n\n // Fetch successful\n if ($row)\n {\n // Add row to data cache\n $this->cache[] = $row;\n }\n\n $this->next = each($this->cache);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 38876846,
"author": "Pedro Sanção",
"author_id": 2932525,
"author_profile": "https://Stackoverflow.com/users/2932525",
"pm_score": 2,
"selected": false,
"text": "<p>Asked a long time ago but currently there's another solution.</p>\n\n<p>The method <code>PDOStatement::fetch()</code> may receives a second parameter, the cursor orientation, with one of <code>PDO::FETCH_ORI_*</code> constants. These parameter are only valid if the <code>PDOStatement</code> are created with the atribute <code>PDO::ATTR_CURSOR</code> as <code>PDO::CURSOR_SCROLL</code>.</p>\n\n<p>This way you can navigate as follows.</p>\n\n<pre><code>$sql = \"Select * From Tabela\";\n$statement = $db->prepare($sql, array(\n PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,\n));\n$statement->execute();\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_NEXT); // return next\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_PRIOR); // return previous\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_FIRST); // return first\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_LAST); // return last\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_ABS, $n); // return to $n position\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_REL, $n); // return to $n position relative to current\n</code></pre>\n\n<p>More info in <a href=\"http://php.net/manual/en/pdostatement.fetch.php#refsect1-pdostatement.fetch-parameters\" rel=\"nofollow\">docs</a> and <a href=\"http://php.net/manual/en/pdo.constants.php\" rel=\"nofollow\">PDO predefined constants</a>.</p>\n\n<p>Note: used <code>PDO::FETCH_BOTH</code> because is the default, just customize it for your project.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
I'm trying to write an iterator for results from a PDO statement but I can't find any way of rewinding to the first row. I would like to avoid the overhead of calling fetchAll and storing all the result data.
```
// first loop works fine
foreach($statement as $result) {
// do something with result
}
// but subsequent loops don't
foreach($statement as $result) {
// never called
}
```
Is there some way of reseting the statement or seeking the first row?
|
I'm pretty sure this is database dependent. Because of that, it is something you should try to avoid. However, I think you can achieve what you want by enabling [buffered queries](http://www.php.net/pdo-mysql#pdo-mysql.constants). If that doesn't work, you can always pull the result into an array with [`fetchAll`](http://www.php.net/manual/en/pdostatement.fetchall.php). Both solutions have implications for your applications performance, so think twice about it, if the resultsets are large.
|
278,278 |
<p>I'd like to change this:</p>
<pre><code><a href='foo'>
<div> Moo </div>
</a>
</code></pre>
<p>to be standards compliant (you're not supposed to have block elements in inline elements). Wiring javascript to the divs just for navigation seems like a hack and degrades accessibility.. In this case, my requirements are for 2 sets of borders on my fixed-dimension links, so the above non-compliant code works perfectly after applying styles.</p>
<p>Also, is "<code>a { display:block; }</code>" a legal way to circumvent the validation?</p>
|
[
{
"answer_id": 278292,
"author": "Zack The Human",
"author_id": 18265,
"author_profile": "https://Stackoverflow.com/users/18265",
"pm_score": 5,
"selected": true,
"text": "<p>Why not use a <strong><span></strong> rather than a <strong><div></strong> and set <strong>display:block</strong> on both elements?</p>\n\n<p>Additionally, to answer your latter question: I don't believe adding <strong>display:block;</strong> to your anchor will make it pass validation. The validator checks to see if you're following (X)HTML rules, not how to present the page to the user.</p>\n"
},
{
"answer_id": 278305,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I normally consider the <code><a ></code> tag to be a special case for this purpose. You ought to be able to apply that to just about anything- it is after kind of the whole point of hypertext (<code><tr ></code> comes to mind a good example). But if you have to pass a validator somewhere I understand. </p>\n\n<p>Could you use a javascript <code>onclick</code> handler for the div, and eliminate the anchor entirely?</p>\n"
},
{
"answer_id": 278561,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to consider putting the <code>div</code> outside the <code>a</code> if it is only for display purposes, unless it's important that the outer border be clickable. Either this:</p>\n\n<pre><code><div class=\"dbl_border_links\"><a href=\"blah\">Blah text</a></div>\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code><a class=\"dbl_border_links\" href=\"blah\"><span>Blah text</span></a>\n</code></pre>\n\n<p>will work and you can use something like this:</p>\n\n<pre><code><style>\n .dbl_border_links, .dbl_border_links>* {\n display: block;\n border: 1px solid;\n padding: 1px;\n }\n .dbl_border_links {\n border-color: red;\n }\n .dbl_border_links > * {\n border-color: blue;\n }\n</style>\n</code></pre>\n\n<p>to specify the styles. Personally I'd go with the <code>div</code> containing the <code>a</code> but either approach works.</p>\n"
},
{
"answer_id": 279788,
"author": "Ola Tuvesson",
"author_id": 6903,
"author_profile": "https://Stackoverflow.com/users/6903",
"pm_score": 1,
"selected": false,
"text": "<p>Firstly, there is certainly nothing wrong with giving an anchor display:block; I'd say it's one of the more common things people do with CSS and is perfectly standards compliant. Secondly, there are a number of ways to achieve a double border on an HTML element. For one thing, check out the \"outline\" property: </p>\n\n<p><a href=\"http://webdesign.about.com/od/advancedcss/a/outline_style.htm\" rel=\"nofollow noreferrer\">http://webdesign.about.com/od/advancedcss/a/outline_style.htm</a> </p>\n\n<p>Admittedly, this will only work in the more modern browsers but should degrade gracefully as the outline doesn't take up any space in the page. If the contents of the link is to be an image you can simply give the <a> a little padding and a background colour as well as a normal border (in another colour) to create the impression of a double border. Or give the image a border of its own. Of course you can also do something along the lines of your original idea, though nesting your HTML the other way around, and simply assigning a different border to each element. Or you can use an inline element inside the link (like a <span> or an <em> or something) which you also set to display:block; (yes, this is also valid!). Happy coding! </p>\n"
},
{
"answer_id": 279820,
"author": "Esteban Küber",
"author_id": 34813,
"author_profile": "https://Stackoverflow.com/users/34813",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand correctly your intentions, you should place, as already mentioned, the div outside the anchor, and, to get the same presentation, make the anchor <code>width:100%;height:100%</code>. Cross Browser milage may vary.\nAlso, you could dump the div altogether and give the anchor <code>display:block;</code></p>\n\n<p>What are you exactly trying to do?</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4435/"
] |
I'd like to change this:
```
<a href='foo'>
<div> Moo </div>
</a>
```
to be standards compliant (you're not supposed to have block elements in inline elements). Wiring javascript to the divs just for navigation seems like a hack and degrades accessibility.. In this case, my requirements are for 2 sets of borders on my fixed-dimension links, so the above non-compliant code works perfectly after applying styles.
Also, is "`a { display:block; }`" a legal way to circumvent the validation?
|
Why not use a **<span>** rather than a **<div>** and set **display:block** on both elements?
Additionally, to answer your latter question: I don't believe adding **display:block;** to your anchor will make it pass validation. The validator checks to see if you're following (X)HTML rules, not how to present the page to the user.
|
278,286 |
<p><strike>All of the errors are on auto-generated files, not within the files that were created by me. Here are a few of them:</p>
<pre><code>'Context' is not a member of 'auth_cookies'
'ProcessRequest' cannot be declared 'Overrides' because it does not override a sub in a base class
'Server' is not a member of 'ASP.auth_cookies_aspx'
Class 'auth_cookies_aspx' must implement 'Sub ProcessRequest(context As HttpContext)' for interface 'System.Web.IHttpHandler'
</code></pre>
<p>Any help would be appreciated.</strike></p>
<p>EDIT: found out that the file it was looking for wasn't there, fixed that problem and that eliminated all the errors except one:</p>
<pre><code> Error-5: There can be only one 'page' directive.
>> C:\Users\darren\Documents\Visual Studio 2008\WebSites\gs_ontheweb\auth\cookies.aspx
</code></pre>
<p>This is the contents of the <strong><code>cookies.aspx</code></strong> page:</p>
<pre><code><%@ Page Language="VB" MasterPageFile="~/theMaster.master" AutoEventWireup="false" CodeFile="cookies.aspx.vb" Inherits="auth_cookies" title="NOM COOKIES" %>
</code></pre>
<p>UPDATE: Turns out one of linked files had a link to another .aspx page, causing 2 page directives to be loaded.</p>
|
[
{
"answer_id": 278319,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": true,
"text": "<p>Did you put a <code><%@Page%></code> directive in your Master page? It should only have a <code><%@Master%></code> directive.</p>\n"
},
{
"answer_id": 278330,
"author": "Anders",
"author_id": 25515,
"author_profile": "https://Stackoverflow.com/users/25515",
"pm_score": 0,
"selected": false,
"text": "<p>No, the header of my MasterPage is:</p>\n\n<pre><code><%@ Master Language=\"VB\" CodeFile=\"theMaster.master.vb\" Inherits=\"theMaster\" %>\n</code></pre>\n\n<p>There is no <code><%@Page%></code> directive on the MasterPage.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
All of the errors are on auto-generated files, not within the files that were created by me. Here are a few of them:
```
'Context' is not a member of 'auth_cookies'
'ProcessRequest' cannot be declared 'Overrides' because it does not override a sub in a base class
'Server' is not a member of 'ASP.auth_cookies_aspx'
Class 'auth_cookies_aspx' must implement 'Sub ProcessRequest(context As HttpContext)' for interface 'System.Web.IHttpHandler'
```
Any help would be appreciated.
EDIT: found out that the file it was looking for wasn't there, fixed that problem and that eliminated all the errors except one:
```
Error-5: There can be only one 'page' directive.
>> C:\Users\darren\Documents\Visual Studio 2008\WebSites\gs_ontheweb\auth\cookies.aspx
```
This is the contents of the **`cookies.aspx`** page:
```
<%@ Page Language="VB" MasterPageFile="~/theMaster.master" AutoEventWireup="false" CodeFile="cookies.aspx.vb" Inherits="auth_cookies" title="NOM COOKIES" %>
```
UPDATE: Turns out one of linked files had a link to another .aspx page, causing 2 page directives to be loaded.
|
Did you put a `<%@Page%>` directive in your Master page? It should only have a `<%@Master%>` directive.
|
278,290 |
<p>Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?</p>
|
[
{
"answer_id": 278315,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 4,
"selected": true,
"text": "<p>Here's how to add a value at the top of the list. It can be an empty string, or some text.</p>\n\n<pre><code><asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n</code></pre>\n\n<p>Be sure to set the DropDownList's AppendDataBoundItems=True. </p>\n"
},
{
"answer_id": 278326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'd provide an extension method on <code>IEnumerable<string></code> that prepended an item to the beginning of the list:</p>\n\n<pre><code> public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item)\n {\n return new string[] { item == null ? string.Empty : item }.Union(data);\n }\n</code></pre>\n\n<p>Its sort of linq-y, as it uses the linq extension method Union. Its a little cleaner than doing this:</p>\n\n<pre><code>var result = new string[]{string.Empty}.Union(from x in data select x.ToString());\n</code></pre>\n"
},
{
"answer_id": 3477928,
"author": "Cheryl G",
"author_id": 419659,
"author_profile": "https://Stackoverflow.com/users/419659",
"pm_score": 1,
"selected": false,
"text": "<p>Markup: </p>\n\n<pre><code><asp:DropDownList ID=\"ddlQualQuestion\" runat=\"server\" DataSourceID=\"sdsQualQuestion\" DataTextField=\"ShortQuestionText\" DataValueField=\"QualificationQuestionKey\" AutoPostBack=\"true\" OnSelectedIndexChanged=\"ddlQualQuestion_SelectedIndexChanged\" OnDataBound=\"ddlQualQuestion_DataBound\" />;\n</code></pre>\n\n<p>Code behind:</p>\n\n<pre><code>protected void ddlQualQuestion_DataBound(object sender, EventArgs e) \n{ \n ddlQualQuestion.Items.Insert(0, new ListItem(\"\", \"0\")); \n} \n</code></pre>\n"
},
{
"answer_id": 14456109,
"author": "jme-mac",
"author_id": 1996522,
"author_profile": "https://Stackoverflow.com/users/1996522",
"pm_score": 1,
"selected": false,
"text": "<p>Taking the solution DOK provided:</p>\n\n<pre><code><asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n</code></pre>\n\n<p>Addtionally, if you don't want to force the user to make a selection you can add a method to the LinqDataSource of your GridView:</p>\n\n<pre><code>OnSelecting=\"myGridview_Selecting\"\n</code></pre>\n\n<p>Add code behind like this:</p>\n\n<pre><code>protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n if (categories.SelectedValue == \"-1\")\n {\n e.WhereParameters.Remove(\"CategoryID\");\n }\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12111/"
] |
Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?
|
Here's how to add a value at the top of the list. It can be an empty string, or some text.
```
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
```
Be sure to set the DropDownList's AppendDataBoundItems=True.
|
278,294 |
<p>The new Vista Audio subsystem is set up to be a chain of devices starting with the inputs, going through all the various controls (like mixers and volumen controls) and then ending up at various endpoints (like speakers or headphones).</p>
<p>My question is: Is there a tool out there that will show all the endpoints devices in the system, and what devices are chained together? Ideally, it would diagram the topology, showing what inputs where connected to what outputs, and you would be able to see all the properties for each part of the audio system.</p>
|
[
{
"answer_id": 278315,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 4,
"selected": true,
"text": "<p>Here's how to add a value at the top of the list. It can be an empty string, or some text.</p>\n\n<pre><code><asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n</code></pre>\n\n<p>Be sure to set the DropDownList's AppendDataBoundItems=True. </p>\n"
},
{
"answer_id": 278326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'd provide an extension method on <code>IEnumerable<string></code> that prepended an item to the beginning of the list:</p>\n\n<pre><code> public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item)\n {\n return new string[] { item == null ? string.Empty : item }.Union(data);\n }\n</code></pre>\n\n<p>Its sort of linq-y, as it uses the linq extension method Union. Its a little cleaner than doing this:</p>\n\n<pre><code>var result = new string[]{string.Empty}.Union(from x in data select x.ToString());\n</code></pre>\n"
},
{
"answer_id": 3477928,
"author": "Cheryl G",
"author_id": 419659,
"author_profile": "https://Stackoverflow.com/users/419659",
"pm_score": 1,
"selected": false,
"text": "<p>Markup: </p>\n\n<pre><code><asp:DropDownList ID=\"ddlQualQuestion\" runat=\"server\" DataSourceID=\"sdsQualQuestion\" DataTextField=\"ShortQuestionText\" DataValueField=\"QualificationQuestionKey\" AutoPostBack=\"true\" OnSelectedIndexChanged=\"ddlQualQuestion_SelectedIndexChanged\" OnDataBound=\"ddlQualQuestion_DataBound\" />;\n</code></pre>\n\n<p>Code behind:</p>\n\n<pre><code>protected void ddlQualQuestion_DataBound(object sender, EventArgs e) \n{ \n ddlQualQuestion.Items.Insert(0, new ListItem(\"\", \"0\")); \n} \n</code></pre>\n"
},
{
"answer_id": 14456109,
"author": "jme-mac",
"author_id": 1996522,
"author_profile": "https://Stackoverflow.com/users/1996522",
"pm_score": 1,
"selected": false,
"text": "<p>Taking the solution DOK provided:</p>\n\n<pre><code><asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n</code></pre>\n\n<p>Addtionally, if you don't want to force the user to make a selection you can add a method to the LinqDataSource of your GridView:</p>\n\n<pre><code>OnSelecting=\"myGridview_Selecting\"\n</code></pre>\n\n<p>Add code behind like this:</p>\n\n<pre><code>protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n if (categories.SelectedValue == \"-1\")\n {\n e.WhereParameters.Remove(\"CategoryID\");\n }\n}\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17958/"
] |
The new Vista Audio subsystem is set up to be a chain of devices starting with the inputs, going through all the various controls (like mixers and volumen controls) and then ending up at various endpoints (like speakers or headphones).
My question is: Is there a tool out there that will show all the endpoints devices in the system, and what devices are chained together? Ideally, it would diagram the topology, showing what inputs where connected to what outputs, and you would be able to see all the properties for each part of the audio system.
|
Here's how to add a value at the top of the list. It can be an empty string, or some text.
```
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
```
Be sure to set the DropDownList's AppendDataBoundItems=True.
|
278,296 |
<p>I've got a PHP script which I'm running from a command line (windows) that performs a variety of tasks, and the only output it gives is via 'print' statements which output direct to screen.</p>
<p>What I want to do is capture this to a log file as well.</p>
<p>I know I can do: </p>
<pre><code>php-cli script.php > log.txt
</code></pre>
<p>But the problem with this approach is that all the output is written to the log file, but I can't see how things are running in the mean time (so I can stop the process if anything dodgy is happening).</p>
<p>Just to pre-empt other possible questions, I can't change all the print's to a log statement as there are far too many of them and I'd rather not change anything in the code lest I be blamed for something going fubar. Plus there's the lack of time aspect as well. I also have to run this on a windows machine.</p>
<p>Thanks in advance :)</p>
<p>Edit: Thanks for the answers guys, in the end I went with the browser method because that was the easiest and quickest to set up, although I am convinced there is an actual answer to this problem somewhere.</p>
|
[
{
"answer_id": 278327,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 2,
"selected": false,
"text": "<p>You can create a powershell script that runs the command, reads the data from the command's STDOUT then outputs the output to both the log file and the terminal for you to watch. You can use the commands Write-Output and Write-Host. </p>\n\n<p>Microsoft's site: <a href=\"http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/tee-object.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/tee-object.mspx</a></p>\n\n<p>Another option would be use find a tee program that will read input and divert it to two different outputs. I believe I have seen these for windows but I don't think they are standard.</p>\n\n<p>Wikipedia: <a href=\"http://en.wikipedia.org/wiki/Tee_(command)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Tee_(command)</a></p>\n"
},
{
"answer_id": 278401,
"author": "Jack Ryan",
"author_id": 28882,
"author_profile": "https://Stackoverflow.com/users/28882",
"pm_score": 2,
"selected": true,
"text": "<p>I have always opened the log file up in my web browser. This allows me to refresh it easily and does not interrupt any writing to the file that windows does. It isn't particularly elegant but it does work!</p>\n"
},
{
"answer_id": 278403,
"author": "Charles Beattie",
"author_id": 97554,
"author_profile": "https://Stackoverflow.com/users/97554",
"pm_score": 0,
"selected": false,
"text": "<p>Slow:</p>\n\n<pre><code>for /f \"delims=\" %a in ('php-cli script.php') do @echo %a&echo %a>>log.txt\n</code></pre>\n\n<p>or in a batch file:</p>\n\n<pre><code>for /f \"delims=\" %%a in ('php-cli script.php') do @echo %%a&echo %%a>>log.txt\n</code></pre>\n"
},
{
"answer_id": 342997,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 1,
"selected": false,
"text": "<p>You want the \"tee\" command for Windows. See <a href=\"http://en.wikipedia.org/wiki/Tee_(command)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Tee_(command)</a> </p>\n\n<p>Powershell includes a tee command, and there are also numerous versions of tee for Windows available, for instance: </p>\n\n<ul>\n<li><a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\">http://unxutils.sourceforge.net/</a></li>\n<li><a href=\"http://www.chipstips.com/?p=129\" rel=\"nofollow noreferrer\">http://www.chipstips.com/?p=129</a></li>\n</ul>\n\n<p>Also can be <a href=\"http://www.fpschultze.de/uploads/tee.vbs.txt\" rel=\"nofollow noreferrer\">implemented in VBScript</a> if you prefer.</p>\n\n<p><strong>EDIT</strong>: Just occurred to me I should also mention the tail command: <a href=\"http://en.wikipedia.org/wiki/Tail_(Unix)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Tail_(Unix)</a>. Tail allows you to read the last <em>N</em> lines of a file, and also includes a \"file monitor\" mode that just continually displays the end of the file in real-time. This is perfect for log file monitoring since it allows you to watch the log in real-time without interfering with the process that's writing to the log. There are several implementations of tail for Windows, both command line and GUI based. Microsoft's Services For UNIX packages (or whatever they're calling it now) also include a version of tail. Some examples: </p>\n\n<ul>\n<li><a href=\"http://ophilipp.free.fr/op_tail.htm\" rel=\"nofollow noreferrer\">mTail</a></li>\n<li><a href=\"http://tailforwin32.sourceforge.net/\" rel=\"nofollow noreferrer\">Tail for Win32</a></li>\n<li><a href=\"http://www.baremetalsoft.com/wintail/\" rel=\"nofollow noreferrer\">WinTail</a></li>\n<li><a href=\"http://www.makelogic.com/tail/TailHome.htm\" rel=\"nofollow noreferrer\">MakeLogic Tail</a></li>\n</ul>\n\n<p>Some of these go far beyond just displaying the file in real-time as it updates and can send email alerts and colorize string matches, monitor multiple files at once, etc.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11905/"
] |
I've got a PHP script which I'm running from a command line (windows) that performs a variety of tasks, and the only output it gives is via 'print' statements which output direct to screen.
What I want to do is capture this to a log file as well.
I know I can do:
```
php-cli script.php > log.txt
```
But the problem with this approach is that all the output is written to the log file, but I can't see how things are running in the mean time (so I can stop the process if anything dodgy is happening).
Just to pre-empt other possible questions, I can't change all the print's to a log statement as there are far too many of them and I'd rather not change anything in the code lest I be blamed for something going fubar. Plus there's the lack of time aspect as well. I also have to run this on a windows machine.
Thanks in advance :)
Edit: Thanks for the answers guys, in the end I went with the browser method because that was the easiest and quickest to set up, although I am convinced there is an actual answer to this problem somewhere.
|
I have always opened the log file up in my web browser. This allows me to refresh it easily and does not interrupt any writing to the file that windows does. It isn't particularly elegant but it does work!
|
278,304 |
<p>What is the best way to stop a user from resizing the top-level window of an application written in WPF?</p>
|
[
{
"answer_id": 278332,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 8,
"selected": true,
"text": "<p>You will want to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.resizemode.aspx\" rel=\"noreferrer\"><code>ResizeMode.NoResize</code></a> on the window.</p>\n\n<pre><code><Window x:Class=\"WpfApplication5.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n ResizeMode=\"NoResize\">\n</Window>\n</code></pre>\n"
},
{
"answer_id": 1142605,
"author": "Rob Sobers",
"author_id": 132931,
"author_profile": "https://Stackoverflow.com/users/132931",
"pm_score": 3,
"selected": false,
"text": "<p>A WPF quirk to note is that if <code>ResizeMode=\"NoResize\"</code> and <code>WindowStyle=\"None\"</code> you will lose the chrome around the <em>entirely</em> in Vista Aero.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
] |
What is the best way to stop a user from resizing the top-level window of an application written in WPF?
|
You will want to use the [`ResizeMode.NoResize`](http://msdn.microsoft.com/en-us/library/system.windows.resizemode.aspx) on the window.
```
<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ResizeMode="NoResize">
</Window>
```
|
278,312 |
<p>I am migrating web apps to new hosting servers, but when I try to access them to test on the new server, I get all these assemblies not found errors like:</p>
<pre><code>Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 28: <compilation debug="false">
Line 29: <assemblies>
Line 30: <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Line 31: <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
Line 32: <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</code></pre>
<p>Does anyone know where you find these to install or how to migrate them over?</p>
|
[
{
"answer_id": 278316,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "<p>That's part of the ASP.Net AJAX kit.</p>\n"
},
{
"answer_id": 278384,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 0,
"selected": false,
"text": "<p>You will have to either install the ASP.AJAX kit on the server, or include the assemblies in your project. <a href=\"https://stackoverflow.com/questions/273418/any-way-to-use-aspnet-ajax-when-my-server-does-not-and-can-not-have-the-aspnet\">This question</a> and <a href=\"https://stackoverflow.com/questions/221761/how-do-i-force-aspnet-ajax-to-use-a-script-from-the-fs-and-not-webresourceaxd-o\">this question</a> say you how you can include the libraries as DLL or JS.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18309/"
] |
I am migrating web apps to new hosting servers, but when I try to access them to test on the new server, I get all these assemblies not found errors like:
```
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 28: <compilation debug="false">
Line 29: <assemblies>
Line 30: <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Line 31: <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
Line 32: <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
```
Does anyone know where you find these to install or how to migrate them over?
|
That's part of the ASP.Net AJAX kit.
|
278,320 |
<p>I am using SQL Server 2005 CE framework 3.5 and attempting to use merge replication between my hand held and my SQL Server. When I run the code to synchronise it just seems to sit forever, and when I put a breakpoint in my code it never gets past the call to Synchronize().</p>
<p>If I look at the replication monitor in sql server, it gets to the point where it says the subscription is no longer synchronising and doesn't show any errors. Therefore I am assuming this to mean the synchronisation is complete.</p>
<p><a href="http://server/virtualdirectory/sqlcesa35.dll?diag" rel="nofollow noreferrer">http://server/virtualdirectory/sqlcesa35.dll?diag</a> does not report any issues.</p>
<p>This is my first attempt at any handheld development, so I may have done something daft. However, SQL Server seems to be reporting a successful synchronisation.</p>
<p>Any help would be greatly appreciated as I have spent ages on this ! </p>
<p>Here is my code.</p>
<pre><code>const string DatabasePath = @"SD Card\mydb.sdf";
var repl = new SqlCeReplication
{
ConnectionManager = true,
InternetUrl = @"http://server/virtualdirectory/sqlcesa35.dll",
Publisher = @"servername",
PublisherDatabase = @"databasename",
PublisherSecurityMode = SecurityType.DBAuthentication,
PublisherLogin = @"username",
PublisherPassword = @"password",
Publication = @"publicationname",
Subscriber = @"PPC",
SubscriberConnectionString = "Data Source=" + DatabasePath
};
try
{
Cursor.Current = Cursors.WaitCursor;
if (!File.Exists(DatabasePath))
{
repl.AddSubscription(AddOption.CreateDatabase);
}
repl.Synchronize();
MessageBox.Show("Successfully synchronised");
}
catch (SqlCeException e)
{
DisplaySqlCeErrors(e.Errors, e);
}
finally
{
repl.Dispose();
Cursor.Current = Cursors.Default;
}
</code></pre>
|
[
{
"answer_id": 278510,
"author": "Cheryl",
"author_id": 30270,
"author_profile": "https://Stackoverflow.com/users/30270",
"pm_score": 0,
"selected": false,
"text": "<p>I have since discovered that it was just taking a long time to copy the data to the physical disk. Although the sql server replication had completed, it was still copying the data to the sd card.</p>\n\n<p>I identified this by reducing the amount of tables I am replicating and I got a more immediate response (well another error but unrelated to this issue).</p>\n\n<p>Thanks anyway :)</p>\n"
},
{
"answer_id": 280102,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "<p>Another thing you can do to speed up the Synchronize operation is to specify a db file path that is in your PDA's main program memory (instead of on the SD Card as in your example). You should see a speed improvement of up to 4X (meaning the Sync may take only 25% as long as it's taking now).</p>\n\n<p>If you're running out of main program memory on your PDA, you can use System.IO.File.Move() to move the file to the SD Card after the Synchronize call. This seems a bit strange, I know, but it's much faster to sync to program memory and copy to the SD card then it is to sync directly to the SD card.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30270/"
] |
I am using SQL Server 2005 CE framework 3.5 and attempting to use merge replication between my hand held and my SQL Server. When I run the code to synchronise it just seems to sit forever, and when I put a breakpoint in my code it never gets past the call to Synchronize().
If I look at the replication monitor in sql server, it gets to the point where it says the subscription is no longer synchronising and doesn't show any errors. Therefore I am assuming this to mean the synchronisation is complete.
<http://server/virtualdirectory/sqlcesa35.dll?diag> does not report any issues.
This is my first attempt at any handheld development, so I may have done something daft. However, SQL Server seems to be reporting a successful synchronisation.
Any help would be greatly appreciated as I have spent ages on this !
Here is my code.
```
const string DatabasePath = @"SD Card\mydb.sdf";
var repl = new SqlCeReplication
{
ConnectionManager = true,
InternetUrl = @"http://server/virtualdirectory/sqlcesa35.dll",
Publisher = @"servername",
PublisherDatabase = @"databasename",
PublisherSecurityMode = SecurityType.DBAuthentication,
PublisherLogin = @"username",
PublisherPassword = @"password",
Publication = @"publicationname",
Subscriber = @"PPC",
SubscriberConnectionString = "Data Source=" + DatabasePath
};
try
{
Cursor.Current = Cursors.WaitCursor;
if (!File.Exists(DatabasePath))
{
repl.AddSubscription(AddOption.CreateDatabase);
}
repl.Synchronize();
MessageBox.Show("Successfully synchronised");
}
catch (SqlCeException e)
{
DisplaySqlCeErrors(e.Errors, e);
}
finally
{
repl.Dispose();
Cursor.Current = Cursors.Default;
}
```
|
Another thing you can do to speed up the Synchronize operation is to specify a db file path that is in your PDA's main program memory (instead of on the SD Card as in your example). You should see a speed improvement of up to 4X (meaning the Sync may take only 25% as long as it's taking now).
If you're running out of main program memory on your PDA, you can use System.IO.File.Move() to move the file to the SD Card after the Synchronize call. This seems a bit strange, I know, but it's much faster to sync to program memory and copy to the SD card then it is to sync directly to the SD card.
|
278,331 |
<p>I'm finally getting the hang of RSpec after spending a couple of hours over the weekend. Now I'm stuck trying to figure out how to assert that parameters are indeed passed into the controller. I'm following the <a href="http://blog.8thlight.com/articles/2008/04/20/bowled-over-by-rubycocoa" rel="nofollow noreferrer">Bowled over by Ruby/Cocoa example</a> and adapting it for the iPhone SDK. I've done a more detailed <a href="http://codeforfun.wordpress.com/2008/11/10/rspec-for-iphone-development/" rel="nofollow noreferrer">writeup of my progress on my blog</a> so I'll defer there for the entire story. In short I've followed the tutorial all the way up to where you need to pass the pin value from the text field into the Bowling object. RSpec keeps complaining that, <em>"Spec::Mocks::MockExpectationError in ‘OSX::BowlingController should send the pin value to the bowling object’
Mock ‘Bowling’ expected :roll with (10) but received it with (no args)
./test/bowling_controller_spec.rb:38:”</em> Even as I'm certain that I'm passing a value in. Here's my code. Can someone tell me where I'm going wrong?</p>
<p><strong>bowling_controller_spec.rb</strong></p>
<pre><code>require File.dirname(__FILE__) + '/test_helper'
require "BowlingController.bundle"
OSX::ns_import :BowlingController
include OSX
describe BowlingController do
before(:each) do
@controller = BowlingController.new
@bowling = mock('Bowling')
@text_field = mock('Pins')
@text_field.stub!(:intValue).and_return(10)
@controller.pins = @text_field
end
it "should roll a ball" do
@controller.roll
end
it "should roll a ball and get the value from the pins outlet" do
@text_field.should_receive(:intValue).and_return(0)
@controller.roll
end
it "should be an OSX::NSObject" do
@controller.is_a?(OSX::NSObject).should == true
end
it "should have an outlet to a bowling object" do
@controller.bowling = @bowling
end
it "should send the pin value to the bowling object" do
@controller.bowling = @bowling
@bowling.should_receive(:roll).with(10)
@controller.roll
end
end
</code></pre>
<p><strong>BowlingController.h</strong></p>
<pre><code>#import <Foundation/Foundation.h>
@class UITextField;
@class Bowling;
@interface BowlingController : NSObject {
UITextField* pins;
Bowling* bowling;
}
@property (nonatomic, retain) UITextField* pins;
@property (nonatomic, retain) Bowling* bowling;
-(void) roll;
@end
</code></pre>
<p><strong>BowlingController.m</strong></p>
<pre><code>#import "BowlingController.h"
#import "Bowling.h"
@implementation BowlingController
@synthesize pins;
@synthesize bowling;
-(void) roll{
[self.bowling roll:[self.pins intValue]];
}
@end
// This initialization function gets called when we import the Ruby module.
// It doesn't need to do anything because the RubyCocoa bridge will do
// all the initialization work.
// The rbiphonetest test framework automatically generates bundles for
// each objective-c class containing the following line. These
// can be used by your tests.
void Init_BowlingController() { }
</code></pre>
<p><strong>Bowling.h</strong></p>
<pre><code>#import <Foundation/Foundation.h>
@interface Bowling : NSObject {
}
- (void) roll:(int) pins;
@end
</code></pre>
<p><strong>Bowling.m</strong></p>
<pre><code>#import "Bowling.h"
@implementation Bowling
- (void) roll:(int) pins{
}
@end
// This initialization function gets called when we import the Ruby module.
// It doesn't need to do anything because the RubyCocoa bridge will do
// all the initialization work.
// The rbiphonetest test framework automatically generates bundles for
// each objective-c class containing the following line. These
// can be used by your tests.
void Init_Bowling() { }
</code></pre>
|
[
{
"answer_id": 279817,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 2,
"selected": false,
"text": "<p>RubyCocoa is not supported at all on the iPhone. There is no bridge support library, and I do not believe there is any ruby interpreter on the phone.</p>\n\n<p>You might be able to get it working in the simulator, it will not stop you from using OS X only libraries if you really try, but that still will not make it work on the iPhone.</p>\n\n<p>If you really want to use RubyCocoa on the iPhone you will need to build ruby as a static library and port the bridge to the phone, which is doable, but would probably be very difficult.</p>\n"
},
{
"answer_id": 283140,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Howdy! Though I'm not familiar with how Ruby/Cocoa wraps foreign method calls- or with Objective C for that matter- the first place that would seem likely to disconnect under test is passing in a Ruby mock to the natively implemented controller. In the bowling tutorial, the ruby controller proxy is exposes its interface to the Cocoa bridge while in this implementation the proxy wraps an exposed Cocoa interface. There might be an issue, then, when substituting a ruby mock for a native field versus a ruby mock for a ruby field.</p>\n\n<p>The roll() test for the pins succeeds, though, so it's possible that messages are being passed correctly but arguments are mangled or dropped.</p>\n\n<p>This probably isn't much help, but it's an interesting problem. Good luck with the project!</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10631/"
] |
I'm finally getting the hang of RSpec after spending a couple of hours over the weekend. Now I'm stuck trying to figure out how to assert that parameters are indeed passed into the controller. I'm following the [Bowled over by Ruby/Cocoa example](http://blog.8thlight.com/articles/2008/04/20/bowled-over-by-rubycocoa) and adapting it for the iPhone SDK. I've done a more detailed [writeup of my progress on my blog](http://codeforfun.wordpress.com/2008/11/10/rspec-for-iphone-development/) so I'll defer there for the entire story. In short I've followed the tutorial all the way up to where you need to pass the pin value from the text field into the Bowling object. RSpec keeps complaining that, *"Spec::Mocks::MockExpectationError in ‘OSX::BowlingController should send the pin value to the bowling object’
Mock ‘Bowling’ expected :roll with (10) but received it with (no args)
./test/bowling\_controller\_spec.rb:38:”* Even as I'm certain that I'm passing a value in. Here's my code. Can someone tell me where I'm going wrong?
**bowling\_controller\_spec.rb**
```
require File.dirname(__FILE__) + '/test_helper'
require "BowlingController.bundle"
OSX::ns_import :BowlingController
include OSX
describe BowlingController do
before(:each) do
@controller = BowlingController.new
@bowling = mock('Bowling')
@text_field = mock('Pins')
@text_field.stub!(:intValue).and_return(10)
@controller.pins = @text_field
end
it "should roll a ball" do
@controller.roll
end
it "should roll a ball and get the value from the pins outlet" do
@text_field.should_receive(:intValue).and_return(0)
@controller.roll
end
it "should be an OSX::NSObject" do
@controller.is_a?(OSX::NSObject).should == true
end
it "should have an outlet to a bowling object" do
@controller.bowling = @bowling
end
it "should send the pin value to the bowling object" do
@controller.bowling = @bowling
@bowling.should_receive(:roll).with(10)
@controller.roll
end
end
```
**BowlingController.h**
```
#import <Foundation/Foundation.h>
@class UITextField;
@class Bowling;
@interface BowlingController : NSObject {
UITextField* pins;
Bowling* bowling;
}
@property (nonatomic, retain) UITextField* pins;
@property (nonatomic, retain) Bowling* bowling;
-(void) roll;
@end
```
**BowlingController.m**
```
#import "BowlingController.h"
#import "Bowling.h"
@implementation BowlingController
@synthesize pins;
@synthesize bowling;
-(void) roll{
[self.bowling roll:[self.pins intValue]];
}
@end
// This initialization function gets called when we import the Ruby module.
// It doesn't need to do anything because the RubyCocoa bridge will do
// all the initialization work.
// The rbiphonetest test framework automatically generates bundles for
// each objective-c class containing the following line. These
// can be used by your tests.
void Init_BowlingController() { }
```
**Bowling.h**
```
#import <Foundation/Foundation.h>
@interface Bowling : NSObject {
}
- (void) roll:(int) pins;
@end
```
**Bowling.m**
```
#import "Bowling.h"
@implementation Bowling
- (void) roll:(int) pins{
}
@end
// This initialization function gets called when we import the Ruby module.
// It doesn't need to do anything because the RubyCocoa bridge will do
// all the initialization work.
// The rbiphonetest test framework automatically generates bundles for
// each objective-c class containing the following line. These
// can be used by your tests.
void Init_Bowling() { }
```
|
RubyCocoa is not supported at all on the iPhone. There is no bridge support library, and I do not believe there is any ruby interpreter on the phone.
You might be able to get it working in the simulator, it will not stop you from using OS X only libraries if you really try, but that still will not make it work on the iPhone.
If you really want to use RubyCocoa on the iPhone you will need to build ruby as a static library and port the bridge to the phone, which is doable, but would probably be very difficult.
|
278,351 |
<p>I'm painfully new to PHP, and was trying to set up phpBB on my local site. I have a stock debian install of apache2 and php5. The phpBB installer ran fine, connected to the database and created all its tables with no problem. But when I tried to open the login page, I got a 0-byte response.</p>
<p>A little digging showed that it was never making it past the call to mysql_pconnect(). The php binary just quits without error or message. Nothing at all. I tried running the following code:</p>
<pre><code><?php
$id = @mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
</code></pre>
<p>and the "id=" string never prints. It just does nothing. I don't know where to look to see what error happened, or what is going on at all. All i've installed is "mysql" using pear... perhaps I'm missing something else?</p>
<p>This has got to be a path problem somewhere. The mysql extension is built nicely at</p>
<pre><code>/usr/lib/php5/20060613+lfs/mysql.so
</code></pre>
<p><strong>Answer:</strong></p>
<p>jishi: informed me that the "@" operator suppresses output, including error messages (@echo off, anyone?)</p>
<p>tomhaigh: extensions must be explicitly enabled in php.ini file. After adding the line "extension=mysql.so" to php.ini, the following code runs fine:</p>
<pre><code>% cat d.php
<?php
ini_set('display_errors', true);
error_reporting(E_ALL | E_NOTICE);
$id = mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
% php -c /etc/php5/apache2/php.ini d.php
id=Resource id #4
</code></pre>
<p>JOY!</p>
|
[
{
"answer_id": 278394,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I sometimes have PHP going down a 'black hole' when it finds a function that it can't find.</p>\n\n<p>Can you verify that the mysql extension is installed correctly?</p>\n\n<p>You can do this by creating a php page like this:</p>\n\n<pre><code><?php\nphpinfo();\n?>\n</code></pre>\n\n<p>Saving it in your webroot, and then accessing it. It should contain all the information about what your server is currently running in terms of PHP modules.</p>\n"
},
{
"answer_id": 278428,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 3,
"selected": false,
"text": "<p>Just noted that you're using a @ in front of mysql_pconnect(). That suppresses all errors, which in this case is a pretty bad idea. Remove that and you would probably see the output. </p>\n\n<p>Otherwise:</p>\n\n<p>Check your php.ini, should be in /etc/php5/apache2/php.ini for debian.</p>\n\n<p>Check for a line called display_errors, set that to true if you want error-output in your browser (not recommended for a production-system, but is useful during debugging and development).</p>\n\n<p>Specify log_errors on for apache to log your errors to apaches error logfile, which by default in debian would be (unless other error-file is specified for the phpBB-site):</p>\n\n<p>/var/log/apache2/error.log</p>\n"
},
{
"answer_id": 278436,
"author": "MrChrister",
"author_id": 24229,
"author_profile": "https://Stackoverflow.com/users/24229",
"pm_score": 1,
"selected": false,
"text": "<p>Remove the \"@\" That is muting the error messages that mysql_pconnect is throwing.</p>\n\n<p><a href=\"http://us.php.net/@\" rel=\"nofollow noreferrer\">Documentation</a></p>\n"
},
{
"answer_id": 278467,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 0,
"selected": false,
"text": "<p>I think you have no mysql extensions installed for your PHP. Since PHP5 I think it is a PECL extension. \nIf you are working on windows, there should be a pecl.bat or something like this in your php directory. Just go there via console and enter</p>\n\n<pre><code>pecl download mysql\n</code></pre>\n\n<p>Then everything should work as expected. </p>\n"
},
{
"answer_id": 278560,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": true,
"text": "<p>try doing this:</p>\n\n<pre><code><?php\nini_set('display_errors', true);\nerror_reporting(E_ALL | E_NOTICE);\n$id = mysql_pconnect('localhost','myusername', 'mypassword', true);\nprint \"id=\".$id.\"\\n\";\n?>\n</code></pre>\n\n<p>and see what the response is</p>\n\n<p><strong>edit</strong></p>\n\n<p>From your comment it looks like the mysql module is not installed or enabled. You could have a look in your php.ini file and see if there is a line like</p>\n\n<pre><code>extension=mysql.so\n</code></pre>\n\n<p>If it is commented with a semi-colon, try removing it and restarting apache</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36228/"
] |
I'm painfully new to PHP, and was trying to set up phpBB on my local site. I have a stock debian install of apache2 and php5. The phpBB installer ran fine, connected to the database and created all its tables with no problem. But when I tried to open the login page, I got a 0-byte response.
A little digging showed that it was never making it past the call to mysql\_pconnect(). The php binary just quits without error or message. Nothing at all. I tried running the following code:
```
<?php
$id = @mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
```
and the "id=" string never prints. It just does nothing. I don't know where to look to see what error happened, or what is going on at all. All i've installed is "mysql" using pear... perhaps I'm missing something else?
This has got to be a path problem somewhere. The mysql extension is built nicely at
```
/usr/lib/php5/20060613+lfs/mysql.so
```
**Answer:**
jishi: informed me that the "@" operator suppresses output, including error messages (@echo off, anyone?)
tomhaigh: extensions must be explicitly enabled in php.ini file. After adding the line "extension=mysql.so" to php.ini, the following code runs fine:
```
% cat d.php
<?php
ini_set('display_errors', true);
error_reporting(E_ALL | E_NOTICE);
$id = mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
% php -c /etc/php5/apache2/php.ini d.php
id=Resource id #4
```
JOY!
|
try doing this:
```
<?php
ini_set('display_errors', true);
error_reporting(E_ALL | E_NOTICE);
$id = mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
```
and see what the response is
**edit**
From your comment it looks like the mysql module is not installed or enabled. You could have a look in your php.ini file and see if there is a line like
```
extension=mysql.so
```
If it is commented with a semi-colon, try removing it and restarting apache
|
278,361 |
<p>I'm updating a long list of records. In my code, everything run as predicted until it execute the query. I get an </p>
<blockquote>
<p>Incorrect syntax near 'TempUpdatePhysicalCityStateZip' </p>
</blockquote>
<p>(my stored procedure name). I've tested it with SQL Server Management Studio and it runs fine. So, I'm not quite sure where I got it wrong. Below is my stored procedure and code:</p>
<pre><code>ALTER PROCEDURE [dbo].[TempUpdateCityStateZip]
@StoreNo nvarchar (11),
@City nvarchar(50),
@State nvarchar(2),
@Zip nvarchar(5)
AS
BEGIN
SET NOCOUNT ON;
UPDATE StoreContact
SET City = @City, State = @State, Zip = @Zip
WHERE StoreNo = @StoreNo
END
</code></pre>
<p>Here is my code:</p>
<pre><code>Dictionary<string, string> CityStateZipList = getCityStateZipList(dbPath);
using (SqlConnection conn = new SqlConnection(dbPath))
{
conn.Open();
SqlCommand cmdUpdate = new SqlCommand("TempUpdateCityStateZip", conn);
foreach (KeyValuePair<string, string> frKeyValue in CityStateZipList)
{
cmdUpdate.Parameters.Clear();
string[] strCityStateZip = frKeyValue.Value.Split(' ');
cmdUpdate.Parameters.AddWithValue("StoreNo", frKeyValue.Key.ToString());
foreach (String i in strCityStateZip)
{
double zipCode;
if (i.Length == 2)
{
cmdUpdate.Parameters.AddWithValue("State", i);
}
else if (i.Length == 5 && double.TryParse(i, out zipCode))
{
cmdUpdate.Parameters.AddWithValue("Zip", i);
}
else
{
cmdUpdate.Parameters.AddWithValue("City", i);
}
}
cmdUpdate.ExecuteNonQuery();
}
}
</code></pre>
|
[
{
"answer_id": 278380,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 3,
"selected": false,
"text": "<p>I believe you can get that puzzling error message if you don't specify the command type:</p>\n\n<pre><code>cmdUpdate.CommandType = CommandType.StoredProcedure;\n</code></pre>\n"
},
{
"answer_id": 278405,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": "<p>Don't you need the @ sign before the parameter?</p>\n\n<pre><code> cmdUpdate.Parameters.AddWithValue(\"@State\", i);\n</code></pre>\n\n<p>FWIW, Thats kind of a dirty piece of code there, you will probably have many issues trying to maintain that. For performance reasons you may want to parse out the CityStateZipList before you open the connection, that way you aren't keeping it open longer than you need.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
I'm updating a long list of records. In my code, everything run as predicted until it execute the query. I get an
>
> Incorrect syntax near 'TempUpdatePhysicalCityStateZip'
>
>
>
(my stored procedure name). I've tested it with SQL Server Management Studio and it runs fine. So, I'm not quite sure where I got it wrong. Below is my stored procedure and code:
```
ALTER PROCEDURE [dbo].[TempUpdateCityStateZip]
@StoreNo nvarchar (11),
@City nvarchar(50),
@State nvarchar(2),
@Zip nvarchar(5)
AS
BEGIN
SET NOCOUNT ON;
UPDATE StoreContact
SET City = @City, State = @State, Zip = @Zip
WHERE StoreNo = @StoreNo
END
```
Here is my code:
```
Dictionary<string, string> CityStateZipList = getCityStateZipList(dbPath);
using (SqlConnection conn = new SqlConnection(dbPath))
{
conn.Open();
SqlCommand cmdUpdate = new SqlCommand("TempUpdateCityStateZip", conn);
foreach (KeyValuePair<string, string> frKeyValue in CityStateZipList)
{
cmdUpdate.Parameters.Clear();
string[] strCityStateZip = frKeyValue.Value.Split(' ');
cmdUpdate.Parameters.AddWithValue("StoreNo", frKeyValue.Key.ToString());
foreach (String i in strCityStateZip)
{
double zipCode;
if (i.Length == 2)
{
cmdUpdate.Parameters.AddWithValue("State", i);
}
else if (i.Length == 5 && double.TryParse(i, out zipCode))
{
cmdUpdate.Parameters.AddWithValue("Zip", i);
}
else
{
cmdUpdate.Parameters.AddWithValue("City", i);
}
}
cmdUpdate.ExecuteNonQuery();
}
}
```
|
I believe you can get that puzzling error message if you don't specify the command type:
```
cmdUpdate.CommandType = CommandType.StoredProcedure;
```
|
278,363 |
<p>My lack of C++ experience, or rather my early learning in garbage collected languages is really stinging me at the moment and I have a problem working with strings in C++.</p>
<p>To make it very clear, using std::string or equlivents is not an option - this is char* 's all the way.</p>
<p>So: what I need to do is very simple and basically boils down to concatenating strings. At runtime I have 2 classes.</p>
<p>One class contains "type" information in the form of a base filename.</p>
<p>in the header:</p>
<pre><code>char* mBaseName;
</code></pre>
<p>and later, in the .cpp it is loaded with info passed in from elsewhere.</p>
<pre><code>mBaseName = attributes->BaseName;
</code></pre>
<p>The 2nd class provides version information in the form of a suffix to the base file name, it's a static class and implemented like this at present:</p>
<pre><code>static const char* const suffixes[] = {"Version1", "Version", "Version3"}; //etc.
static char* GetSuffix()
{
int i = 0;
//perform checks on some data structures
i = somevalue;
return suffixes[i];
}
</code></pre>
<p>Then, at runtime the base class creates the filename it needs:</p>
<pre><code>void LoadStuff()
{
char* suffix = GetSuffix();
char* nameToUse = new char[50];
sprintf(nameToUse, "%s%s",mBaseName,suffix);
LoadAndSetupData(nameToUse);
}
</code></pre>
<p>And you can see the problem immediately. nameToUse never gets deleted, memory leak.</p>
<p>The suffixes are a fixed list, but the basefilenames are arbitrary. The name that is created needs to persist beyond the end of "LoadStuff()" as it's not clear when if and how it is used subsequently.</p>
<p>I am probably worrying too much, or being very stupid, but similar code to LoadStuff() happens in other places too, so it needs solving. It's frustrating as I don't quite know enough about the way things work to see a safe and "un-hacky" solution. In C# I'd just write:</p>
<pre><code>LoadAndSetupData(mBaseName + GetSuffix());
</code></pre>
<p>and wouldn't need to worry.</p>
<p>Any comments, suggestions, or advice much appreciated.</p>
<h2>Update</h2>
<p>The issue with the code I am calling LoadAndSetupData() is that, at some point it probably does copy the filename and keep it locally, but the actual instantiation is asynchranous, LoadAndSetupData actually puts things into a queue, and at that point at least, it expects that the string passed in still exists.</p>
<p>I do not control this code so I can't update it's function.</p>
|
[
{
"answer_id": 278406,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Since std::string is not an option, for whatever reason, have you looked into smart pointers? See <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">boost</a></p>\n\n<p>But I can only encourage you to use std::string.</p>\n\n<p>Christian</p>\n"
},
{
"answer_id": 278408,
"author": "Jonathan Adelson",
"author_id": 8092,
"author_profile": "https://Stackoverflow.com/users/8092",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not totally clear on where LoadAndSetupData is defined, but it looks like it's keeping its own copy of the string. So then you should delete your locally allocated copy after the call to LoadAndSetupData and let it manage its own copy.</p>\n\n<p>Or, make sure LoadAndSetupData cleans up the allocated char[] that you give it.</p>\n\n<p>My preference would be to let the other function keep its own copy and manage it so that you don't allocate an object for another class.</p>\n\n<p>Edit: since you use new with a fixed size [50], you might as well make it local as has been suggested and the let LoadAndSetupData make its own copy.</p>\n"
},
{
"answer_id": 278411,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "<p>Since you need nameToUse to still exist after the function, you are stuck using new, what I would do is return a pointer to it, so the caller can \"delete\" it at a later time when it is no longer needed.</p>\n\n<pre><code>char * LoadStuff()\n{\n char* suffix = GetSuffix();\n char* nameToUse = new char[50];\n sprintf(\"%s%s\",mBaseName,suffix);\n\n LoadAndSetupData(nameToUse);\n return nameToUse;\n}\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>char *name = LoadStuff();\n// do whatever you need to do:\ndelete [] name;\n</code></pre>\n"
},
{
"answer_id": 278415,
"author": "Dani",
"author_id": 28772,
"author_profile": "https://Stackoverflow.com/users/28772",
"pm_score": 0,
"selected": false,
"text": "<p>Where exactly nameToUse is used beyond the scope of LoadStuff? If someone needs it after LoadStuff it needs to pass it, along with the responisbility for memory deallocation</p>\n\n<p>If you would have done it in c# as you suggested</p>\n\n<pre><code>LoadAndSetupData(mBaseName + GetSuffix()); \n</code></pre>\n\n<p>then nothing would reference LoadAndSetupData's parameter, therefore you can safely change it to </p>\n\n<pre><code>char nameToUse[50];\n</code></pre>\n\n<p>as Martin suggested.</p>\n"
},
{
"answer_id": 278419,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>EDIT: This answer doesn't address his problem completely -- I made other suggestions here:\n<a href=\"https://stackoverflow.com/questions/278363/c-string-manipulation#278460\">C++ string manipulation</a></p>\n\n<p>His problem is that he needs to extend the scope of the char* he created to outside the function, and until an asynchronous job is finished.</p>\n\n<p>Original Answer:</p>\n\n<p>In C++, if I can't use the standard library or Boost, I still have a class like this:</p>\n\n<pre><code>template<class T>\nclass ArrayGuard {\n public:\n ArrayGuard(T* ptr) { _ptr = ptr; }\n ~ArrayGuard() { delete[] _ptr; }\n private:\n T* _ptr;\n ArrayGuard(const ArrayGuard&);\n ArrayGuard& operator=(const ArrayGuard&);\n}\n</code></pre>\n\n<p>You use it like:</p>\n\n<pre><code>char* buffer = new char[50];\nArrayGuard<char *> bufferGuard(buffer);\n</code></pre>\n\n<p>The buffer will be deleted at the end of the scope (on return or throw).</p>\n\n<p>For just simple array deleting for dynamic sized arrays that I want to be treated like a static sized array that gets released at the end of the scope.</p>\n\n<p>Keep it simple -- if you need fancier smart pointers, use Boost.</p>\n\n<p>This is useful if the 50 in your example is variable.</p>\n"
},
{
"answer_id": 278423,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 0,
"selected": false,
"text": "<p>You're going to have to manage the lifetime of the memory you allocate for nameToUse. Wrapping it up in a class such as std::string makes your life a bit simpler.</p>\n\n<p>I guess this is a minor outrage, but since I can't think of any better solution to your problem, I'll point out another potential problem. You need to be very careful to check the size of the buffer you're writing into when copying or concatenating strings. Functions such as strcat, strcpy and sprintf can easily overwrite the end of their target buffers, leading to spurious runtime errors and security vulnerabilities.</p>\n\n<p>Apologies, my own experience is mostly on the Windows platform, where they introduced \"safe\" versions of these functions, called strcat_s, strcpy_s, and sprintf_s. The same goes for all their many related functions.</p>\n"
},
{
"answer_id": 278433,
"author": "JSBձոգչ",
"author_id": 8078,
"author_profile": "https://Stackoverflow.com/users/8078",
"pm_score": 0,
"selected": false,
"text": "<p>First: Why do you need for the allocated string to persist beyond the end of LoadStuff()? Is there a way you can refactor to remove that requirement.</p>\n\n<p>Since C++ doesn't provide a straightforward way to do this kind of stuff, most programming environments use a set of guidelines about pointers to prevent delete/free problems. Since things can only be allocated/freed once, it needs to be very clear who \"owns\" the pointer. Some sample guidelines:</p>\n\n<p>1) Usually the person that allocates the string is the owner, and is also responsible for freeing the string.</p>\n\n<p>2) If you need to free in a different function/class than you allocated in, there must be an explicit hand-off of ownership to another class/function.</p>\n\n<p>3) Unless explicitly stated otherwise, pointers (including strings) belong to the caller. A function, constructor, etc. cannot assume that the string pointer it gets will persist beyond the end of the function call. If they need a persistent copy of the pointer, they should make a local copy with strdup().</p>\n\n<p>What this boils down to in your specific case is that LoadStuff() should delete[] nameToUse, and the function that it calls should make a local copy.</p>\n\n<p>One alternate solution: if nameToUse is going to be passed lots of places and needs to persist for the lifetime of the program, you could make it a global variable. (This saves the trouble of making lots of copies of it.) If you don't want to pollute your global namespace, you could just declare it static local to the function:</p>\n\n<pre><code>static char *nameToUse = new char[50];\n</code></pre>\n"
},
{
"answer_id": 278444,
"author": "Todd Gamblin",
"author_id": 9122,
"author_profile": "https://Stackoverflow.com/users/9122",
"pm_score": 2,
"selected": false,
"text": "<p>If you must use char*'s, then LoadAndSetupData() should explicitly document who owns the memory for the char* after the call. You can do one of two things:</p>\n\n<ol>\n<li><p><strong>Copy the string.</strong> This is probably the simplest thing. LoadAndSetupData copies the string into some internal buffer, and the caller is always responsible for the memory.</p></li>\n<li><p><strong>Transfer ownership.</strong> LoadAndSetupData() documents that it will be responsible for eventually freeing the memory for the char*. The caller doesn't need to worry about freeing the memory. </p></li>\n</ol>\n\n<p>I generally prefer safe copying as in #1, because the allocator of the string is also responsible for freeing it. If you go with #2, the allocator has to remember NOT to free things, and memory management happens in two places, which I find harder to maintain. In either case, it's a matter of <strong>explicitly documenting</strong> the policy so that the caller knows what to expect.</p>\n\n<p>If you go with #1, take a look at Lou Franco's answer to see how you might allocate a char[] in an exception-safe, sure to be freed way using a guard class. Note that you can't (safely) use std::auto_ptr for arrays.</p>\n"
},
{
"answer_id": 278460,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>Seeing now that the issue is how to clean up the string that you created and passed to LoadAndSetUpData()</p>\n\n<p>I am assuming that:</p>\n\n<ol>\n<li>LoadAndSetUpData() does not make its own copy</li>\n<li>You can't change LoadAndSetUpData() to do that</li>\n<li>You need the string to still exist for some time after LoadAndSetupData() returns</li>\n</ol>\n\n<p>Here are suggestions:</p>\n\n<ol>\n<li><p>Can you make your own queue objects to be called? Are they guaranteed to be called after the ones that use your string. If so, create cleanup queue events with the same string that call delete[] on them</p></li>\n<li><p>Is there a maximum number you can count on. If you created a large array of strings, could you use them in a cycle and be assured that when you got back to the beginning, it would be ok to reuse that string</p></li>\n<li><p>Is there an amount of time you can count on? If so, register them for deletion somewhere and check that after some time.</p></li>\n</ol>\n\n<p>The best thing would be for functions that take char* to take ownership or copy. Shared ownership is the hardest thing to do without reference counting or garbage collection.</p>\n"
},
{
"answer_id": 278464,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": false,
"text": "<p>The thing to remember with C++ memory management is ownership. If the LoadAndSetupData data is not going to take ownership of the string, then it's still your responsibility. Since you can't delete it immediately (because of the asynchronicity issue), you're going to have to hold on to those pointers until such time as you know you can delete them. </p>\n\n<p>Maintain a pool of strings that you have created:</p>\n\n<ul>\n<li>If you have some point in time where you know that the queue has been completely dealt with, you can simply delete all the strings in the pool. </li>\n<li>If you know that all strings created after a certain point in time have been dealt with, then keep track of when the strings were created, and you can delete that subset. - If you can somehow find out when an individual string has been dealt with, then just delete that string.</li>\n</ul>\n\n<hr>\n\n<pre><code>class StringPool\n{\n struct StringReference {\n char *buffer;\n time_t created;\n } *Pool;\n\n size_t PoolSize;\n size_t Allocated;\n\n static const size_t INITIAL_SIZE = 100;\n\n void GrowBuffer()\n {\n StringReference *newPool = new StringReference[PoolSize * 2];\n for (size_t i = 0; i < Allocated; ++i)\n newPool[i] = Pool[i];\n StringReference *oldPool = Pool;\n Pool = newPool;\n delete[] oldPool;\n }\n\npublic:\n\n StringPool() : Pool(new StringReference[INITIAL_SIZE]), PoolSize(INITIAL_SIZE)\n {\n }\n\n ~StringPool()\n {\n ClearPool();\n delete[] Pool;\n }\n\n char *GetBuffer(size_t size)\n {\n if (Allocated == PoolSize)\n GrowBuffer();\n Pool[Allocated].buffer = new char[size];\n Pool[Allocated].buffer = time(NULL);\n ++Allocated;\n }\n\n void ClearPool()\n {\n for (size_t i = 0; i < Allocated; ++i)\n delete[] Pool[i].buffer;\n Allocated = 0;\n }\n\n void ClearBefore(time_t knownCleared)\n {\n size_t newAllocated = 0;\n for (size_t i = 0; i < Allocated; ++i)\n {\n if (Pool[i].created < knownCleared)\n {\n delete[] Pool[i].buffer;\n }\n else\n {\n Pool[newAllocated] = Pool[i];\n ++newAllocated;\n }\n }\n Allocated = newAllocated;\n }\n\n // This compares pointers, not strings!\n void ReleaseBuffer(char *knownCleared)\n {\n size_t newAllocated = 0;\n for (size_t i = 0; i < Allocated; ++i)\n {\n if (Pool[i].buffer == knownCleared)\n {\n delete[] Pool[i].buffer;\n }\n else\n {\n Pool[newAllocated] = Pool[i];\n ++newAllocated;\n }\n }\n Allocated = newAllocated;\n }\n\n};\n</code></pre>\n"
},
{
"answer_id": 278470,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 1,
"selected": false,
"text": "<p>There is no need to allocate on heap in this case. And always use snprintf:</p>\n\n<pre><code>char nameToUse[50];\nsnprintf(nameToUse, sizeof(nameToUse), \"%s%s\",mBaseName,suffix);\n</code></pre>\n"
},
{
"answer_id": 278590,
"author": "xan",
"author_id": 15667,
"author_profile": "https://Stackoverflow.com/users/15667",
"pm_score": 0,
"selected": false,
"text": "<p>Thankyou everyone for your answers. I have not selected one as \"the answer\" as there isn't a concrete solution to this problem and the best discussions on it are all upvoted be me and others anyway.</p>\n\n<p>Your suggestions are all good, and you have been very patient with the clunkiness of my question. As I am sure you can see, this is a simplification of a more complicated problem and there is a lot more going on which is connected with the example I gave, hence the way that bits of it may not have entirely made sense.</p>\n\n<p>For your interest I have decided to \"cheat\" my way out of the difficulty for now. I said that the base names were arbitrary, but this isn't quite true. In fact they are a limited set of names too, just a limited set that could change at some point, so I was attempting to solve a more general problem.</p>\n\n<p>For now I will extend the \"static\" solution to suffixes and build a table of possible names. This is very \"hacky\", but will work and moreover avoids refactoring a large amount of complex code which I am not able to.</p>\n\n<p>Feedback has been fantastic, many thanks.</p>\n"
},
{
"answer_id": 278842,
"author": "orcmid",
"author_id": 33810,
"author_profile": "https://Stackoverflow.com/users/33810",
"pm_score": 0,
"selected": false,
"text": "<p>You can combine some of the ideas here.</p>\n\n<p>Depending on how you have modularized your application, there may be a method (main?) whose execution determines the scope in which nameToUse is definable as a fixed size local variable. You can pass the pointer (&nameToUse[0] or simply nameToUse) to those other methods that need to fill it (so pass the size too) or use it, knowing that the storage will disappear when the function having the local variable exits or your program terminates by any other means.</p>\n\n<p>There is little difference between this and using dynamic allocation and deletion (since the pointer holding the location will have to be managed more-or-less the same way). The local allocation is more direct in many cases and is very inexpensive when there is no problem with associating the maximum-required lifetime with the duration of a particular function's execution.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15667/"
] |
My lack of C++ experience, or rather my early learning in garbage collected languages is really stinging me at the moment and I have a problem working with strings in C++.
To make it very clear, using std::string or equlivents is not an option - this is char\* 's all the way.
So: what I need to do is very simple and basically boils down to concatenating strings. At runtime I have 2 classes.
One class contains "type" information in the form of a base filename.
in the header:
```
char* mBaseName;
```
and later, in the .cpp it is loaded with info passed in from elsewhere.
```
mBaseName = attributes->BaseName;
```
The 2nd class provides version information in the form of a suffix to the base file name, it's a static class and implemented like this at present:
```
static const char* const suffixes[] = {"Version1", "Version", "Version3"}; //etc.
static char* GetSuffix()
{
int i = 0;
//perform checks on some data structures
i = somevalue;
return suffixes[i];
}
```
Then, at runtime the base class creates the filename it needs:
```
void LoadStuff()
{
char* suffix = GetSuffix();
char* nameToUse = new char[50];
sprintf(nameToUse, "%s%s",mBaseName,suffix);
LoadAndSetupData(nameToUse);
}
```
And you can see the problem immediately. nameToUse never gets deleted, memory leak.
The suffixes are a fixed list, but the basefilenames are arbitrary. The name that is created needs to persist beyond the end of "LoadStuff()" as it's not clear when if and how it is used subsequently.
I am probably worrying too much, or being very stupid, but similar code to LoadStuff() happens in other places too, so it needs solving. It's frustrating as I don't quite know enough about the way things work to see a safe and "un-hacky" solution. In C# I'd just write:
```
LoadAndSetupData(mBaseName + GetSuffix());
```
and wouldn't need to worry.
Any comments, suggestions, or advice much appreciated.
Update
------
The issue with the code I am calling LoadAndSetupData() is that, at some point it probably does copy the filename and keep it locally, but the actual instantiation is asynchranous, LoadAndSetupData actually puts things into a queue, and at that point at least, it expects that the string passed in still exists.
I do not control this code so I can't update it's function.
|
Since std::string is not an option, for whatever reason, have you looked into smart pointers? See [boost](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smart_ptr.htm)
But I can only encourage you to use std::string.
Christian
|
278,398 |
<p>I'd like to have a blank line after my bash prompt and before the output on my Mac. It should look like this would:</p>
<pre><code>echo; ls
</code></pre>
<p>Can I add a newline to my bash prompt and then go back up one line to wait for user input? Is there something obvious I'm missing?</p>
|
[
{
"answer_id": 278414,
"author": "Paul D. Eden",
"author_id": 3045,
"author_profile": "https://Stackoverflow.com/users/3045",
"pm_score": 2,
"selected": false,
"text": "<p>To my knowledge this is not possible unless you delve into more low-level stuff like full-screen emulators like curses.</p>\n"
},
{
"answer_id": 278422,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 2,
"selected": false,
"text": "<p>This is a bit of a stab in the dark, but you <em>may</em> be able to use <a href=\"http://www.ibiblio.org/pub/historic-linux/ftp-archives/tsx-11.mit.edu/Oct-07-1996/info/vt102.codes\" rel=\"nofollow noreferrer\">VT102 terminal codes</a> to control the cursor without having to use Curses. The relevant VT102 commands that you'd be interested in all consist of sending ESC, then [, then the specific command parameters.</p>\n\n<p>For instance, to move the cursor up one line, one needs to output:</p>\n\n<pre><code>ESC [ 1 A\n0x1B 0x5B 0x31 0x41\n</code></pre>\n\n<p>Be warned that the VT102 documentation generally uses octal, so keep an <a href=\"http://www.asciitable.com/\" rel=\"nofollow noreferrer\">ascii table</a> handy if you're using hex.</p>\n\n<p>All of this advice is given without having tested it -- I don't know if VT102 commands can be embedded into your bash prompt, but I thought it might be worth a shot.</p>\n\n<p>Edit: Yeah -- looks like <a href=\"http://www.mail-archive.com/[email protected]/msg05109.html\" rel=\"nofollow noreferrer\">a lot of people</a> use VT102 formatting codes in their bash prompts. To translate my above example into something Bash would recognize, putting:</p>\n\n<pre><code>\\e[1A\n</code></pre>\n\n<p>into your prompt should move the cursor up one line.</p>\n"
},
{
"answer_id": 278502,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "<p>I believe (but haven't tried) if you put <code>'\\n\\b'</code> in the prompt string it would do that.</p>\n"
},
{
"answer_id": 857990,
"author": "Pianosaurus",
"author_id": 44680,
"author_profile": "https://Stackoverflow.com/users/44680",
"pm_score": 2,
"selected": false,
"text": "<p>This is very possible. If your bash has <code>C-v</code> set as the readline quoted-insert command, you can simply add the following to your <code>~/.inputrc</code>:</p>\n\n<pre><code>RETURN: \"\\C-e\\C-v\\n\\C-v\\n\\n\"</code></pre>\n\n<p>This wil make bash (readline, actually) insert two verbatim newlines before a regular interpreted newline. By default, only one is inserted, which is what causes output to start on the line after the prompt.</p>\n\n<p>You can test if <code>C-v</code> is set to quoted-insert by typing it in bash (that's <code>Ctrl+V</code>) followed by e.g. an up arrow. This should print <code>^[[A</code> or something similar. If it doesn't, you can bind it in <code>~/.inputrc</code> too:</p>\n\n<pre><code>C-v: quoted-insert\nRETURN: \"\\C-e\\C-v\\n\\C-v\\n\\n\"</code></pre>\n\n<p><code>~/.inputrc</code> can be created if it doesn't exist. The changes will not take effect in running bashes unless you issue a readline re-read-init-file command (by default on <code>C-x C-r</code>). Be careful though. If you do something wrong, enter will no longer issue commands, and fixing your mistake could prove to be difficult. If you should do something wrong, <code>C-o</code> will by default also accept the line.</p>\n\n<p>Adding a newline followed by moving the cursor back to the regular prompt (like you described) is possible, but will not have the effect you intend. The newline you inserted would simply be overwritten by the application output, since you moved the cursor back in front of it.</p>\n"
},
{
"answer_id": 977256,
"author": "Jerry Penner",
"author_id": 83680,
"author_profile": "https://Stackoverflow.com/users/83680",
"pm_score": 0,
"selected": false,
"text": "<p>In general, if you want to find out the codes to do anything a terminal can do, read the <code>terminfo</code> man page.</p>\n\n<p>In this case, the <em>cursor up one line</em> code can be determined by:</p>\n\n<pre><code>tput cuu1\n</code></pre>\n\n<p>If you redirect the tput output to a file, you can see what control characters are used.</p>\n\n<p>Bash also supports the PROMPT_COMMAND variable, allowing you to run arbitrary commands before each prompt is issued.</p>\n"
},
{
"answer_id": 3392660,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 2,
"selected": false,
"text": "<p>This works:</p>\n\n<pre><code>trap echo DEBUG\n</code></pre>\n\n<p>It doesn't add an extra newline if you hit return at an empty prompt.</p>\n\n<p>The command above will cause a newline to be output for every member of a pipeline or multi-command line such as:</p>\n\n<pre><code>$ echo foo; echo bar\n\\n\nfoo\n\\n\nbar\n</code></pre>\n\n<p>To prevent that so that only one extra newline is output before all command output:</p>\n\n<pre><code>PROMPT_COMMAND='_nl=true'; trap -- '$_nl && [[ $BASH_COMMAND != $PROMPT_COMMAND ]] && echo; _nl=false' DEBUG\n</code></pre>\n\n<p>The <code>DEBUG</code> trap is performed before each command so before the first command it checks to see if the flag is true and, if so, outputs a newline. Then it sets the flag to false so each command afterwards on the line doesn't trigger an extra newline.</p>\n\n<p>The contents of <code>$PROMPT_COMMAND</code> are executed before the prompt is output so the flag is set to true - ready for the next cycle.</p>\n\n<p>Because pressing enter on an empty command line still triggers the execution of the contents of <code>$PROMPT_COMMAND</code> the test in the trap also checks for those contents as the current command and doesn't perform the <code>echo</code> if they match.</p>\n"
},
{
"answer_id": 13019345,
"author": "Matt",
"author_id": 1766551,
"author_profile": "https://Stackoverflow.com/users/1766551",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is old but for someone like me who came across this while googling for it. This is how you do this...\nIt's actually pretty simple!</p>\n\n<p>Check out this link --> <a href=\"http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html\" rel=\"noreferrer\">Cursor Movement</a></p>\n\n<p>Basically to move up N number of lines:</p>\n\n<pre><code>echo -e \"\\033[<N>A HELLO WORLD\\n\"\n</code></pre>\n\n<p>Just change the \"<em>< N ></em>\" to however many lines you want to go back...\nFor instance, to move up 5 lines it would be <strong>\"/033[5A\"</strong></p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019/"
] |
I'd like to have a blank line after my bash prompt and before the output on my Mac. It should look like this would:
```
echo; ls
```
Can I add a newline to my bash prompt and then go back up one line to wait for user input? Is there something obvious I'm missing?
|
I know this is old but for someone like me who came across this while googling for it. This is how you do this...
It's actually pretty simple!
Check out this link --> [Cursor Movement](http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html)
Basically to move up N number of lines:
```
echo -e "\033[<N>A HELLO WORLD\n"
```
Just change the "*< N >*" to however many lines you want to go back...
For instance, to move up 5 lines it would be **"/033[5A"**
|
278,416 |
<p>I have a C++ assembly with both managed and umanaged code compiled to
a DLL. It is correctly imported into the project references as I can
see all my classes and their members with the Object Browser.</p>
<p>The problem is with the XAML Design view. In my XAML code I want to
make a data bind with my C++ assembly so I have the namespace like so:</p>
<pre><code>xmlns:kudu="clr-namespace:kudu;assembly=CLI"
</code></pre>
<p>CLI is the name of the dll and it has a namespace inside called kudu.
The Design view refuses to shows the XAML and gives me this error:</p>
<pre>Assembly 'CLI' was not found. Verify that you are not missing an
assembly reference. Also, verify that your project and all referenced
assemblies have been built.</pre>
<p>The best part is I can actually build the entire solution and
everything works! The window updates as the C++ objects change and
what not. However with out the Design view this makes continuing
development quite difficult.</p>
<p>Does anyone have an answer as to why this happens and how I can fix
it? </p>
|
[
{
"answer_id": 278531,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 2,
"selected": true,
"text": "<p>This is probably happening because the ide cannot load one of the unmanaged dll's. You may have to move them into the windows/system32.</p>\n"
},
{
"answer_id": 369500,
"author": "Jippers",
"author_id": 36234,
"author_profile": "https://Stackoverflow.com/users/36234",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative solution I've found to this is add to the windows PATH variable the bin directory of my assembly which has all the DLLs. </p>\n"
},
{
"answer_id": 838027,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Very helpful, thanks for this insight.</p>\n\n<p>My solution is to copy the DLLs into the output directory using a Post-Build event.\nHere's how\n1. Project Properties / Build Events \n2. Set Post-build event command line:</p>\n\n<p>copy path_to_dependent_dlls .</p>\n\n<p>Oh, and I find that a VStudio restart is required for it to start working ...</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36234/"
] |
I have a C++ assembly with both managed and umanaged code compiled to
a DLL. It is correctly imported into the project references as I can
see all my classes and their members with the Object Browser.
The problem is with the XAML Design view. In my XAML code I want to
make a data bind with my C++ assembly so I have the namespace like so:
```
xmlns:kudu="clr-namespace:kudu;assembly=CLI"
```
CLI is the name of the dll and it has a namespace inside called kudu.
The Design view refuses to shows the XAML and gives me this error:
```
Assembly 'CLI' was not found. Verify that you are not missing an
assembly reference. Also, verify that your project and all referenced
assemblies have been built.
```
The best part is I can actually build the entire solution and
everything works! The window updates as the C++ objects change and
what not. However with out the Design view this makes continuing
development quite difficult.
Does anyone have an answer as to why this happens and how I can fix
it?
|
This is probably happening because the ide cannot load one of the unmanaged dll's. You may have to move them into the windows/system32.
|
278,421 |
<p>I'm trying to drop a SQL Server database using the following code:</p>
<pre><code>SqlCommand command = new SqlCommand("USE MASTER; ALTER DATABASE @database SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE @Database", connection);
command.Parameters.AddWithValue("@database", TestingEnvironment.DatabaseName);
command.ExecuteNonQuery();
</code></pre>
<p>When I execute it, I get the error:</p>
<blockquote>
<p>Incorrect syntax near '@database'.
Incorrect syntax near the keyword
'with'. If this statement is a common
table expression or an xmlnamespaces
clause, the previous statement must be
terminated with a semicolon. Incorrect
syntax near 'IMMEDIATE'.</p>
</blockquote>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 278492,
"author": "Mr. Flibble",
"author_id": 34632,
"author_profile": "https://Stackoverflow.com/users/34632",
"pm_score": 0,
"selected": false,
"text": "<p>Are the Params case sensitive? You have a capital D in the 2nd @Database.</p>\n"
},
{
"answer_id": 278568,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 4,
"selected": true,
"text": "<p>putting it simply the Alter Database command doesn't support parameters as you want it to. you'll have to concat strings here.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1727/"
] |
I'm trying to drop a SQL Server database using the following code:
```
SqlCommand command = new SqlCommand("USE MASTER; ALTER DATABASE @database SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE @Database", connection);
command.Parameters.AddWithValue("@database", TestingEnvironment.DatabaseName);
command.ExecuteNonQuery();
```
When I execute it, I get the error:
>
> Incorrect syntax near '@database'.
> Incorrect syntax near the keyword
> 'with'. If this statement is a common
> table expression or an xmlnamespaces
> clause, the previous statement must be
> terminated with a semicolon. Incorrect
> syntax near 'IMMEDIATE'.
>
>
>
What am I doing wrong?
|
putting it simply the Alter Database command doesn't support parameters as you want it to. you'll have to concat strings here.
|
278,429 |
<p>I have a piece of code looking like this : </p>
<pre><code>TAxis *axis = 0;
if (dynamic_cast<MonitorObjectH1C*>(obj))
axis = (dynamic_cast<MonitorObjectH1C*>(obj))->GetXaxis();
</code></pre>
<p>Sometimes it crashes : </p>
<pre><code>Thread 1 (Thread -1208658240 (LWP 11400)):
#0 0x0019e7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1 0x048c67fb in __waitpid_nocancel () from /lib/tls/libc.so.6
#2 0x04870649 in do_system () from /lib/tls/libc.so.6
#3 0x048709c1 in system () from /lib/tls/libc.so.6
#4 0x001848bd in system () from /lib/tls/libpthread.so.0
#5 0x0117a5bb in TUnixSystem::Exec () from /opt/root/lib/libCore.so.5.21
#6 0x01180045 in TUnixSystem::StackTrace () from /opt/root/lib/libCore.so.5.21
#7 0x0117cc8a in TUnixSystem::DispatchSignals ()
from /opt/root/lib/libCore.so.5.21
#8 0x0117cd18 in SigHandler () from /opt/root/lib/libCore.so.5.21
#9 0x0117bf5d in sighandler () from /opt/root/lib/libCore.so.5.21
#10 <signal handler called>
#11 0x0533ddf4 in __dynamic_cast () from /usr/lib/libstdc++.so.6
</code></pre>
<p>I have no clue why it crashes. <em>obj</em> is not null (and if it was it would not be a problem, would it ?). </p>
<p>What could be the reason for a dynamic cast to crash ? </p>
<p>If it can't cast, it should just return NULL no ?</p>
|
[
{
"answer_id": 278479,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>Can the value of obj be changed by a different thread?</p>\n"
},
{
"answer_id": 278483,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "<p>dynamic_cast will return 0 if the cast fails and you are casting to a pointer, which is your case. The problem is that you have either corrupted the heap earlier in your code, or rtti wasn't enabled.</p>\n"
},
{
"answer_id": 278514,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>Are you sure that the value of 'obj' has been correctly defined?</p>\n\n<p>If for example it is uninitialised (ie random) them I could see it causing a crash.</p>\n"
},
{
"answer_id": 278556,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>As it crashes only sometimes, i bet it's a threading issue. Check all references to 'obj':</p>\n\n<pre>grep -R 'obj.*=' .</pre>\n"
},
{
"answer_id": 278575,
"author": "bradtgmurray",
"author_id": 1546,
"author_profile": "https://Stackoverflow.com/users/1546",
"pm_score": 4,
"selected": false,
"text": "<p>I suggest using a different syntax for this code snippet.</p>\n\n<pre><code>if (MonitorObjectH1C* monitorObject = dynamic_cast<MonitorObjectH1C*>(obj))\n{\n axis = monitorObject->GetXaxis();\n}\n</code></pre>\n\n<p>You can still crash if some other thread is deleting what monitorObject points to or if obj is crazy garbage, but at least your problem isn't casting related anymore and you're not doing the dynamic_cast twice.</p>\n"
},
{
"answer_id": 280031,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 6,
"selected": true,
"text": "<p>Some possible reasons for the crash:</p>\n\n<ul>\n<li><code>obj</code> points to an object with a non-polymorphic type (a class or struct with no virtual methods, or a fundamental type).</li>\n<li><code>obj</code> points to an object that has been freed.</li>\n<li><code>obj</code> points to unmapped memory, or memory that has been mapped in such a way as to generate an exception when accessed (such as a guard page or inaccessible page).</li>\n<li><code>obj</code> points to an object with a polymorphic type, but that type was defined in an external library that was compiled with RTTI disabled.</li>\n</ul>\n\n<p>Not all of these problems necessarily cause a crash in all situations.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20986/"
] |
I have a piece of code looking like this :
```
TAxis *axis = 0;
if (dynamic_cast<MonitorObjectH1C*>(obj))
axis = (dynamic_cast<MonitorObjectH1C*>(obj))->GetXaxis();
```
Sometimes it crashes :
```
Thread 1 (Thread -1208658240 (LWP 11400)):
#0 0x0019e7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1 0x048c67fb in __waitpid_nocancel () from /lib/tls/libc.so.6
#2 0x04870649 in do_system () from /lib/tls/libc.so.6
#3 0x048709c1 in system () from /lib/tls/libc.so.6
#4 0x001848bd in system () from /lib/tls/libpthread.so.0
#5 0x0117a5bb in TUnixSystem::Exec () from /opt/root/lib/libCore.so.5.21
#6 0x01180045 in TUnixSystem::StackTrace () from /opt/root/lib/libCore.so.5.21
#7 0x0117cc8a in TUnixSystem::DispatchSignals ()
from /opt/root/lib/libCore.so.5.21
#8 0x0117cd18 in SigHandler () from /opt/root/lib/libCore.so.5.21
#9 0x0117bf5d in sighandler () from /opt/root/lib/libCore.so.5.21
#10 <signal handler called>
#11 0x0533ddf4 in __dynamic_cast () from /usr/lib/libstdc++.so.6
```
I have no clue why it crashes. *obj* is not null (and if it was it would not be a problem, would it ?).
What could be the reason for a dynamic cast to crash ?
If it can't cast, it should just return NULL no ?
|
Some possible reasons for the crash:
* `obj` points to an object with a non-polymorphic type (a class or struct with no virtual methods, or a fundamental type).
* `obj` points to an object that has been freed.
* `obj` points to unmapped memory, or memory that has been mapped in such a way as to generate an exception when accessed (such as a guard page or inaccessible page).
* `obj` points to an object with a polymorphic type, but that type was defined in an external library that was compiled with RTTI disabled.
Not all of these problems necessarily cause a crash in all situations.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.