qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
134,845
|
<p>The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="#" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
<p>or</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 134853,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 8,
"selected": false,
"text": "'#' void(0) javascript:; javascript:void(0);"
},
{
"answer_id": 134865,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 7,
"selected": false,
"text": "<a href=\"#\" onclick=\"myJsFunc(); return false;\">Link</a>\n <a [routerLink]=\"\" (click)=\"passTheSalt()\">Click me</a>"
},
{
"answer_id": 135120,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 7,
"selected": false,
"text": "<a href=\"javascriptlessDestination.html\" onclick=\"myJSFunc(); return false;\">Link text</a>\n"
},
{
"answer_id": 135139,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 4,
"selected": false,
"text": "return false; javascript:void(0)"
},
{
"answer_id": 135200,
"author": "Peter",
"author_id": 8792,
"author_profile": "https://Stackoverflow.com/users/8792",
"pm_score": 3,
"selected": false,
"text": "# href onclick #"
},
{
"answer_id": 135248,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 7,
"selected": false,
"text": "<span> onclick handler <a> function callFunction() { console.log(\"function called\"); } .jsAction {\n cursor: pointer;\n color: #00f;\n text-decoration: underline;\n} <p>I want to call a JavaScript function <span class=\"jsAction\" onclick=\"callFunction();\">here</span>.</p>"
},
{
"answer_id": 136103,
"author": "Will Read",
"author_id": 22396,
"author_profile": "https://Stackoverflow.com/users/22396",
"pm_score": 4,
"selected": false,
"text": "<a href=\"javascript:myJsFunc()\">Link Text</a>\n # <a href=\"javascriptlessDestination.html\" onclick=\"myJSFunc(); return false;\">Link text</a>\n javascript:void(0)"
},
{
"answer_id": 136225,
"author": "CleverPatrick",
"author_id": 22399,
"author_profile": "https://Stackoverflow.com/users/22399",
"pm_score": 4,
"selected": false,
"text": "<span>"
},
{
"answer_id": 136340,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 3,
"selected": false,
"text": "<a href=\"javascript:(function()%7Balert(%22test%22)%3B%7D)()%3B\">test</a>\n"
},
{
"answer_id": 138233,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 11,
"selected": false,
"text": "javascript:void(0) # function doSomething() {\n //Some code\n return false;\n}\n return doSomething() doSomething() # return false; onclick onclick onclick=\"someFunc.call(this)\"\n onclick=\"someFunc.apply(this, arguments)\"\n javascript:void(0) href=\"#\" onclick return false; onclick false href=\"javascript:void(0)\""
},
{
"answer_id": 138934,
"author": "Pablo Cabrera",
"author_id": 12540,
"author_profile": "https://Stackoverflow.com/users/12540",
"pm_score": 3,
"selected": false,
"text": "<a> <a href=\"javascript:myJSFunc();\" />myLink</a>\n attachEvent addEventListener"
},
{
"answer_id": 143410,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 6,
"selected": false,
"text": "href return false false true function doSomething() {\n alert( 'you clicked on the link' );\n return true;\n}\n <a href=\"path/to/some/url\" onclick=\"return !doSomething();\">link text</a>\n doSomething() true false path/to/some/URL false true path/to/some/URL"
},
{
"answer_id": 209580,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 6,
"selected": false,
"text": "<button>"
},
{
"answer_id": 209618,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 4,
"selected": false,
"text": "<a href=\"search.php\" id=\"searchLink\">Search</a>\n var link = document.getElementById('searchLink');\n\nlink.onclick = function() {\n try {\n // Do Stuff Here \n } finally {\n return false;\n }\n};\n search.php"
},
{
"answer_id": 229157,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 5,
"selected": false,
"text": "$(document).ready(function() {\n $(\"a\").css(\"cursor\", \"pointer\");\n});\n href=\"#\" href=\"javascript:void(0)\" <a onclick=\"hello()\">Hello</a>\n"
},
{
"answer_id": 229926,
"author": "Matt Goddard",
"author_id": 5185,
"author_profile": "https://Stackoverflow.com/users/5185",
"pm_score": 3,
"selected": false,
"text": "var [functionName] = function() {\n // do something\n};\n\njQuery(\"[link id or other selector]\").bind(\"click\", [functionName]);\n"
},
{
"answer_id": 598317,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<a href=\"javascript:void('open popup image')\" onclick=\"return f()\">...</a>\n"
},
{
"answer_id": 759284,
"author": "se_pavel",
"author_id": 80917,
"author_profile": "https://Stackoverflow.com/users/80917",
"pm_score": 6,
"selected": false,
"text": "<a href=\"javascript:;\" onclick=\"myJsFunc();\">Link</a>\n <a href=\"javascript:void(0);\" onclick=\"myJsFunc();\">Link</a>\n"
},
{
"answer_id": 1691745,
"author": "Free Consulting",
"author_id": 205376,
"author_profile": "https://Stackoverflow.com/users/205376",
"pm_score": 5,
"selected": false,
"text": "# ...href=\"javascript_required.html\" onclick=\"..."
},
{
"answer_id": 1785783,
"author": "Justin Johnson",
"author_id": 126562,
"author_profile": "https://Stackoverflow.com/users/126562",
"pm_score": 6,
"selected": false,
"text": "# javascript:anything <a href=\"/gracefully/degrading/url/with/same/functionality.ext\" class=\"some-selector\">For great justice</a>\n $(function() {\n $(\".some-selector\").click(myJsFunc);\n});\n"
},
{
"answer_id": 3273564,
"author": "user394888",
"author_id": 394888,
"author_profile": "https://Stackoverflow.com/users/394888",
"pm_score": 3,
"selected": false,
"text": "void(0) <a href=\"./Readable/Text/URL/Pointing/To/Server-Side/Script\" id=\"theLinkId\">WhyClickHere</a>\n"
},
{
"answer_id": 6829393,
"author": "user564706",
"author_id": 564706,
"author_profile": "https://Stackoverflow.com/users/564706",
"pm_score": 5,
"selected": false,
"text": "javascript:void(0) javascript:;"
},
{
"answer_id": 7536475,
"author": "Spammer Joe",
"author_id": 962185,
"author_profile": "https://Stackoverflow.com/users/962185",
"pm_score": 6,
"selected": false,
"text": "# #self JavaScript bla, bla,"
},
{
"answer_id": 8511644,
"author": "Jesse Atkinson",
"author_id": 762889,
"author_profile": "https://Stackoverflow.com/users/762889",
"pm_score": 3,
"selected": false,
"text": "<a> <a class=\"trigger\" href=\"#\">Click me!</a> $('.trigger').click(function (e) {\n e.preventDefault();\n // Do stuff...\n});\n <span> <div> cursor: pointer;"
},
{
"answer_id": 8512410,
"author": "Josh Simerman",
"author_id": 200292,
"author_profile": "https://Stackoverflow.com/users/200292",
"pm_score": 4,
"selected": false,
"text": "javascript:void(0); # javascript:void(0); <p><a href=\"Home/ChangePicture\" onclick=\"return ChangePicture_onClick();\" title=\"Change Picture\">Change Picture</a></p>\n\n<script type=\"text/javascript\">\n function ChangePicture_onClick() {\n $.get('Home/ChangePicture',\n function (htmlResult) {\n $(\"#ModalViewDiv\").remove(); //Prevent duplicate dialogs\n $(\"#modalContainer\").append(htmlResult);\n $(\"#ModalViewDiv\").dialog({\n width: 400,\n modal: true,\n buttons: {\n \"Upload\": function () {\n if(!ValidateUpload()) return false;\n $(\"#ModalViewDiv\").find(\"form\").submit();\n },\n Cancel: function () { $(this).dialog(\"close\"); }\n },\n close: function () { }\n });\n }\n );\n return false;\n }\n</script>\n"
},
{
"answer_id": 8517735,
"author": "Berker Yüceer",
"author_id": 861019,
"author_profile": "https://Stackoverflow.com/users/861019",
"pm_score": 3,
"selected": false,
"text": "<a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a>\n <a href=\"#\" onclick=\"myJsFunc();\">Link</a>\n <a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a> <a href=\"#\" onclick=\"myJsFunc();\">Link</a> javascript: <a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a>\n $(document).ready(function(){\n $(\".blabla\").append('<a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a>')\n});\n"
},
{
"answer_id": 8525002,
"author": "Tracker1",
"author_id": 43906,
"author_profile": "https://Stackoverflow.com/users/43906",
"pm_score": 8,
"selected": false,
"text": "<button></button> button.link {\n display: inline-block;\n position: relative;\n background-color: transparent;\n cursor: pointer;\n border: 0;\n padding: 0;\n color: #00f;\n text-decoration: underline;\n font: inherit;\n} <p>A button that looks like a <button type=\"button\" class=\"link\">link</button>.</p> onclick javascript:void(0); 0 javascript:void('Delete record 123')"
},
{
"answer_id": 8528329,
"author": "Eric Yin",
"author_id": 939713,
"author_profile": "https://Stackoverflow.com/users/939713",
"pm_score": 5,
"selected": false,
"text": "<a href=\"#\" onclick=\"myJsFunc();return false;\">Link</a>\n href 404 not found return false; back"
},
{
"answer_id": 9440536,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 10,
"selected": false,
"text": "<a href=\"#\" onclick=\"myJsFunc();\">Link</a> <a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a> onclick href // Cancel click event\n$('.cancel-action').click(function(){\n alert('Cancel action occurs!');\n});\n\n// Hover shim for Internet Explorer 6 and Internet Explorer 7.\n$(document.body).on('hover','a',function(){\n $(this).toggleClass('hover');\n}); a { cursor: pointer; color: blue; }\na:hover,a.hover { text-decoration: underline; } <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a class=\"cancel-action\">Cancel this action</a> href a tab tab tabindex button href a a:hover a.hover a href event.preventDefault()"
},
{
"answer_id": 9717217,
"author": "Timo Huovinen",
"author_id": 175071,
"author_profile": "https://Stackoverflow.com/users/175071",
"pm_score": 2,
"selected": false,
"text": "<a href=\"#void\" onclick=\"myJsFunc()\">Run JavaScript function</a>\n"
},
{
"answer_id": 9730961,
"author": "dazbradbury",
"author_id": 892397,
"author_profile": "https://Stackoverflow.com/users/892397",
"pm_score": 3,
"selected": false,
"text": "# href javascript:void(0) href <a href=\"javascript:void(0)\" onclick=\"someFunc.call(this)\">Link Text</a>\n # href <a href=\"#\" onclick=\"someFunc.call(this)\">Link Text</a>\n\n<script type=\"text/javascript\">\n /* Stop page jumping when javascript links are clicked.\n Only select links where the href value is a #. */\n $('a[href=\"#\"]').live(\"click\", function(e) {\n return false; // prevent default click action from happening!\n e.preventDefault(); // same thing as above\n });\n</script>\n click $('a[href=\"#\"]').click(function(e) {"
},
{
"answer_id": 11196124,
"author": "Stacks on Stacks on Stacks",
"author_id": 800471,
"author_profile": "https://Stackoverflow.com/users/800471",
"pm_score": 4,
"selected": false,
"text": "$(function(){\n $('.no-link').click(function(e){\n e.preventDefault();\n });\n});\n <a href=\"/\" class=\"no-link\">Faux-Link</a>\n <a href=\"javascript:void(0)\" class=\"no-link\">Faux-Link</a>\n"
},
{
"answer_id": 12077178,
"author": "vol7ron",
"author_id": 183181,
"author_profile": "https://Stackoverflow.com/users/183181",
"pm_score": 3,
"selected": false,
"text": "<a href=\"#\" onclick=\"run_foo()\"> foo </a>\n $(document).ready(function(){ // on DOM ready or some other event\n\n $('a[href=#]').attr('href',''); // set all reference handles to blank strings\n // for anchors that have only hashes\n\n});\n"
},
{
"answer_id": 14774496,
"author": "G. Ghez",
"author_id": 67276,
"author_profile": "https://Stackoverflow.com/users/67276",
"pm_score": 3,
"selected": false,
"text": "onclick=\"something();\" $('#myAnchor').click(function(){... **return false**;}); $('#myAnchor').bind('click', function(){... **return false**;}); href=\"javascript:void(0);\" href=\"#\""
},
{
"answer_id": 17869905,
"author": "whirlwin",
"author_id": 490315,
"author_profile": "https://Stackoverflow.com/users/490315",
"pm_score": 4,
"selected": false,
"text": "<a href=\"\">Do some fancy JavaScript</a>\n false"
},
{
"answer_id": 21744656,
"author": "Ashish Kumar",
"author_id": 1562258,
"author_profile": "https://Stackoverflow.com/users/1562258",
"pm_score": 5,
"selected": false,
"text": "<a /> href=\"#\" <a href=\"#\" onclick=\"myJsFunc(); return false;\">Run JavaScript Code</a>\n <a href=\"javascript://\" onclick=\"myJsFunc();\">Run JavaScript Code</a>\n <a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Run JavaScript Code</a>\n <a> <button /> <a href=\"#\"> a href=\"#\" cursor:pointer; event.preventDefault() <a> <a>"
},
{
"answer_id": 22252785,
"author": "Vinny Fonseca",
"author_id": 1145945,
"author_profile": "https://Stackoverflow.com/users/1145945",
"pm_score": 3,
"selected": false,
"text": "$(document).ready(function() {\n $(\"a[href='#']\").click(function(event) {\n event.preventDefault();\n });\n});\n"
},
{
"answer_id": 22530755,
"author": "Anders M.",
"author_id": 1617103,
"author_profile": "https://Stackoverflow.com/users/1617103",
"pm_score": 3,
"selected": false,
"text": "Javascript:void(0) #"
},
{
"answer_id": 23315028,
"author": "Milan and Friends",
"author_id": 2666313,
"author_profile": "https://Stackoverflow.com/users/2666313",
"pm_score": 4,
"selected": false,
"text": "<a href=\"#\">Link</a>\n $('a[href=\"#\"]').attr('href','javascript:void(0);');\n $('a[href=\"#\"]').click(function(e) {\n e.preventDefault();\n});\n on <span> class <span class=\"link\">Link</span>\n .link </body> <script>\n (function($) {\n $('.link').click(function() {\n // do something\n });\n })(jQuery);\n</script>\n $('.link').on('click', function() {\n // do something\n});\n $(document).on('click','.link', function() {\n // do something\n});\n .link {\n color: #0000ee;\n text-decoration: underline;\n cursor: pointer;\n}\n.link:active {\n color: red;\n}\n"
},
{
"answer_id": 26998181,
"author": "AlxGol",
"author_id": 3010765,
"author_profile": "https://Stackoverflow.com/users/3010765",
"pm_score": 3,
"selected": false,
"text": "<span role=\"button\" onclick=\"myJsFunc();\">Run JavaScript Code</span>\n"
},
{
"answer_id": 31977848,
"author": "dnetix",
"author_id": 3295095,
"author_profile": "https://Stackoverflow.com/users/3295095",
"pm_score": 5,
"selected": false,
"text": "<a href=\"javascript:;\" onclick=\"yourFunction()\">Link description</a>\n"
},
{
"answer_id": 35022676,
"author": "Garrett",
"author_id": 261439,
"author_profile": "https://Stackoverflow.com/users/261439",
"pm_score": 5,
"selected": false,
"text": "<span onclick=\"myJsFunc()\" class=\"funcActuator\">myJsFunc</span>\n .funcActuator { \n cursor: default;\n}\n\n.funcActuator:hover { \n color: #900;\n}\n"
},
{
"answer_id": 40322672,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "id=\"#\" javascript:void(0) javascript:void(0)"
},
{
"answer_id": 46573009,
"author": "Charlie",
"author_id": 145976,
"author_profile": "https://Stackoverflow.com/users/145976",
"pm_score": -1,
"selected": false,
"text": "href a # javascript:void(0); AJAX Error: error GET javascript:void(0);"
},
{
"answer_id": 54009205,
"author": "L Y E S - C H I O U K H",
"author_id": 9317830,
"author_profile": "https://Stackoverflow.com/users/9317830",
"pm_score": 3,
"selected": false,
"text": "<a>previous</a>\n <a> <span> :hover javascript:void(0) javascript:undefined javascript:;"
},
{
"answer_id": 56131904,
"author": "SchoolforDesign",
"author_id": 3527054,
"author_profile": "https://Stackoverflow.com/users/3527054",
"pm_score": 2,
"selected": false,
"text": "Javascript: void(0); NULL '#'"
},
{
"answer_id": 56353294,
"author": "Javed Khan",
"author_id": 9704900,
"author_profile": "https://Stackoverflow.com/users/9704900",
"pm_score": 2,
"selected": false,
"text": "function helloFunction() {\n alert(\"hello world\");\n}\n<a href=\"javascript:void(0)\" onclick=\"helloFunction();\">Call Hello Function</a>\n"
},
{
"answer_id": 56597389,
"author": "Dev pokhariya",
"author_id": 7179457,
"author_profile": "https://Stackoverflow.com/users/7179457",
"pm_score": 3,
"selected": false,
"text": "<a href=\"javascript:void(0)\" onclick=\"testFunction();\">Click To check Function</a>\n\nfunction testFunction() {\n alert(\"hello world\");\n}\n"
},
{
"answer_id": 66427870,
"author": "Stokely",
"author_id": 5555938,
"author_profile": "https://Stackoverflow.com/users/5555938",
"pm_score": 2,
"selected": false,
"text": "return false; href href href href <a href=\"\" onclick=\"alert('hello world!');return false;\">My Link</a>\n<a href=\"#\" onclick=\"alert('hello world!');return false;\">My Link</a>\n<a href=\"MyFallbackURL.html\" onclick=\"alert('hello world!');return false;\">My Link</a>\n javascript:void(0) href href <a href=\"javascript:void(0);\" onclick=\"alert('hello world!');\">My Link</a>\n"
},
{
"answer_id": 68150105,
"author": "Nedim AKAR",
"author_id": 11943388,
"author_profile": "https://Stackoverflow.com/users/11943388",
"pm_score": 1,
"selected": false,
"text": "javascript:void(0) #"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8018/"
] |
134,858
|
<p>I have some code I've written in PHP for consuming our simple webservice, which I'd also like to provide in Perl for users who may prefer that language. What's the simplest method of making a HTTP request to do that? In PHP I can do it in one line with <code>file_get_contents()</code>.</p>
<p>Here's the entire code I want to port to Perl:</p>
<pre class="lang-php prettyprint-override"><code>/**
* Makes a remote call to the our API, and returns the response
* @param cmd {string} - command string ID
* @param argsArray {array} - associative array of argument names and argument values
* @return {array} - array of responses
*/
function callAPI( $cmd, $argsArray=array() )
{
$apikey="MY_API_KEY";
$secret="MY_SECRET";
$apiurl="https://foobar.com/api";
// timestamp this API was submitted (for security reasons)
$epoch_time=time();
//--- assemble argument array into string
$query = "cmd=" .$cmd;
foreach ($argsArray as $argName => $argValue) {
$query .= "&" . $argName . "=" . urlencode($argValue);
}
$query .= "&key=". $apikey . "&time=" . $epoch_time;
//--- make md5 hash of the query + secret string
$md5 = md5($query . $secret);
$url = $apiurl . "?" . $query . "&md5=" . $md5;
//--- make simple HTTP GET request, put the server response into $response
$response = file_get_contents($url);
//--- convert "|" (pipe) delimited string to array
$responseArray = explode("|", $response);
return $responseArray;
}
</code></pre>
|
[
{
"answer_id": 134889,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 7,
"selected": true,
"text": "use LWP::Simple;\n$contents = get(\"http://YOUR_URL_HERE\");\n"
},
{
"answer_id": 134911,
"author": "Barry Brown",
"author_id": 17312,
"author_profile": "https://Stackoverflow.com/users/17312",
"pm_score": 4,
"selected": false,
"text": "use LWP::Simple;\n$content = get($url);\ndie \"Can't GET $url\" if (! defined $content);\n"
},
{
"answer_id": 18908775,
"author": "Dave Horner",
"author_id": 1937339,
"author_profile": "https://Stackoverflow.com/users/1937339",
"pm_score": 2,
"selected": false,
"text": " use Mojo::UserAgent;\n my $ua = Mojo::UserAgent->new;\n\n # Say hello to the Unicode snowman with \"Do Not Track\" header\n say $ua->get('www.☃.net?hello=there' => {DNT => 1})->res->body;\n\n # Form POST with exception handling\n my $tx = $ua->post('https://metacpan.org/search' => form => {q => 'mojo'});\n if (my $res = $tx->success) { say $res->body }\n else {\n my ($err, $code) = $tx->error;\n say $code ? \"$code response: $err\" : \"Connection error: $err\";\n }\n\n # Quick JSON API request with Basic authentication\n say $ua->get('https://sri:s3cret@example.com/search.json?q=perl')\n ->res->json('/results/0/title');\n\n # Extract data from HTML and XML resources\n say $ua->get('www.perl.org')->res->dom->html->head->title->text;`\n"
},
{
"answer_id": 29163199,
"author": "Srihari Karanth",
"author_id": 1447507,
"author_profile": "https://Stackoverflow.com/users/1447507",
"pm_score": 1,
"selected": false,
"text": "my $content = `GET \"http://trackMyPhones.com/\"`;\n"
},
{
"answer_id": 35093522,
"author": "tboz203",
"author_id": 1445042,
"author_profile": "https://Stackoverflow.com/users/1445042",
"pm_score": 1,
"selected": false,
"text": "$ my $content = `curl -s \"http://google.com\"`;\n<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n<TITLE>301 Moved</TITLE></HEAD><BODY>\n<H1>301 Moved</H1>\nThe document has moved\n<A HREF=\"http://www.google.com/\">here</A>.\n</BODY></HTML>\n -s"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] |
134,866
|
<p>I have a mindmp file from a target's application crash. Is it possible for me to rebuild the dll/pdb files for a version of software and have windbg load symbols correctly? </p>
<p>My problem is that our pdb files are only kept for major releases (unfortunately). This is a daily build, which I can rebuild myself, but I'm getting tripped up on errors.</p>
<p>With !sym noisy on:
"image header does not match memory image header."</p>
<pre><code>DBGENG: C:\...\XXX.dll image header does not match memory image header.
DBGENG: XXX.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
DBGHELP: C:\...\XXX.pdb - mismatched pdb
</code></pre>
<p>Note I've build the pdb with the dll, they are from the same RELEASE directory (should I be building debug?)</p>
<p>Theses are release builds (as release builds are installed on the target and crashing) should I be somehow using the debug build dlls to get more symbol information?</p>
|
[
{
"answer_id": 160818,
"author": "SteveMan",
"author_id": 5994,
"author_profile": "https://Stackoverflow.com/users/5994",
"pm_score": 4,
"selected": false,
"text": "chkmatch -m OriginalExecutable.exe RebuiltPDB.pdb\n"
},
{
"answer_id": 21099781,
"author": "Dan K",
"author_id": 328285,
"author_profile": "https://Stackoverflow.com/users/328285",
"pm_score": 0,
"selected": false,
"text": ".symopt_0x40\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
] |
134,882
|
<p>How do I easily undo a git rebase? A lengthy manual method is:</p>
<ol>
<li>checkout the commit parent to both of the branches</li>
<li>create and checkout a temporary branch</li>
<li>cherry-pick all commits by hand</li>
<li>reset the faulty rebased branch to point to the temporary branch</li>
</ol>
<p>In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).</p>
<p>Clarification: I am talking about a rebase during which <em>multiple</em> commits were replayed, not only one.</p>
|
[
{
"answer_id": 135614,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 13,
"selected": true,
"text": "git reflog\n --hard HEAD@{2} git reset --hard HEAD@{2}\n git reset --hard \"HEAD@{2}\"\n git log HEAD@{2} git log \"HEAD@{2}\" git reflog branchname@{1} [core]\n logAllRefUpdates = true\n"
},
{
"answer_id": 137363,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 7,
"selected": false,
"text": "--onto topic master master 0deadbeef topic git rebase master git rebase --onto 0deadbeef master topic\n topic master 0deadbeef --onto"
},
{
"answer_id": 692763,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 11,
"selected": false,
"text": "ORIG_HEAD git reset --hard ORIG_HEAD\n reset rebase merge HEAD ORIG_HEAD"
},
{
"answer_id": 854840,
"author": "Alex Gontmakher",
"author_id": 98510,
"author_profile": "https://Stackoverflow.com/users/98510",
"pm_score": 6,
"selected": false,
"text": "git reset --hard BACKUP"
},
{
"answer_id": 1189779,
"author": "Allan",
"author_id": 139035,
"author_profile": "https://Stackoverflow.com/users/139035",
"pm_score": 9,
"selected": false,
"text": "git rebase --abort\n reset Interactive rebase already started"
},
{
"answer_id": 9362339,
"author": "Kris",
"author_id": 22237,
"author_profile": "https://Stackoverflow.com/users/22237",
"pm_score": 5,
"selected": false,
"text": "reflog 5fce6b51 88552c8f Kris Leech <me@example.com> 1329744625 +0000 rebase finished: refs/heads/integrate onto 9e460878\n git checkout 88552c8f\n git log\ngit checkout -b lost_changes\n"
},
{
"answer_id": 28997687,
"author": "Matheus Felipe",
"author_id": 2044035,
"author_profile": "https://Stackoverflow.com/users/2044035",
"pm_score": 4,
"selected": false,
"text": "git rebase -i --abort git rebase --abort -i --abort matbhz@myPc /my/project/environment (branch-123|REBASE-i)\n$ git rebase --abort\n\nmatbhz@myPc /my/project/environment (branch-123)\n$\n"
},
{
"answer_id": 32823323,
"author": "Maksym",
"author_id": 3502543,
"author_profile": "https://Stackoverflow.com/users/3502543",
"pm_score": 7,
"selected": false,
"text": "git rebase --abort $ ~/work/projects/{ProjectName} $ git status\nOn branch {branchName}\nYour branch is ahead of 'origin/{branchName}' by 135 commits.\n (use \"git push\" to publish your local commits)\n\nnothing to commit, working directory clean\n\n$ ~/work/projects/{ProjectName} $ git reset --hard origin/{branchName}\nHEAD is now at 6df5719 \"Commit message\".\n\n$ ~/work/projects/{ProjectName} $ git status\nOn branch {branchName}\nYour branch is up-to-date with 'origin/{branchName}.\n\nnothing to commit, working directory clean\n"
},
{
"answer_id": 35887419,
"author": "stevek-pro",
"author_id": 356759,
"author_profile": "https://Stackoverflow.com/users/356759",
"pm_score": -1,
"selected": false,
"text": "git rebase --abort git reflog right-click->local history"
},
{
"answer_id": 37987428,
"author": "Sergey P. aka azure",
"author_id": 1075459,
"author_profile": "https://Stackoverflow.com/users/1075459",
"pm_score": 4,
"selected": false,
"text": "git rebase --abort your-branch origin/your-branch git branch -m your-branch-rebased git checkout origin/your-branch git checkout -b your-branch git log your-branch-rebased git log your-branch your-branch git cherry-pick COMMIT_HASH your-branch-rebased remote/your-branch your-branch"
},
{
"answer_id": 42136684,
"author": "Hardev",
"author_id": 1299948,
"author_profile": "https://Stackoverflow.com/users/1299948",
"pm_score": 2,
"selected": false,
"text": "git rebase -i HEAD~31\n"
},
{
"answer_id": 54128623,
"author": "devconsole",
"author_id": 773189,
"author_profile": "https://Stackoverflow.com/users/773189",
"pm_score": 2,
"selected": false,
"text": "git reset --hard @{1}\n git reflog git reflog <branch> master git reflog master master@{1} master@{2} git rebase @{1} master@{1} master git reset --hard ORIG_HEAD git reset rebase"
},
{
"answer_id": 56001129,
"author": "Damodar P",
"author_id": 11008980,
"author_profile": "https://Stackoverflow.com/users/11008980",
"pm_score": 6,
"selected": false,
"text": "git reset --hard origin/{branchName}\n"
},
{
"answer_id": 56366149,
"author": "Andrew",
"author_id": 3093731,
"author_profile": "https://Stackoverflow.com/users/3093731",
"pm_score": 4,
"selected": false,
"text": "git reflog\n git checkout HEAD@{57}\n git checkout -b new_branch_name\n"
},
{
"answer_id": 56670315,
"author": "mrigendra",
"author_id": 2270386,
"author_profile": "https://Stackoverflow.com/users/2270386",
"pm_score": 2,
"selected": false,
"text": "git reset #commit_hash git pull"
},
{
"answer_id": 62986490,
"author": "DylanYoung",
"author_id": 3124256,
"author_profile": "https://Stackoverflow.com/users/3124256",
"pm_score": 2,
"selected": false,
"text": "# Useful commands\n#################\n\n# Undo the last rebase\nundo-rebase = \"! f() { : git reset ; PREV_COMMIT=`git x-rev-before-rebase` && git reset --merge \\\"$PREV_COMMIT\\\" \\\"$@\\\";}; f\"\n\n# See what changed since the last rebase\nrdiff = \"!f() { : git diff ; git diff `git x-rev-before-rebase` \"$@\";}; f\"\n\n# Helpers\n########\n# Get the revision before the last rebase started\nx-rev-before-rebase = !git reflog --skip=1 -1 \\\"`git x-start-of-rebase`\\\" --format=\\\"%gD\\\"\n\n# Get the revision that started the rebase\nx-start-of-rebase = reflog --grep-reflog '^rebase (start)' -1 --format=\"%gD\"\n --grep-reflog \"^rebase (start): checkout \" \n :"
},
{
"answer_id": 68217712,
"author": "GuyStalks",
"author_id": 4966536,
"author_profile": "https://Stackoverflow.com/users/4966536",
"pm_score": 3,
"selected": false,
"text": "git reflog\n git log -g e86a52b851e git branch recover-branch e86a52b851e\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349/"
] |
134,885
|
<p>I'm looking to use a VBScript variable within a reference to a DOM element for a web-app I'm building. Here's a brief excerpt of the affected area of code:</p>
<pre><code>dim num
num = CInt(document.myform.i.value)
dim x
x = 0
dim orders(num)
For x = 0 To num
orders(x) = document.getElementById("order" & x).value
objFile.writeLine(orders(x))
Next
</code></pre>
<p>This is my first venture into VBScript, and I've not been able to find any methods of performing this type of action online. As you can see in the above code, I'm trying to create an array (orders). This array can have any number of values, but that number will be specified in <code>document.myform.i.value</code>. So the For loop cycles through all text inputs with an ID of order+x (ie, order0, order1, order2, order3, order4, etc. up to num)</p>
<p>It seems to be a problem with my orders(x) line, I don't think it recognizes what I mean by <code>getElementById("order" & x)</code>, and I'm not sure exactly how to do such a thing. Anyone have any suggestions? It would be much appreciated!</p>
|
[
{
"answer_id": 134927,
"author": "Dan Williams",
"author_id": 4230,
"author_profile": "https://Stackoverflow.com/users/4230",
"pm_score": 0,
"selected": false,
"text": "orders(x) = document.getElementById(\"order\" & x).value\nobjFile.writeLine(orders(x))\n orders(x) = document.getElementById(\"order\" & x)\nobjFile.writeLine(orders(x).value)\n"
},
{
"answer_id": 136030,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "objFile.writeLine(orders(x))\n document.getElementById\n <% = myVariable %>\n document.write myVariable\n"
},
{
"answer_id": 139471,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "document.getElementById(\"order\" & x).value\n temp = \"order\" & x\ndocument.getElementById(temp).value\n"
},
{
"answer_id": 208485,
"author": "Magnus Smith",
"author_id": 11461,
"author_profile": "https://Stackoverflow.com/users/11461",
"pm_score": 0,
"selected": false,
"text": "For x = 0 To num - 1\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
134,887
|
<p>After making it through the major parts of an introductory Lisp book, I still couldn't understand what the special operator <code>(quote)</code> (or equivalent <code>'</code>) function does, yet this has been all over Lisp code that I've seen. </p>
<p>What does it do?</p>
|
[
{
"answer_id": 134908,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 6,
"selected": false,
"text": "(print '(+ 3 4)) (print (+ 3 4))"
},
{
"answer_id": 134924,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 4,
"selected": false,
"text": "(quote a)\n'a\n (quote (1 2 3))\n'(1 2 3)\n"
},
{
"answer_id": 137774,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 9,
"selected": true,
"text": "(* (+ a 2)\n 3)\n (+ a 2) a a a (let ((a 3))\n (* (+ a 2)\n 3))\n (+ 3 2) (* 5 3) quote a quote print(\"'(\")\nwhile allocating:\n if random.random() > 0.5:\n print(f\"(allocate {random.randint(0, 20)})\")\n else:\n print(f\"(free {random.randint(0, 20)})\")\n ...\nprint(\")\")\n '((allocate 3)\n (allocate 7)\n (free 14)\n (allocate 19)\n ...)\n quote allocate free (dolist (entry allocation-log)\n (case (first entry)\n (allocate (plot-allocation (second entry)))\n (free (plot-free (second entry)))))\n (plot-allocation 3)\n(plot-allocation 7)\n(plot-free 14)\n(plot-allocation 19)\n list (defun mess-with (number string)\n '(value-of-number (1+ number) something-with-string (length string)))\n\nLisp> (mess-with 20 \"foo\")\n(VALUE-OF-NUMBER (1+ NUMBER) SOMETHING-WITH-STRING (LENGTH STRING))\n (defun mess-with (number string)\n (list 'value-of-number (1+ number) 'something-with-string (length string)))\n\nLisp> (mess-with 20 \"foo\")\n(VALUE-OF-NUMBER 21 SOMETHING-WITH-STRING 3)\n quote backquote (defun mess-with (number string)\n `(value-of-number ,(1+ number) something-with-string ,(length string)))\n quote list list quote quote quote Lisp> (quote spiffy-symbol)\nSPIFFY-SYMBOL\n\nLisp> 'spiffy-symbol ; ' is just a shorthand (\"reader macro\"), as shown above\nSPIFFY-SYMBOL\n Lisp> spiffy-symbol\ndebugger invoked on a UNBOUND-VARIABLE in thread #<THREAD \"initial thread\" RUNNING {A69F6A9}>:\n The variable SPIFFY-SYMBOL is unbound.\n\nType HELP for debugger help, or (SB-EXT:QUIT) to exit from SBCL.\n\nrestarts (invokable by number or by possibly-abbreviated name):\n 0: [ABORT] Exit debugger, returning to top level.\n\n(SB-INT:SIMPLE-EVAL-IN-LEXENV SPIFFY-SYMBOL #<NULL-LEXENV>)\n0] \n spiffy-symbol quote backquote list struct"
},
{
"answer_id": 24093979,
"author": "unknownerror",
"author_id": 2960555,
"author_profile": "https://Stackoverflow.com/users/2960555",
"pm_score": 2,
"selected": false,
"text": "(define atom? ; defining a procedure atom?\n (lambda (x) ; which as one argument x\n(and (not (null? x)) (not(pair? x) )))) ; checks if the argument is atom or not\n(atom? '(a b c)) ; since it is a list it is false #f\n"
},
{
"answer_id": 35542683,
"author": "Andrew_1510",
"author_id": 451718,
"author_profile": "https://Stackoverflow.com/users/451718",
"pm_score": 1,
"selected": false,
"text": "quote This special form returns object, without evaluating it. \n (quote (+ 1 2))\n ⇒ (+ 1 2)\n\n(quote foo)\n ⇒ foo\n\n'foo\n ⇒ foo\n\n''foo\n ⇒ (quote foo)\n\n'(quote foo)\n ⇒ (quote foo)\n `(a list of (+ 2 3) elements)\n ⇒ (a list of (+ 2 3) elements)\n\n'(a list of (+ 2 3) elements)\n ⇒ (a list of (+ 2 3) elements)\n `(a list of ,(+ 2 3) elements)\n ⇒ (a list of 5 elements)\n `(1 2 (3 ,(+ 4 5)))\n ⇒ (1 2 (3 9))\n (setq some-list '(2 3))\n ⇒ (2 3)\n\n(cons 1 (append some-list '(4) some-list))\n ⇒ (1 2 3 4 2 3)\n\n`(1 ,@some-list 4 ,@some-list)\n ⇒ (1 2 3 4 2 3)\n"
},
{
"answer_id": 35682547,
"author": "jhegedus",
"author_id": 1198559,
"author_profile": "https://Stackoverflow.com/users/1198559",
"pm_score": 2,
"selected": false,
"text": "'5 5 '(one two) (list 'one 'two) (list (intern \"one\") (intern (\"two\"))) (intern \"one\") 'one \"one\" name \"one\" class Symbol:\n def __init__(self,name,code,value):\n self.name=name\n self.code=code\n self.value=value\n (progn\n (fset 'add '+ )\n (set 'add 2)\n (add add add)\n)\n 4 (add add add) (add add add)\n(+ add add)\n(+ 2 add)\n(+ 2 2)\n4\n Symbol add Symbol(\"add\",(lambda x,y: x+y),2)"
},
{
"answer_id": 56653324,
"author": "alinsoar",
"author_id": 1419272,
"author_profile": "https://Stackoverflow.com/users/1419272",
"pm_score": 2,
"selected": false,
"text": "Code is data and data is code. There is no clear distinction between them.\n 1 ]=> '(+ 2 3 4)\n;Value: (+ 2 3 4)\n\n1 ]=> (+ 2 3 4)\n;Value: 9\n 1 ]=> 'code\n;Value: code\n\n1 ]=> '10\n;Value: 10\n\n1 ]=> '\"ok\"\n;Value: \"ok\"\n\n1 ]=> code\n;Unbound variable: code\n '(+ 2 3)"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256/"
] |
134,905
|
<p>What is the best way to return XML from a controller's action in ASP.NET MVC? There is a nice way to return JSON, but not for XML. Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it?</p>
|
[
{
"answer_id": 134982,
"author": "Luke Smith",
"author_id": 5556,
"author_profile": "https://Stackoverflow.com/users/5556",
"pm_score": 8,
"selected": true,
"text": "public class XmlResult : ActionResult\n{\n private object objectToSerialize;\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"XmlResult\"/> class.\n /// </summary>\n /// <param name=\"objectToSerialize\">The object to serialize to XML.</param>\n public XmlResult(object objectToSerialize)\n {\n this.objectToSerialize = objectToSerialize;\n }\n\n /// <summary>\n /// Gets the object to be serialized to XML.\n /// </summary>\n public object ObjectToSerialize\n {\n get { return this.objectToSerialize; }\n }\n\n /// <summary>\n /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.\n /// </summary>\n /// <param name=\"context\">The controller context for the current request.</param>\n public override void ExecuteResult(ControllerContext context)\n {\n if (this.objectToSerialize != null)\n {\n context.HttpContext.Response.Clear();\n var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());\n context.HttpContext.Response.ContentType = \"text/xml\";\n xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);\n }\n }\n}\n"
},
{
"answer_id": 1578296,
"author": "Erik",
"author_id": 191231,
"author_profile": "https://Stackoverflow.com/users/191231",
"pm_score": 5,
"selected": false,
"text": "public string Xml()\n{\n Response.ContentType = \"text/xml\";\n return yourXmlChunk;\n}\n"
},
{
"answer_id": 4325941,
"author": "Petr",
"author_id": 526770,
"author_profile": "https://Stackoverflow.com/users/526770",
"pm_score": 7,
"selected": false,
"text": "return this.Content(xmlString, \"text/xml\");\n"
},
{
"answer_id": 12718046,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 5,
"selected": false,
"text": "XDocument public ActionResult MyXmlAction()\n{\n // Create your own XDocument according to your requirements\n var xml = new XDocument(\n new XElement(\"root\",\n new XAttribute(\"version\", \"2.0\"),\n new XElement(\"child\", \"Hello World!\")));\n\n return new XmlActionResult(xml);\n}\n ActionResult public sealed class XmlActionResult : ActionResult\n{\n private readonly XDocument _document;\n\n public Formatting Formatting { get; set; }\n public string MimeType { get; set; }\n\n public XmlActionResult(XDocument document)\n {\n if (document == null)\n throw new ArgumentNullException(\"document\");\n\n _document = document;\n\n // Default values\n MimeType = \"text/xml\";\n Formatting = Formatting.None;\n }\n\n public override void ExecuteResult(ControllerContext context)\n {\n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ContentType = MimeType;\n\n using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, Encoding.UTF8) { Formatting = Formatting })\n _document.WriteTo(writer);\n }\n}\n application/rss+xml"
},
{
"answer_id": 19036811,
"author": "sheir",
"author_id": 245884,
"author_profile": "https://Stackoverflow.com/users/245884",
"pm_score": 2,
"selected": false,
"text": "<div id=\"docxOutput\">\n<iframe id=\"ifOffice\" name=\"ifOffice\" width=\"0\" height=\"0\"\n hidden=\"hidden\" seamless='seamless' frameBorder=\"0\" scrolling=\"no\"></iframe></div>\n //url to call in the controller to get MS-Excel xml\nvar _lnkToControllerExcel = '@Url.Action(\"ExportToExcel\", \"Home\")';\n$(\"#btExportToExcel\").on(\"click\", function (event) {\n event.preventDefault();\n\n $(\"#ProgressDialog\").show();//like an ajax loader gif\n\n //grab the basket as xml \n var keys = GetMyKeys();//returns delimited list of keys (for selected items from UI) \n\n //potential problem - the querystring might be too long??\n //2K in IE8\n //4096 characters in ASP.Net\n //parameter key names must match signature of Controller method\n var qsParams = [\n 'keys=' + keys,\n 'locale=' + '@locale' \n ].join('&');\n\n //The element with id=\"ifOffice\"\n var officeFrame = $(\"#ifOffice\")[0];\n\n //construct the url for the iframe\n var srcUrl = _lnkToControllerExcel + '?' + qsParams;\n\n try {\n if (officeFrame != null) {\n //Controller method can take up to 4 seconds to return\n officeFrame.setAttribute(\"src\", srcUrl);\n }\n else {\n alert('ExportToExcel - failed to get reference to the office iframe!');\n }\n } catch (ex) {\n var errMsg = \"ExportToExcel Button Click Handler Error: \";\n HandleException(ex, errMsg);\n }\n finally {\n //Need a small 3 second ( delay for the generated MS-Excel XML to come down from server)\n setTimeout(function () {\n //after the timeout then hide the loader graphic\n $(\"#ProgressDialog\").hide();\n }, 3000);\n\n //clean up\n officeFrame = null;\n srcUrl = null;\n qsParams = null;\n keys = null;\n }\n});\n public override void ExecuteResult(ControllerContext context)\n{\n string lastModDate = DateTime.Now.ToString(\"R\");\n\n //Content-Disposition: attachment; filename=\"<file name.xml>\" \n // must set the Content-Disposition so that the web browser will pop the open/save dialog\n string disposition = \"attachment; \" +\n \"filename=\\\"\" + this.DownloadFilename + \"\\\"; \";\n\n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ClearContent();\n context.HttpContext.Response.ClearHeaders();\n context.HttpContext.Response.Cookies.Clear();\n context.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);// Stop Caching in IE\n context.HttpContext.Response.Cache.SetNoStore();// Stop Caching in Firefox\n context.HttpContext.Response.Cache.SetMaxAge(TimeSpan.Zero);\n context.HttpContext.Response.CacheControl = \"private\";\n context.HttpContext.Response.Cache.SetLastModified(DateTime.Now.ToUniversalTime());\n context.HttpContext.Response.ContentType = this.MimeType;\n context.HttpContext.Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;\n\n //context.HttpContext.Response.Headers.Add(\"name\", \"value\");\n context.HttpContext.Response.Headers.Add(\"Last-Modified\", lastModDate);\n context.HttpContext.Response.Headers.Add(\"Pragma\", \"no-cache\"); // HTTP 1.0.\n context.HttpContext.Response.Headers.Add(\"Expires\", \"0\"); // Proxies.\n\n context.HttpContext.Response.AppendHeader(\"Content-Disposition\", disposition);\n\n using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, this.Encoding)\n { Formatting = this.Formatting })\n this.Document.WriteTo(writer);\n}\n"
},
{
"answer_id": 21687683,
"author": "Casey",
"author_id": 2056448,
"author_profile": "https://Stackoverflow.com/users/2056448",
"pm_score": 1,
"selected": false,
"text": "return File(stream, \"text/xml\");"
},
{
"answer_id": 22024105,
"author": "user2670714",
"author_id": 2670714,
"author_profile": "https://Stackoverflow.com/users/2670714",
"pm_score": 0,
"selected": false,
"text": " var xml = new XDocument(\n new XElement(\"root\",\n new XAttribute(\"version\", \"2.0\"),\n new XElement(\"child\", \"Hello World!\")));\n MemoryStream ms = new MemoryStream();\n xml.Save(ms);\n return File(new MemoryStream(ms.ToArray()), \"text/xml\", \"HelloWorld.xml\");\n"
},
{
"answer_id": 38594073,
"author": "Matthew Price",
"author_id": 6640631,
"author_profile": "https://Stackoverflow.com/users/6640631",
"pm_score": 3,
"selected": false,
"text": "public virtual ActionResult ReturnXml()\n{\n return File(Encoding.UTF8.GetBytes(GenerateXmlFeed().OuterXml), \"text/xml\");\n}\n"
},
{
"answer_id": 38855421,
"author": "Nelson Lopez Centeno",
"author_id": 4473736,
"author_profile": "https://Stackoverflow.com/users/4473736",
"pm_score": 0,
"selected": false,
"text": "public sealed class XmlActionResult : ActionResult\n{\n private readonly XDocument _document;\n public string MimeType { get; set; }\n\n public XmlActionResult(XDocument document)\n {\n if (document == null)\n throw new ArgumentNullException(\"document\");\n\n _document = document;\n\n // Default values\n MimeType = \"text/xml\";\n }\n\n public override void ExecuteResult(ControllerContext context)\n {\n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ContentType = MimeType;\n _document.Save(context.HttpContext.Response.OutputStream)\n }\n}\n"
},
{
"answer_id": 65161290,
"author": "Hamid Jolany",
"author_id": 555078,
"author_profile": "https://Stackoverflow.com/users/555078",
"pm_score": 2,
"selected": false,
"text": " public ContentResult GetXml()\n {\n string xmlString = \"your xml data\";\n return Content(xmlString, \"text/xml\");\n }\n public string GetXml()\n {\n string xmlString = \"your xml data\";\n Response.ContentType = \"text/xml\";\n return xmlString;\n }\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22299/"
] |
134,906
|
<p>Is there a command or an existing script that will let me view all of a *NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as <code>/etc/crontab</code>, and whatever's in <code>/etc/cron.d</code>. It would also be nice to see the specific commands run by <code>run-parts</code> in <code>/etc/crontab</code>.</p>
<p>Ideally, I'd like the output in a nice column form and ordered in some meaningful way.</p>
<p>I could then merge these listings from multiple servers to view the overall "schedule of events."</p>
<p>I was about to write such a script myself, but if someone's already gone to the trouble...</p>
|
[
{
"answer_id": 134944,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 10,
"selected": false,
"text": "for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done\n echo $user for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done\n"
},
{
"answer_id": 134947,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 3,
"selected": false,
"text": "(cd /var/cron/tabs && grep -vH ^# *) \n (cd /var/cron/tabs && grep -vH ^# * | sed \"s/:/ /\")\n /etc/passwd crontab -l -u $user"
},
{
"answer_id": 137173,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 9,
"selected": true,
"text": "/etc/crontab run-parts /etc/cron.hourly /etc/cron.daily /etc/cron.d mi h d m w user command\n09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm\n47 */8 * * * root rsync -axE --delete --ignore-errors / /mirror/ >/dev/null\n17 1 * * * root /etc/cron.daily/apt\n17 1 * * * root /etc/cron.daily/aptitude\n17 1 * * * root /etc/cron.daily/find\n17 1 * * * root /etc/cron.daily/logrotate\n17 1 * * * root /etc/cron.daily/man-db\n17 1 * * * root /etc/cron.daily/ntp\n17 1 * * * root /etc/cron.daily/standard\n17 1 * * * root /etc/cron.daily/sysklogd\n27 2 * * 7 root /etc/cron.weekly/man-db\n27 2 * * 7 root /etc/cron.weekly/sysklogd\n13 3 * * * archiver /usr/local/bin/offsite-backup 2>&1\n32 3 1 * * root /etc/cron.monthly/standard\n36 4 * * * yukon /home/yukon/bin/do-daily-stuff\n5 5 * * * archiver /usr/local/bin/update-logs >/dev/null\n #!/bin/bash\n\n# System-wide crontab file and cron job directory. Change these for your system.\nCRONTAB='/etc/crontab'\nCRONDIR='/etc/cron.d'\n\n# Single tab character. Annoyingly necessary.\ntab=$(echo -en \"\\t\")\n\n# Given a stream of crontab lines, exclude non-cron job lines, replace\n# whitespace characters with a single space, and remove any spaces from the\n# beginning of each line.\nfunction clean_cron_lines() {\n while read line ; do\n echo \"${line}\" |\n egrep --invert-match '^($|\\s*#|\\s*[[:alnum:]_]+=)' |\n sed --regexp-extended \"s/\\s+/ /g\" |\n sed --regexp-extended \"s/^ //\"\n done;\n}\n\n# Given a stream of cleaned crontab lines, echo any that don't include the\n# run-parts command, and for those that do, show each job file in the run-parts\n# directory as if it were scheduled explicitly.\nfunction lookup_run_parts() {\n while read line ; do\n match=$(echo \"${line}\" | egrep -o 'run-parts (-{1,2}\\S+ )*\\S+')\n\n if [[ -z \"${match}\" ]] ; then\n echo \"${line}\"\n else\n cron_fields=$(echo \"${line}\" | cut -f1-6 -d' ')\n cron_job_dir=$(echo \"${match}\" | awk '{print $NF}')\n\n if [[ -d \"${cron_job_dir}\" ]] ; then\n for cron_job_file in \"${cron_job_dir}\"/* ; do # */ <not a comment>\n [[ -f \"${cron_job_file}\" ]] && echo \"${cron_fields} ${cron_job_file}\"\n done\n fi\n fi\n done;\n}\n\n# Temporary file for crontab lines.\ntemp=$(mktemp) || exit 1\n\n# Add all of the jobs from the system-wide crontab file.\ncat \"${CRONTAB}\" | clean_cron_lines | lookup_run_parts >\"${temp}\" \n\n# Add all of the jobs from the system-wide cron directory.\ncat \"${CRONDIR}\"/* | clean_cron_lines >>\"${temp}\" # */ <not a comment>\n\n# Add each user's crontab (if it exists). Insert the user's name between the\n# five time fields and the command.\nwhile read user ; do\n crontab -l -u \"${user}\" 2>/dev/null |\n clean_cron_lines |\n sed --regexp-extended \"s/^((\\S+ +){5})(.+)$/\\1${user} \\3/\" >>\"${temp}\"\ndone < <(cut --fields=1 --delimiter=: /etc/passwd)\n\n# Output the collected crontab lines. Replace the single spaces between the\n# fields with tab characters, sort the lines by hour and minute, insert the\n# header line, and format the results as a table.\ncat \"${temp}\" |\n sed --regexp-extended \"s/^(\\S+) +(\\S+) +(\\S+) +(\\S+) +(\\S+) +(\\S+) +(.*)$/\\1\\t\\2\\t\\3\\t\\4\\t\\5\\t\\6\\t\\7/\" |\n sort --numeric-sort --field-separator=\"${tab}\" --key=2,1 |\n sed \"1i\\mi\\th\\td\\tm\\tw\\tuser\\tcommand\" |\n column -s\"${tab}\" -t\n\nrm --force \"${temp}\"\n"
},
{
"answer_id": 361851,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "/var/spool/cron/crontabs/ /var/spool/cron/"
},
{
"answer_id": 1243501,
"author": "jbbarth",
"author_id": 278757,
"author_profile": "https://Stackoverflow.com/users/278757",
"pm_score": 3,
"selected": false,
"text": "2a3,4\n> #See: http://stackoverflow.com/questions/134906/how-do-i-list-all-cron-jobs-for-all-users\n>\n27c29,30\n< match=$(echo \"${line}\" | egrep -o 'run-parts (-{1,2}\\S+ )*\\S+')\n---\n> #match=$(echo \"${line}\" | egrep -o 'run-parts (-{1,2}\\S+ )*\\S+')\n> match=$(echo \"${line}\" | egrep -o 'run-parts.*')\n51c54,57\n< cat \"${CRONDIR}\"/* | clean_cron_lines >>\"${temp}\" # */ <not a comment>\n---\n> sys_cron_num=$(ls /etc/cron.d | wc -l | awk '{print $1}')\n> if [ \"$sys_cron_num\" != 0 ]; then\n> cat \"${CRONDIR}\"/* | clean_cron_lines >>\"${temp}\" # */ <not a comment>\n> fi\n67c73\n< sed \"1i\\mi\\th\\td\\tm\\tw\\tuser\\tcommand\" |\n---\n> sed \"1i\\mi${tab}h${tab}d${tab}m${tab}w${tab}user${tab}command\" |\n"
},
{
"answer_id": 2759975,
"author": "squarism",
"author_id": 88406,
"author_profile": "https://Stackoverflow.com/users/88406",
"pm_score": 3,
"selected": false,
"text": "for user in $(cut -f1 -d: /etc/passwd); do echo User:$user; crontab -l $user 2>&1 | grep -v crontab; done\n"
},
{
"answer_id": 2862180,
"author": "Mithaldu",
"author_id": 145119,
"author_profile": "https://Stackoverflow.com/users/145119",
"pm_score": 4,
"selected": false,
"text": "getent passwd | cut -d: -f1 | perl -e'while(<>){chomp;$l = `crontab -u $_ -l 2>/dev/null`;print \"$_\\n$l\\n\" if $l}'\n"
},
{
"answer_id": 3185772,
"author": "sum",
"author_id": 384480,
"author_profile": "https://Stackoverflow.com/users/384480",
"pm_score": 4,
"selected": false,
"text": "#!/bin/bash\nfor user in $(cut -f1 -d: /etc/passwd)\ndo echo $user && crontab -u $user -l\necho \" \"\ndone\n"
},
{
"answer_id": 7160866,
"author": "Doris",
"author_id": 907686,
"author_profile": "https://Stackoverflow.com/users/907686",
"pm_score": 4,
"selected": false,
"text": "grep -v \"#\" -R /var/spool/cron/tabs\n"
},
{
"answer_id": 11454635,
"author": "indra bhushan kumar",
"author_id": 1521170,
"author_profile": "https://Stackoverflow.com/users/1521170",
"pm_score": 3,
"selected": false,
"text": "for user in $(cut -f1 -d: /etc/passwd); \ndo \n echo $user; crontab -u $user -l; \ndone\n"
},
{
"answer_id": 18028103,
"author": "Jørgen",
"author_id": 638488,
"author_profile": "https://Stackoverflow.com/users/638488",
"pm_score": 5,
"selected": false,
"text": "tail -n 1000 /var/spool/cron/*\n ==> /var/spool/cron/root <==\n15 2 * * * /bla\n\n==> /var/spool/cron/my_user <==\n*/10 1 * * * /path/to/script\n"
},
{
"answer_id": 22665036,
"author": "Ali",
"author_id": 487855,
"author_profile": "https://Stackoverflow.com/users/487855",
"pm_score": 2,
"selected": false,
"text": "for user in $(tail -n +11 /etc/passwd | cut -f1 -d:); do echo $user; crontab -u $user -l; done\n for user in $(dscl . -list /users | cut -f1 -d:); do echo $user; crontab -u $user -l; done \n"
},
{
"answer_id": 27991385,
"author": "Rob Frost",
"author_id": 4462960,
"author_profile": "https://Stackoverflow.com/users/4462960",
"pm_score": -1,
"selected": false,
"text": "for user in $(cut -f1 -d: /etc/passwd); do \n echo $user >> crontab.bak\n echo \"\" >> crontab.bak\n crontab -u $user -l >> crontab.bak 2>> > crontab.bak\ndone\n"
},
{
"answer_id": 31873590,
"author": "idranoels",
"author_id": 5201295,
"author_profile": "https://Stackoverflow.com/users/5201295",
"pm_score": 6,
"selected": false,
"text": "sed 's/^\\([^:]*\\):.*$/crontab -u \\1 -l 2>\\&1/' /etc/passwd | sh | grep -v \"no crontab for\"\n"
},
{
"answer_id": 37328076,
"author": "Monte",
"author_id": 6357058,
"author_profile": "https://Stackoverflow.com/users/6357058",
"pm_score": 2,
"selected": false,
"text": "for I in `lastlog | grep -v Never | cut -f1 -d' '`; do echo $I ; crontab -l -u $I ; done\n"
},
{
"answer_id": 38631252,
"author": "fedorqui",
"author_id": 1983854,
"author_profile": "https://Stackoverflow.com/users/1983854",
"pm_score": 2,
"selected": false,
"text": "/etc/passwd while IFS=\":\" read -r user _\ndo\n echo \"crontab for user ${user}:\"\n crontab -u \"$user\" -l\ndone < /etc/passwd\n /etc/passwd : read -r user _ $user _ crontab -u $user"
},
{
"answer_id": 39385151,
"author": "rkoots",
"author_id": 6771480,
"author_profile": "https://Stackoverflow.com/users/6771480",
"pm_score": 3,
"selected": false,
"text": "sudo crontab -u userName -l\n\n,\n cd /etc/cron.daily/\nls -l\ncat filename\n cd /etc/cron.d/\nls -l\ncat filename\n"
},
{
"answer_id": 41233535,
"author": "Dale C. Anderson",
"author_id": 267455,
"author_profile": "https://Stackoverflow.com/users/267455",
"pm_score": 3,
"selected": false,
"text": "sudo for USER in $(cut -f1 -d: /etc/passwd); do \\\nUSERTAB=\"$(sudo crontab -u \"$USER\" -l 2>&1)\"; \\\nFILTERED=\"$(echo \"$USERTAB\"| grep -vE '^#|^$|no crontab for|cannot use this program')\"; \\\nif ! test -z \"$FILTERED\"; then \\\necho \"# ------ $(tput bold)$USER$(tput sgr0) ------\"; \\\necho \"$FILTERED\"; \\\necho \"\"; \\\nfi; \\\ndone\n # ------ root ------\n0 */6 * * * /usr/local/bin/disk-space-notify.sh\n45 3 * * * /opt/mysql-backups/mysql-backups.sh\n5 7 * * * /usr/local/bin/certbot-auto renew --quiet --no-self-upgrade\n\n# ------ sammy ------\n55 * * * * wget -O - -q -t 1 https://www.example.com/cron.php > /dev/null\n"
},
{
"answer_id": 44714620,
"author": "Sam Arul Raj T",
"author_id": 493662,
"author_profile": "https://Stackoverflow.com/users/493662",
"pm_score": 4,
"selected": false,
"text": "sudo cat /etc/passwd | sed 's/^\\([^:]*\\):.*$/sudo crontab -u \\1 -l 2>\\&1/' | grep -v \"no crontab for\" | sh\n"
},
{
"answer_id": 48003490,
"author": "Sheikh Abdul Wahid",
"author_id": 3590283,
"author_profile": "https://Stackoverflow.com/users/3590283",
"pm_score": 4,
"selected": false,
"text": "for user in $(cut -f1 -d: /etc/passwd); do echo $user; sudo crontab -u $user -l; done\n"
},
{
"answer_id": 48194538,
"author": "armagedescu",
"author_id": 4582948,
"author_profile": "https://Stackoverflow.com/users/4582948",
"pm_score": 3,
"selected": false,
"text": "crontab -l username\n for user in $(cut -f1 -d: /etc/passwd); do crontab -l $user 2>/dev/null; done\n"
},
{
"answer_id": 64662148,
"author": "Ярослав Рахматуллин",
"author_id": 657703,
"author_profile": "https://Stackoverflow.com/users/657703",
"pm_score": 3,
"selected": false,
"text": "$ \\cat ~jaroslav/bin/ls-crons \n#!/bin/bash\ngetent passwd | awk -F: '{ print $1 }' | xargs -I% sh -c 'crontab -l -u % | sed \"/^$/d; /^#/d; s/^/% /\"' 2>/dev/null\necho\ncat /etc/crontab /etc/anacrontab 2>/dev/null | sed '/^$/d; /^#/d;'\necho\nrun-parts --list /etc/cron.hourly;\nrun-parts --list /etc/cron.daily;\nrun-parts --list /etc/cron.weekly;\nrun-parts --list /etc/cron.monthly;\n $ sudo ls-cron\n $ sudo ~jaroslav/bin/ls-crons \njaroslav */5 * * * * mv ~/java_error_in_PHPSTORM* ~/tmp 2>/dev/null\njaroslav 5 */24 * * * ~/bin/Find-home-files\njaroslav * 7 * * * cp /T/fortrabbit/ssh-config/fapps.tsv /home/jaroslav/reference/fortrabbit/fapps\njaroslav */8 1 * * * make -C /T/fortrabbit/ssh-config discover-apps # >/dev/null\njaroslav */7 * * * * getmail -r jazzoslav -r fortrabbit 2>/dev/null\njaroslav */1 * * * * /home/jaroslav/bin/checkmail\njaroslav * 9-18 * * * getmail -r fortrabbit 2>/dev/null\n\nSHELL=/bin/bash\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nMAILTO=root\nHOME=/\nSHELL=/bin/sh\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nMAILTO=root\nRANDOM_DELAY=45\nSTART_HOURS_RANGE=3-22\n1 5 cron.daily nice run-parts /etc/cron.daily\n7 25 cron.weekly nice run-parts /etc/cron.weekly\n@monthly 45 cron.monthly nice run-parts /etc/cron.monthly\n\n/etc/cron.hourly/0anacron\n/etc/cron.daily/logrotate\n/etc/cron.daily/man-db\n/etc/cron.daily/mlocate\n/etc/cron.weekly/mdadm\n/etc/cron.weekly/pfl\n SHELL=/bin/sh\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n17 * * * * root cd / && run-parts --report /etc/cron.hourly\n25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )\n47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )\n52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )\n\n/etc/cron.hourly/btrfs-quota-cleanup\n/etc/cron.hourly/ntpdate-debian\n/etc/cron.daily/apport\n/etc/cron.daily/apt-compat\n/etc/cron.daily/apt-show-versions\n/etc/cron.daily/aptitude\n/etc/cron.daily/bsdmainutils\n/etc/cron.daily/dpkg\n/etc/cron.daily/logrotate\n/etc/cron.daily/man-db\n/etc/cron.daily/mlocate\n/etc/cron.daily/passwd\n/etc/cron.daily/popularity-contest\n/etc/cron.daily/ubuntu-advantage-tools\n/etc/cron.daily/update-notifier-common\n/etc/cron.daily/upstart\n/etc/cron.weekly/apt-xapian-index\n/etc/cron.weekly/man-db\n/etc/cron.weekly/update-notifier-common\n\n"
},
{
"answer_id": 68988468,
"author": "Manifest Man",
"author_id": 5667103,
"author_profile": "https://Stackoverflow.com/users/5667103",
"pm_score": 1,
"selected": false,
"text": " echo \"Jobs owned by $USER\" && crontab -l -u $USER\n for wellknownUser in $(cut -f1 -d: /etc/passwd);\n do\n echo \"Jobs owned by $wellknownUser\";\n crontab -l -u $wellknownUser;\n echo -e \"\\n\";\n sleep 2; # (optional sleep 2 seconds) while drinking a coffee\n done\n"
},
{
"answer_id": 69394204,
"author": "linux.cnf",
"author_id": 10000566,
"author_profile": "https://Stackoverflow.com/users/10000566",
"pm_score": 3,
"selected": false,
"text": "cat /etc/passwd |awk -F ':' '{print $1}'|while read a;do crontab -l -u ${a} ; done\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
] |
134,917
|
<p>We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.</p>
<p>I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.</p>
<p>Any advice?</p>
|
[
{
"answer_id": 135004,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 2,
"selected": false,
"text": "WebRequest request = WebRequest.Create(\"http://something.somewhere/url\");\nWebResponse response = null;\nrequest.Timeout = 10000; // 10 second timeout\ntry\n{\n response = request.GetResponse();\n}\ncatch(WebException e)\n{\n if( e.Status == WebExceptionStatus.Timeout)\n {\n //something\n }\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
134,934
|
<p>How do I display a leading zero for all numbers with less than two digits?</p>
<pre class="lang-none prettyprint-override"><code>1 → 01
10 → 10
100 → 100
</code></pre>
|
[
{
"answer_id": 134942,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 6,
"selected": false,
"text": "x = [1, 10, 100]\nfor i in x:\n print '%02d' % i\n 01\n10\n100\n"
},
{
"answer_id": 134951,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 12,
"selected": true,
"text": "number = 1\nprint(\"%02d\" % (number,))\n printf sprintf format number = 1\nprint(\"{:02d}\".format(number))\n number = 1\nprint(f\"{number:02d}\")\n"
},
{
"answer_id": 134961,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 3,
"selected": false,
"text": "python -c 'print \"%(num)02d\" % {\"num\":5}'\n"
},
{
"answer_id": 135157,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 9,
"selected": false,
"text": "format() for i in (1, 10, 100):\n print('{num:02d}'.format(num=i))\n print(format(i, '02d'))\n"
},
{
"answer_id": 3371180,
"author": "Datageek",
"author_id": 328989,
"author_profile": "https://Stackoverflow.com/users/328989",
"pm_score": 10,
"selected": false,
"text": "str.zfill print(str(1).zfill(2))\nprint(str(10).zfill(2))\nprint(str(100).zfill(2))\n 01\n10\n100\n"
},
{
"answer_id": 4143246,
"author": "ajd",
"author_id": 503017,
"author_profile": "https://Stackoverflow.com/users/503017",
"pm_score": 7,
"selected": false,
"text": "print '{0:02d}'.format(1)"
},
{
"answer_id": 10358441,
"author": "ZuLu",
"author_id": 1100233,
"author_profile": "https://Stackoverflow.com/users/1100233",
"pm_score": 6,
"selected": false,
"text": "str(number).rjust(string_width, fill_char)\n a = [1, 10, 100]\nfor num in a:\n print str(num).rjust(2, '0')\n 01\n10\n100\n"
},
{
"answer_id": 19962689,
"author": "Kresimir",
"author_id": 1127700,
"author_profile": "https://Stackoverflow.com/users/1127700",
"pm_score": 7,
"selected": false,
"text": "print('{:02}'.format(1))\nprint('{:02}'.format(10))\nprint('{:02}'.format(100))\n 01\n10\n100\n"
},
{
"answer_id": 20005921,
"author": "nvd",
"author_id": 1943525,
"author_profile": "https://Stackoverflow.com/users/1943525",
"pm_score": 2,
"selected": false,
"text": "width = 5\nnum = 3\nformatted = (width - len(str(num))) * \"0\" + str(num)\nprint formatted\n"
},
{
"answer_id": 33860138,
"author": "WinterChilly",
"author_id": 4527839,
"author_profile": "https://Stackoverflow.com/users/4527839",
"pm_score": 5,
"selected": false,
"text": "\"{:0>2}\".format(number)\n"
},
{
"answer_id": 35497237,
"author": "Knowbody",
"author_id": 4526483,
"author_profile": "https://Stackoverflow.com/users/4526483",
"pm_score": -1,
"selected": false,
"text": "'0'+str(number)[-2:] '0{0}'.format(number)[-2:]"
},
{
"answer_id": 47534472,
"author": "Dimitris Fasarakis Hilliard",
"author_id": 4952130,
"author_profile": "https://Stackoverflow.com/users/4952130",
"pm_score": 7,
"selected": false,
"text": "f'{val:02}'\n val fill 0 width 2 a, b, c = 1, 10, 100\nfor val in [a, b, c]:\n print(f'{val:02}')\n 01 \n10\n100\n"
},
{
"answer_id": 49942659,
"author": "Linekio",
"author_id": 9675003,
"author_profile": "https://Stackoverflow.com/users/9675003",
"pm_score": 2,
"selected": false,
"text": "'00'[len(str(i)):] + str(i)\n math import math\n'00'[math.ceil(math.log(i, 10)):] + str(i)\n"
},
{
"answer_id": 50958859,
"author": "Roberto",
"author_id": 183713,
"author_profile": "https://Stackoverflow.com/users/183713",
"pm_score": 3,
"selected": false,
"text": "str(1).zfill(len(str(total)))\n"
},
{
"answer_id": 60642717,
"author": "Nicolas Gervais",
"author_id": 10908375,
"author_profile": "https://Stackoverflow.com/users/10908375",
"pm_score": 3,
"selected": false,
"text": "import numpy as np\n\nprint(f'{np.random.choice([1, 124, 13566]):0>8}')\n 0 00000001\n00000124\n00013566\n"
},
{
"answer_id": 66553049,
"author": "handle",
"author_id": 1619432,
"author_profile": "https://Stackoverflow.com/users/1619432",
"pm_score": 2,
"selected": false,
"text": ">python -m timeit \"'{:02d}'.format(1)\"\n1000000 loops, best of 5: 357 nsec per loop\n\n>python -m timeit \"'{0:0{1}d}'.format(1,2)\"\n500000 loops, best of 5: 607 nsec per loop\n\n>python -m timeit \"f'{1:02d}'\"\n1000000 loops, best of 5: 281 nsec per loop\n\n>python -m timeit \"f'{1:0{2}d}'\"\n500000 loops, best of 5: 423 nsec per loop\n\n>python -m timeit \"str(1).zfill(2)\"\n1000000 loops, best of 5: 271 nsec per loop\n\n>python\nPython 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32\n"
},
{
"answer_id": 72264376,
"author": "Stuart Demmer",
"author_id": 19106782,
"author_profile": "https://Stackoverflow.com/users/19106782",
"pm_score": 1,
"selected": false,
"text": "'{:0>2}'.format(1)\n"
},
{
"answer_id": 74377641,
"author": "thosbrown",
"author_id": 20460618,
"author_profile": "https://Stackoverflow.com/users/20460618",
"pm_score": -1,
"selected": false,
"text": "f'{number:02d}'\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22306/"
] |
134,956
|
<p>Is it even possible to perform address (physical, not e-mail) validation? It seems like the sheer number of address formats, even in the US alone, would make this a fairly difficult task. On the other hand it seems like a task that would be necessary for several business requirements.</p>
|
[
{
"answer_id": 13351246,
"author": "Xeoncross",
"author_id": 99923,
"author_profile": "https://Stackoverflow.com/users/99923",
"pm_score": 1,
"selected": false,
"text": "$address = urlencode('1600 Pennsylvania Avenue, Washington, DC');\n$json = json_decode(file_get_contents(\"http://where.yahooapis.com/geocode?q=$address&flags=J\"));\nprint_r($json);\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
134,958
|
<p>How would I be able to get N results for several groups in
an oracle query.</p>
<p>For example, given the following table:</p>
<pre><code>|--------+------------+------------|
| emp_id | name | occupation |
|--------+------------+------------|
| 1 | John Smith | Accountant |
| 2 | Jane Doe | Engineer |
| 3 | Jack Black | Funnyman |
|--------+------------+------------|
</code></pre>
<p>There are many more rows with more occupations. I would like to get
three employees (lets say) from each occupation.</p>
<p>Is there a way to do this without using a subquery?</p>
|
[
{
"answer_id": 135046,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 1,
"selected": false,
"text": "select *\nfrom people p1\n join people p2\n on p1.occupation = p2.occupation\n join people p3\n on p1.occupation = p3.occupation\n and p2.occupation = p3.occupation\nwhere p1.emp_id != p2.emp_id\n and p1.emp_id != p3.emp_id\n"
},
{
"answer_id": 135064,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 5,
"selected": false,
"text": "select *\nfrom (select emp_id, name, occupation,\n rank() over ( partition by occupation order by emp_id) rank\n from employee)\nwhere rank <= 3\n"
},
{
"answer_id": 135101,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": 1,
"selected": false,
"text": "select emp_id, name, occupation\nfrom employees t1\nwhere emp_id IN (select top 3 emp_id from employees t2 where t2.occupation = t1.occupation)\n"
},
{
"answer_id": 135977,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "SELECT MAX(e.name) AS name, MAX(e.occupation) AS occupation \nFROM emp e \n LEFT OUTER JOIN emp e2 \n ON (e.occupation = e2.occupation AND e.emp_id <= e2.emp_id) \nGROUP BY e.emp_id \nHAVING COUNT(*) <= 3 \nORDER BY occupation;\n"
},
{
"answer_id": 6263662,
"author": "trung",
"author_id": 787235,
"author_profile": "https://Stackoverflow.com/users/787235",
"pm_score": 2,
"selected": false,
"text": "select * from \n (select emp_id, name, occupation,rank() over ( partition by occupation order by emp_id,RowNum) rank \n from employee) \n where rank <= 3 \n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9435/"
] |
134,962
|
<p>I've been trying this a couple of different ways, but it's not working for some reason. Is it even possible?</p>
|
[
{
"answer_id": 39594411,
"author": "Richard",
"author_id": 269537,
"author_profile": "https://Stackoverflow.com/users/269537",
"pm_score": 0,
"selected": false,
"text": "GetVaryByCustomString(HttpContext context, string custom) custom VaryByCustom <%@ OutputCache Duration=\"86400\" VaryByParam=\"none\" VaryByCustom=\"custom1;custom2\" %>\n base.GetVaryByCustomString browser null"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
134,969
|
<p>In Ruby, is there the equivalent of the <code>__str__()</code> method that you can define on Python classes? </p>
|
[
{
"answer_id": 134978,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 3,
"selected": false,
"text": "irb(main):001:0> puts \"array is: #{[1,2,3].inspect}\"\narray is: [1, 2, 3]\n=> nil\nirb(main):002:0> puts \"array is: #{[1,2,3]}\"\narray is: 123\n=> nil\nirb(main):003:0>\n"
},
{
"answer_id": 135641,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 3,
"selected": false,
"text": "__repr__() __str__() Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form \"<...some useful description...>\" should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required."
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
134,988
|
<ol>
<li>Is it possible to secure only the Login.aspx page (and the postback) and not the whole site in IIS?</li>
<li>We are looking to do this specifically with a SharePoint site running Forms Based Authentication against our Active Directory.</li>
<li>Links to this will be helpful.</li>
</ol>
<p>This is what we have done so far:<br>
1. Setup SharePoint to use FBA against AD.<br>
2. Moved Login Page to Secure/Login.aspx<br>
3. Set the appropriate Login url in web.config as <code>https://..../Secure/Login.aspx</code></p>
<p>This is not working and help is needed here.
However even if this works, how do we get the user back to http from https?</p>
|
[
{
"answer_id": 153918,
"author": "Abs",
"author_id": 1245,
"author_profile": "https://Stackoverflow.com/users/1245",
"pm_score": 0,
"selected": false,
"text": "/_layouts Properties File Security Edit... Secure communications Require secure channel (SSL)"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/134988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21586/"
] |
135,000
|
<p>When generating XML from XmlDocument in .NET, a blank <code>xmlns</code> attribute appears the first time an element <em>without</em> an associated namespace is inserted; how can this be prevented?</p>
<p>Example:</p>
<pre><code>XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
</code></pre>
<p>Output:</p>
<pre><code><root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
</code></pre>
<p><em>Desired</em> Output:</p>
<pre><code><root xmlns="whatever:name-space-1.0"><loner /></root>
</code></pre>
<p>Is there a solution applicable to the <code>XmlDocument</code> code, not something that occurs <em>after</em> converting the document to a string with <code>OuterXml</code>?</p>
<p>My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank <code>xmlns</code> attribute <em>may</em> not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.</p>
|
[
{
"answer_id": 135027,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": false,
"text": "<loner> xmlns whatever:name-space-1.0 xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")\n <loner> xmlns"
},
{
"answer_id": 135066,
"author": "jlew",
"author_id": 7450,
"author_profile": "https://Stackoverflow.com/users/7450",
"pm_score": 3,
"selected": false,
"text": "<w:root xmlns:w=\"whatever:name-space-1.0\">\n <loner/>\n</w:root>\n XmlDocument doc = new XmlDocument();\nXmlElement root = doc.CreateElement( \"w\", \"root\", \"whatever:name-space-1.0\" );\ndoc.AppendChild( root );\nroot.AppendChild( doc.CreateElement( \"loner\" ) );\nConsole.WriteLine(doc.OuterXml);\n"
},
{
"answer_id": 135525,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\nns.Add(\"\", \"\");\nXmlSerializer serializer = new XmlSerializer(yourType);\nserializer.Serialize(xmlTextWriter, someObject, ns);\n"
},
{
"answer_id": 135982,
"author": "Neil C. Obremski",
"author_id": 9642,
"author_profile": "https://Stackoverflow.com/users/9642",
"pm_score": 8,
"selected": true,
"text": "xmlns XmlDocument xml = new XmlDocument();\nxml.AppendChild(xml.CreateElement(\"root\", \"whatever:name-space-1.0\"));\nxml.DocumentElement.AppendChild(xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")); \nConsole.WriteLine(xml.OuterXml);\n"
},
{
"answer_id": 5093771,
"author": "brinke",
"author_id": 630565,
"author_profile": "https://Stackoverflow.com/users/630565",
"pm_score": 0,
"selected": false,
"text": "internal class XElementFactory\n{\n private readonly XNamespace currentNs;\n\n public XElementFactory(XNamespace ns)\n {\n this.currentNs = ns;\n }\n\n internal XElement CreateXElement(String name, params object[] content)\n {\n return new XElement(currentNs + name, content);\n }\n}\n"
},
{
"answer_id": 8676037,
"author": "C.J.",
"author_id": 321866,
"author_profile": "https://Stackoverflow.com/users/321866",
"pm_score": 7,
"selected": false,
"text": "XmlElement new_element = doc.CreateElement(\"Foo\", doc.DocumentElement.NamespaceURI);\n"
},
{
"answer_id": 30685927,
"author": "Debabrata Ghosh",
"author_id": 4981856,
"author_profile": "https://Stackoverflow.com/users/4981856",
"pm_score": 0,
"selected": false,
"text": "<trkpt lat=\"30.53597\" lon=\"-97.753324\" xmlns=\"\">\n <ele>249.118774</ele>\n <time>2006-05-05T14:34:44Z</time>\n</trkpt>\n XmlElement bookElement = xdoc.CreateElement(\"trkpt\", \"http://www.topografix.com/GPX/1/1\");\nbookElement.SetAttribute(\"lat\", \"30.53597\");\nbookElement.SetAttribute(\"lon\", \"97.753324\");\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
135,010
|
<p>I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is. </p>
<p>Here's the scenario,
I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email.</p>
<p>Here's the 'servstop.txt' file contents:</p>
<blockquote>
<p>[SC] StartService FAILED 1058:</p>
<p>The service cannot be started, either
because it is disabled or because it
has no enabled devices associated with
it.</p>
</blockquote>
<p>I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058"
and the body to contain the entire error message above.</p>
<p>I will put my current method in an answer below using a program called blat to send me the result.</p>
|
[
{
"answer_id": 135027,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": false,
"text": "<loner> xmlns whatever:name-space-1.0 xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")\n <loner> xmlns"
},
{
"answer_id": 135066,
"author": "jlew",
"author_id": 7450,
"author_profile": "https://Stackoverflow.com/users/7450",
"pm_score": 3,
"selected": false,
"text": "<w:root xmlns:w=\"whatever:name-space-1.0\">\n <loner/>\n</w:root>\n XmlDocument doc = new XmlDocument();\nXmlElement root = doc.CreateElement( \"w\", \"root\", \"whatever:name-space-1.0\" );\ndoc.AppendChild( root );\nroot.AppendChild( doc.CreateElement( \"loner\" ) );\nConsole.WriteLine(doc.OuterXml);\n"
},
{
"answer_id": 135525,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\nns.Add(\"\", \"\");\nXmlSerializer serializer = new XmlSerializer(yourType);\nserializer.Serialize(xmlTextWriter, someObject, ns);\n"
},
{
"answer_id": 135982,
"author": "Neil C. Obremski",
"author_id": 9642,
"author_profile": "https://Stackoverflow.com/users/9642",
"pm_score": 8,
"selected": true,
"text": "xmlns XmlDocument xml = new XmlDocument();\nxml.AppendChild(xml.CreateElement(\"root\", \"whatever:name-space-1.0\"));\nxml.DocumentElement.AppendChild(xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")); \nConsole.WriteLine(xml.OuterXml);\n"
},
{
"answer_id": 5093771,
"author": "brinke",
"author_id": 630565,
"author_profile": "https://Stackoverflow.com/users/630565",
"pm_score": 0,
"selected": false,
"text": "internal class XElementFactory\n{\n private readonly XNamespace currentNs;\n\n public XElementFactory(XNamespace ns)\n {\n this.currentNs = ns;\n }\n\n internal XElement CreateXElement(String name, params object[] content)\n {\n return new XElement(currentNs + name, content);\n }\n}\n"
},
{
"answer_id": 8676037,
"author": "C.J.",
"author_id": 321866,
"author_profile": "https://Stackoverflow.com/users/321866",
"pm_score": 7,
"selected": false,
"text": "XmlElement new_element = doc.CreateElement(\"Foo\", doc.DocumentElement.NamespaceURI);\n"
},
{
"answer_id": 30685927,
"author": "Debabrata Ghosh",
"author_id": 4981856,
"author_profile": "https://Stackoverflow.com/users/4981856",
"pm_score": 0,
"selected": false,
"text": "<trkpt lat=\"30.53597\" lon=\"-97.753324\" xmlns=\"\">\n <ele>249.118774</ele>\n <time>2006-05-05T14:34:44Z</time>\n</trkpt>\n XmlElement bookElement = xdoc.CreateElement(\"trkpt\", \"http://www.topografix.com/GPX/1/1\");\nbookElement.SetAttribute(\"lat\", \"30.53597\");\nbookElement.SetAttribute(\"lon\", \"97.753324\");\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] |
135,020
|
<p>When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?</p>
<p>Example:</p>
<pre><code>foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}
</code></pre>
<p>...</p>
<pre><code>private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}
private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}
</code></pre>
<p>Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.</p>
|
[
{
"answer_id": 135023,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": false,
"text": "this static"
},
{
"answer_id": 36888316,
"author": "sara",
"author_id": 2622234,
"author_profile": "https://Stackoverflow.com/users/2622234",
"pm_score": 2,
"selected": false,
"text": "public class MyClass\n{\n private readonly MyDependency _dependency;\n\n public MyClass(MyDependency dependency)\n {\n _dependency = dependency;\n }\n\n public int CalculateHardStuff()\n {\n var intermediate = StepOne(_dependency);\n return StepTwo(intermediate);\n }\n\n private static int StepOne(MyDependency dependency)\n {\n return dependency.GetFirst3Primes().Sum();\n }\n\n private static int StepTwo(int intermediate)\n {\n return (intermediate + 5)/4;\n }\n}\n\npublic class MyDependency\n{\n public IEnumerable<int> GetFirst3Primes()\n {\n yield return 2;\n yield return 3;\n yield return 5;\n }\n}\n MyClass"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6146/"
] |
135,035
|
<p>In ruby the library path is provided in <code>$:</code>, in perl it's in <code>@INC</code> - how do you get the list of paths that Python searches for modules when you do an import?</p>
|
[
{
"answer_id": 135050,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "import sys\nsys.path\n"
},
{
"answer_id": 135051,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 8,
"selected": true,
"text": "import sys\nprint (sys.path)\n"
},
{
"answer_id": 135273,
"author": "apg",
"author_id": 22277,
"author_profile": "https://Stackoverflow.com/users/22277",
"pm_score": 7,
"selected": false,
"text": "import sys\nsys.path.append('/home/user/python-libs')\n"
},
{
"answer_id": 71260812,
"author": "CodeFarmer",
"author_id": 479008,
"author_profile": "https://Stackoverflow.com/users/479008",
"pm_score": 2,
"selected": false,
"text": "python -c \"import sys; print('\\n'.join(sys.path))\"\n\n\n/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python39.zip\n/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9\n/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload\n/usr/local/lib/python3.9/site-packages\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
] |
135,041
|
<p>Why or why not?</p>
|
[
{
"answer_id": 135070,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 4,
"selected": false,
"text": "xrange() xrange()"
},
{
"answer_id": 135074,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 5,
"selected": false,
"text": "range() xrange() range() xrange() range() xrange() xrange()"
},
{
"answer_id": 135114,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 10,
"selected": true,
"text": "xrange() range() range() xrange() xrange() xrange() range() xrange() range() xrange() range() range() xrange() RefactoringTool: Skipping implicit fixer: buffer\nRefactoringTool: Skipping implicit fixer: idioms\nRefactoringTool: Skipping implicit fixer: ws_comma\n--- range_test.py (original)\n+++ range_test.py (refactored)\n@@ -1,7 +1,7 @@\n\n for x in range(20):\n- a=range(20)\n+ a=list(range(20))\n b=list(range(20))\n c=[x for x in range(20)]\n d=(x for x in range(20))\n- e=xrange(20)\n+ e=range(20)\n"
},
{
"answer_id": 135669,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 7,
"selected": false,
"text": "xrange() for x in xrange(1, one_zillion):\n for x in range(1, one_zillion):\n range() multiples_of_seven = range(7,100,7)\nprint \"Multiples of seven < 100: \", multiples_of_seven\n"
},
{
"answer_id": 9641194,
"author": "Garrett Berg",
"author_id": 674076,
"author_profile": "https://Stackoverflow.com/users/674076",
"pm_score": 3,
"selected": false,
"text": "from __future__ import division\n\ndef read_xrange(xrange_object):\n # returns the xrange object's start, stop, and step\n start = xrange_object[0]\n if len(xrange_object) > 1:\n step = xrange_object[1] - xrange_object[0]\n else:\n step = 1\n stop = xrange_object[-1] + step\n return start, stop, step\n\nclass Xrange(object):\n ''' creates an xrange-like object that supports slicing and indexing.\n ex: a = Xrange(20)\n a.index(10)\n will work\n\n Also a[:5]\n will return another Xrange object with the specified attributes\n\n Also allows for the conversion from an existing xrange object\n '''\n def __init__(self, *inputs):\n # allow inputs of xrange objects\n if len(inputs) == 1:\n test, = inputs\n if type(test) == xrange:\n self.xrange = test\n self.start, self.stop, self.step = read_xrange(test)\n return\n\n # or create one from start, stop, step\n self.start, self.step = 0, None\n if len(inputs) == 1:\n self.stop, = inputs\n elif len(inputs) == 2:\n self.start, self.stop = inputs\n elif len(inputs) == 3:\n self.start, self.stop, self.step = inputs\n else:\n raise ValueError(inputs)\n\n self.xrange = xrange(self.start, self.stop, self.step)\n\n def __iter__(self):\n return iter(self.xrange)\n\n def __getitem__(self, item):\n if type(item) is int:\n if item < 0:\n item += len(self)\n\n return self.xrange[item]\n\n if type(item) is slice:\n # get the indexes, and then convert to the number\n start, stop, step = item.start, item.stop, item.step\n start = start if start != None else 0 # convert start = None to start = 0\n if start < 0:\n start += start\n start = self[start]\n if start < 0: raise IndexError(item)\n step = (self.step if self.step != None else 1) * (step if step != None else 1)\n stop = stop if stop is not None else self.xrange[-1]\n if stop < 0:\n stop += stop\n\n stop = self[stop]\n stop = stop\n\n if stop > self.stop:\n raise IndexError\n if start < self.start:\n raise IndexError\n return Xrange(start, stop, step)\n\n def index(self, value):\n error = ValueError('object.index({0}): {0} not in object'.format(value))\n index = (value - self.start)/self.step\n if index % 1 != 0:\n raise error\n index = int(index)\n\n\n try:\n self.xrange[index]\n except (IndexError, TypeError):\n raise error\n return index\n\n def __len__(self):\n return len(self.xrange)\n"
},
{
"answer_id": 11795908,
"author": "Brian Minton",
"author_id": 752695,
"author_profile": "https://Stackoverflow.com/users/752695",
"pm_score": 5,
"selected": false,
"text": "xrange() range() Python 2.7.3 (default, Jul 13 2012, 22:29:01) \n[GCC 4.7.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> range(123456787676676767676676,123456787676676767676679)\n[123456787676676767676676L, 123456787676676767676677L, 123456787676676767676678L]\n>>> xrange(123456787676676767676676,123456787676676767676679)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nOverflowError: Python int too large to convert to C long\n Python 3.2.3 (default, Jul 14 2012, 01:01:48) \n[GCC 4.7.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> range(123456787676676767676676,123456787676676767676679)\nrange(123456787676676767676676, 123456787676676767676679)\n"
},
{
"answer_id": 18288537,
"author": "Grijesh Chauhan",
"author_id": 1673391,
"author_profile": "https://Stackoverflow.com/users/1673391",
"pm_score": 2,
"selected": false,
"text": ">>> zip(range(5), xrange(100000000))\n[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\n"
},
{
"answer_id": 39428467,
"author": "Tushar Patil",
"author_id": 2013238,
"author_profile": "https://Stackoverflow.com/users/2013238",
"pm_score": 2,
"selected": false,
"text": "range() range(1, 10) xrange() range() range() xrange() In [1]: range(1,10)\nOut[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nIn [2]: xrange(10)\nOut[2]: xrange(10)\n\nIn [3]: print xrange.__doc__\nOut[3]: xrange([start,] stop[, step]) -> xrange object\n range() xrange() xrange() range() xrange() range()"
},
{
"answer_id": 41726540,
"author": "speedplane",
"author_id": 234270,
"author_profile": "https://Stackoverflow.com/users/234270",
"pm_score": 2,
"selected": false,
"text": "xrange range range xrange import timeit\n# Try various list sizes.\nfor list_len in [1, 10, 100, 1000, 10000, 100000, 1000000]:\n # Time doing a range and an xrange.\n rtime = timeit.timeit('a=0;\\nfor n in range(%d): a += n'%list_len, number=1000)\n xrtime = timeit.timeit('a=0;\\nfor n in xrange(%d): a += n'%list_len, number=1000)\n # Print the result\n print \"Loop list of len %d: range=%.4f, xrange=%.4f\"%(list_len, rtime, xrtime)\n xrange Loop list of len 1: range=0.0003, xrange=0.0003\nLoop list of len 10: range=0.0013, xrange=0.0011\nLoop list of len 100: range=0.0068, xrange=0.0034\nLoop list of len 1000: range=0.0609, xrange=0.0438\nLoop list of len 10000: range=0.5527, xrange=0.5266\nLoop list of len 100000: range=10.1666, xrange=7.8481\nLoop list of len 1000000: range=168.3425, xrange=155.8719\n xrange"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
] |
135,057
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/574463">Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine</a> </p>
</blockquote>
<p>Is there a way to have Internet Explorer 8 and Internet Explorer 6 side by side without virtualizing?</p>
<p>I used <a href="http://tredosoft.com/Multiple_IE" rel="nofollow noreferrer" title="Multiple IEs">Multiple IEs</a> which works fine with Internet Explorer 7, but since I installed Internet Explorer 8 beta 2, Internet Explorer 6 started behaving oddly (that is, more than usual).</p>
|
[
{
"answer_id": 179126,
"author": "Carl Camera",
"author_id": 12804,
"author_profile": "https://Stackoverflow.com/users/12804",
"pm_score": 4,
"selected": false,
"text": "mshtml.dll"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13275/"
] |
135,069
|
<p>This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...</p>
<p>Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:</p>
<pre><code>//---- SomeSourceFile.cpp ----
#define DEBUG_ENABLED (0)
...
SomeFunction()
{
int someVariable = 5;
#if(DEBUG_ENABLED)
printf("Debugging: someVariable == %d", someVariable);
#endif
}
</code></pre>
<p>Some of the team prefer the following though:</p>
<pre><code>// #define DEBUG_ENABLED
...
SomeFunction()
{
int someVariable = 5;
#ifdef DEBUG_ENABLED
printf("Debugging: someVariable == %d", someVariable);
#endif
}
</code></pre>
<p>...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere.</p>
|
[
{
"answer_id": 135077,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 3,
"selected": false,
"text": "#if #define DEBUG 1"
},
{
"answer_id": 135089,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 3,
"selected": false,
"text": "#if defined(DEBUG_ENABLED)\n #if !defined(DEBUG_ENABLED)\n #ifndef(DEBUG_ENABLED)\n"
},
{
"answer_id": 135253,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "#define MY_MACRO (0)\n\nint doSomething(int p_iValue)\n{\n return p_iValue + 1 ;\n}\n\nint main(int argc, char **argv)\n{\n int MY_MACRO = 25 ;\n doSomething(MY_MACRO) ;\n\n return 0;\n}\n main.cpp|408|error: lvalue required as left operand of assignment|\n||=== Build finished: 1 errors, 0 warnings ===|\n #define MY_MACRO\n\nint doSomething(int p_iValue)\n{\n return p_iValue + 1 ;\n}\n\nint main(int argc, char **argv)\n{\n int MY_MACRO = 25 ;\n doSomething(MY_MACRO) ;\n\n return 0;\n}\n main.cpp||In function ‘int main(int, char**)’:|\nmain.cpp|406|error: expected unqualified-id before ‘=’ token|\nmain.cpp|399|error: too few arguments to function ‘int doSomething(int)’|\nmain.cpp|407|error: at this point in file|\n||=== Build finished: 3 errors, 0 warnings ===|\n #define MY_MACRO @@@@@@@@@@@@@@@@@@\n main.cpp|410|error: stray ‘@’ in program|\n"
},
{
"answer_id": 135454,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 8,
"selected": true,
"text": "#ifdef #if DEBUG_ENABLED #if DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000);\n #ifdef DEBUG_MODE\n DoSomethingSlowWithTimeout(5000);\n#else\n DoSomethingSlowWithTimeout(1000);\n#endif\n #define #define #if #ifdef DEBUG_ENABLED #define #define DEBUG_ENABLED true\n #define DEBUG_ENABLED (1)\n"
},
{
"answer_id": 135611,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 3,
"selected": false,
"text": "#ifdef USE_DEBUG\n#define debug_print printf\n#else\n#define debug_print\n#endif\n\ndebug_print(\"i=%d\\n\", i);\n void dummy(const char*, ...)\n{}\n\n#ifdef USE_DEBUG\n#define debug_print printf\n#else\n#define debug_print dummy\n#endif\n\ndebug_print(\"i=%d\\n\", i);\n"
},
{
"answer_id": 135981,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 4,
"selected": false,
"text": "#if defined(PRO_VERSION) && !defined(TRIAL_VERSION)\n...\n#else\n...\n#endif\n"
},
{
"answer_id": 136080,
"author": "Terence Simpson",
"author_id": 22395,
"author_profile": "https://Stackoverflow.com/users/22395",
"pm_score": 5,
"selected": false,
"text": "#ifdef #define FOO 0\n #ifdef FOO // is true\n#if FOO // is false, because it evaluates to \"#if 0\"\n"
},
{
"answer_id": 3160643,
"author": "Brent Priddy",
"author_id": 351211,
"author_profile": "https://Stackoverflow.com/users/351211",
"pm_score": 5,
"selected": false,
"text": "#ifndef FEATURE_H\n#define FEATURE_H\n\n// turn on cool new feature\n#define COOL_FEATURE 1\n\n#endif // FEATURE_H\n #if COOL_FEATURE\n // definitely awesome stuff here...\n#endif\n #ifndef FEATURE_H\n#define FEATURE_H\n\n// turn on cool new feature\n#define COOL_FEATURE() 1\n\n#endif // FEATURE_H\n #if COOL_FEATURE()\n // definitely awseome stuff here...\n#endif\n"
},
{
"answer_id": 3172334,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 6,
"selected": false,
"text": "#ifdef DEBUG\n#define D(x) do { x } while(0)\n#else\n#define D(x) do { } while(0)\n#endif\n D(); #ifdef"
},
{
"answer_id": 17032843,
"author": "tmanthey",
"author_id": 837119,
"author_profile": "https://Stackoverflow.com/users/837119",
"pm_score": 2,
"selected": false,
"text": "#ifdef macro\n #if macro\n #if macro !=0\n #if CFLAG_EDITION == 0\n return EDITION_FREE;\n#elif CFLAG_EDITION == 1\n return EDITION_BASIC;\n#else\n return EDITION_PRO;\n#endif\n #define CFLAG_EDITION 1 \n"
},
{
"answer_id": 45511381,
"author": "StefanB",
"author_id": 5895733,
"author_profile": "https://Stackoverflow.com/users/5895733",
"pm_score": 1,
"selected": false,
"text": "#ifdef #if"
},
{
"answer_id": 48298164,
"author": "Tomilov Anatoliy",
"author_id": 1430927,
"author_profile": "https://Stackoverflow.com/users/1430927",
"pm_score": 2,
"selected": false,
"text": "diff <( echo | g++ -DA= -dM -E - ) <( echo | g++ -DA -dM -E - )\n 344c344\n< #define A \n---\n> #define A 1\n -DA -DA=1 #if A"
},
{
"answer_id": 57519378,
"author": "memtha",
"author_id": 11529348,
"author_profile": "https://Stackoverflow.com/users/11529348",
"pm_score": 0,
"selected": false,
"text": "#define DEBUG_ENABLED (0) #define DEBUG_RELEASE (0)\n#define DEBUG_ERROR (1)\n#define DEBUG_WARN (2)\n#define DEBUG_MEM (3)\n#ifndef DEBUG_LEVEL\n#define DEBUG_LEVEL (DEBUG_RELEASE)\n#endif\n//...\n\n//now not only\n#if (DEBUG_LEVEL)\n//...\n#endif\n\n//but also\n#if (DEBUG_LEVEL >= DEBUG_MEM)\nLOG(\"malloc'd %d bytes at %s:%d\\n\", size, __FILE__, __LINE__);\n#endif\n #ifndef make -DDEBUG_LEVEL=2\ncmake -DDEBUG_LEVEL=2\netc\n #ifdef"
},
{
"answer_id": 68450723,
"author": "iheanyi",
"author_id": 2250588,
"author_profile": "https://Stackoverflow.com/users/2250588",
"pm_score": 0,
"selected": false,
"text": "#ifdef HAS_FEATURE_X #define HAS_FEATURE_X 0 #if !defined(HAS_FEATURE_X) || HAS_FEATURE_X == 1 #ifdef #if"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] |
135,076
|
<p>I am <strong>losing hair</strong> on this one ... it seems that when I fix width an HTML SELECT control it renders its width differently depending on the browser. </p>
<p>Any idea how to to standardize this without having to turn to multiple style sheets?</p>
<p>Here is what I am working with:</p>
<pre><code>.combo
{
padding: 2px;
width: 200px;
}
.text
{
padding: 2px;
width: 200px;
}
</code></pre>
<p>This is my document type for the page:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code></pre>
|
[
{
"answer_id": 135085,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "font-size min-width max-width"
},
{
"answer_id": 135764,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 0,
"selected": false,
"text": " .combo\n {\n padding: 2px;\n width: 206px;\n }\n\n.text\n{\n padding: 2px;\n width: 200px;\n}\n"
},
{
"answer_id": 10325061,
"author": "cheekybastard",
"author_id": 1357413,
"author_profile": "https://Stackoverflow.com/users/1357413",
"pm_score": 0,
"selected": false,
"text": "select {\n width:350px;\n}\n select {\n width:350px;\n}\n input[type=text] {\n width:350px;\n}\n\ninput[type=input] {\n width:350px;\n}\n\ninput[type=file] {\n width:350px;\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
135,105
|
<p>We'd like to override DataGridView's default behavior when using a mouse wheel with this control. By default, the DataGridView scrolls a number of rows equal the SystemInformation.MouseWheelScrollLines setting. What we'd like to do is scroll just one item at a time. </p>
<p>(We display images in the DataGridView, which are somewhat large. Because of this scroll three rows (a typical system setting) is too much, often causing the user to scroll to items they can't even see.)</p>
<p>I've tried a couple things already and haven't had much success so far. Here are some issues I've run into:</p>
<ol>
<li><p>You can subscribe to MouseWheel events but there's no way to mark the event as handled and do my own thing.</p></li>
<li><p>You can override OnMouseWheel but this never appears to be called.</p></li>
<li><p>You might be able to correct this in the base scrolling code but it sounds like a messy job since other types of scrolling (e.g. using the keyboard) come through the same pipeline.</p></li>
</ol>
<p>Anyone have a good suggestion?</p>
<p>Here's the final code, using the wonderful answer given:</p>
<pre><code> /// <summary>
/// Handle the mouse wheel manually due to the fact that we display
/// images, which don't work well when you scroll by more than one
/// item at a time.
/// </summary>
///
/// <param name="sender">
/// sender
/// </param>
/// <param name="e">
/// the mouse event
/// </param>
private void mImageDataGrid_MouseWheel(object sender, MouseEventArgs e)
{
// Hack alert! Through reflection, we know that the passed
// in event argument is actually a handled mouse event argument,
// allowing us to handle this event ourselves.
// See http://tinyurl.com/54o7lc for more info.
HandledMouseEventArgs handledE = (HandledMouseEventArgs) e;
handledE.Handled = true;
// Do the scrolling manually. Move just one row at a time.
int rowIndex = mImageDataGrid.FirstDisplayedScrollingRowIndex;
mImageDataGrid.FirstDisplayedScrollingRowIndex =
e.Delta < 0 ?
Math.Min(rowIndex + 1, mImageDataGrid.RowCount - 1):
Math.Max(rowIndex - 1, 0);
}
</code></pre>
|
[
{
"answer_id": 135516,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 1,
"selected": false,
"text": "public partial class MyDataGridView : DataGridView\n protected override void WndProc(ref Message m)\n{\n if (m.Msg == 0x20a)\n {\n int wheelDelta = ((int)m.WParam) >> 16;\n\n // 120 = UP 1 tick\n // -120 = DOWN 1 tick\n\n this.FirstDisplayedScrollingRowIndex -= (wheelDelta / 120);\n }\n else\n {\n base.WndProc(ref m);\n }\n}\n"
},
{
"answer_id": 135562,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": true,
"text": "MouseWheel MouseEventArgs OnMouseWheel() DataGridView Handled MouseEventArgs MouseWheel OnMouseWheel() DataGridView SystemInformation.MouseWheelScrollLines MouseWheel MouseEventArgs HandledMouseEventArgs Handled = true DataGridView OnMouseWheel() SystemInformation.MouseWheelScrollLines 1 ScrollBar"
},
{
"answer_id": 135997,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 1,
"selected": false,
"text": "DataGridView MouseWheel DataGridView WndProc WM_MOUSEWHEEL SendKeys.Send DataGridView public class MyDataGridView : DataGridView\n{\n private const uint WM_MOUSEWHEEL = 0x20a;\n\n protected override void WndProc(ref Message m)\n {\n if (m.Msg == WM_MOUSEWHEEL)\n {\n var wheelDelta = ((int)m.WParam) >> 16;\n\n if (wheelDelta < 0)\n {\n SendKeys.Send(\"{DOWN}\");\n }\n\n if (wheelDelta > 0)\n {\n SendKeys.Send(\"{UP}\");\n }\n\n return;\n }\n\n base.WndProc(ref m);\n }\n}\n public class MyDataGridView : DataGridView\n{\n protected override void OnMouseWheel(MouseEventArgs e)\n {\n if (e.Delta < 0)\n SendKeys.Send(\"{DOWN}\");\n else\n SendKeys.Send(\"{UP}\");\n }\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7357/"
] |
135,121
|
<p>So in my documentation it says:</p>
<blockquote>
<p>public event TreeViewPlusNodeCheckedEventHandler NodeChecked()</p>
<p>You can use this event to run cause a method to run whenever the
check-box for a node is checked on the tree.</p>
</blockquote>
<p>So how do I add a method to my code behind file that will run when a node is checked? The method I want to run is:</p>
<pre><code>protected void TOCNodeCheckedServer(object sender, TreeViewPlusNodeEventArgs args)
{
TreeViewPlusNode aNode = args.Node;
if (!aNode.Checked)
return;
List<string> BaseLayers = new List<string>();
_arcTOCConfig.BaseDataLayers.CopyTo(BaseLayers);
List<MapResourceItem> mapResources = new List<MapResourceItem>();
if (BaseLayers.Contains(aNode.Text))
{
foreach (BaseDataLayerElement anEl in _arcTOCConfig.BaseDataLayers)
{
if (!aNode.Text.Equals(anEl.Name))
{
if (aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked)
{
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked = false;
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Refresh();
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
aMapResource.DisplaySettings.Visible = false;
this.Map1.RefreshResource(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
else
{
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
}
}
foreach (MapResourceItem aMapResource in mapResources)
{
int count = this.Map1.MapResourceManagerInstance.ResourceItems.Count - 1;
this.Map1.MapResourceManagerInstance.ResourceItems.Insert(count, aMapResource);
this.Map1.MapResourceManagerInstance.CreateResource(aMapResource);
}
this.Map1.InitializeFunctionalities();
this.Map1.Refresh();
}
}
</code></pre>
<p>vs 2008
c#
.net 3.5</p>
|
[
{
"answer_id": 135138,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 2,
"selected": false,
"text": "myTreeView.NodeChecked += new TreeViewPlusNodeCheckedEventHandler(TOCNodeCheckedServer);\n myTreeView.NodeChecked += TOCNodeCheckedServer;\n"
},
{
"answer_id": 135141,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 2,
"selected": false,
"text": "treeView.NodeChecked += TOCNodeCheckedServer;\n"
},
{
"answer_id": 135166,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 0,
"selected": false,
"text": "TOCTree.NodeChecked += new TreeViewPlusNodeCheckedEventHandler (TOCNodeCheckedServer);\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] |
135,129
|
<p>I seem to be seeing more 'for' loops over iterators in questions & answers here than I do for_each(), transform(), and the like. Scott Meyers suggests that <a href="http://www.ddj.com/cpp/184401446" rel="noreferrer">stl algorithms are preferred</a>, or at least he did in 2001. Of course, using them often means moving the loop body into a function or function object. Some may feel this is an unacceptable complication, while others may feel it better breaks down the problem.</p>
<p>So... should STL algorithms be preferred over hand-rolled loops?</p>
|
[
{
"answer_id": 135196,
"author": "Maximilian",
"author_id": 1733,
"author_profile": "https://Stackoverflow.com/users/1733",
"pm_score": 2,
"selected": false,
"text": "for (int i = 0; i < some_vector.size(); i++)\n if (some_vector[i] == NULL) some_other_vector[i]++;\n"
},
{
"answer_id": 135545,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 2,
"selected": false,
"text": "int weighted_sum = 0;\nfor (int i = 0; i < a_vector.size(); ++i) {\n weighted_sum += (i + 1) * a_vector[i]; // Just writing something a little nontrivial.\n}\n"
},
{
"answer_id": 135739,
"author": "Roman Odaisky",
"author_id": 21055,
"author_profile": "https://Stackoverflow.com/users/21055",
"pm_score": 2,
"selected": false,
"text": "for std::max_element std::deque"
},
{
"answer_id": 135744,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 3,
"selected": false,
"text": "std::foreach std::foreach #include <string>\n#include <iostream>\n#include <boost/foreach.hpp>\n\nint main()\n{\n std::string hello( \"Hello, world!\" );\n\n BOOST_FOREACH( char ch, hello )\n {\n std::cout << ch;\n }\n\n return 0;\n}\n"
},
{
"answer_id": 137195,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 2,
"selected": false,
"text": "auto for"
},
{
"answer_id": 2166072,
"author": "Ron Romero",
"author_id": 85348,
"author_profile": "https://Stackoverflow.com/users/85348",
"pm_score": 3,
"selected": false,
"text": "for (vector<Child>::iterator iter = children.begin();\n iter != children.end();\n ++iter)\n{\n iter->setFooCount(n);\n}\n for_each(children.begin(), children.end(), SetFooCount(n));\n SetFooCount class SetFooCount\n{\npublic:\n SetFooCount(int n) : fooCount(n) {}\n\n void operator () (Child& child)\n {\n child.setFooCount(fooCount);\n }\n\nprivate:\n int fooCount;\n};\n SetFooCount SetFooCount for_each"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10077/"
] |
135,132
|
<p>I'm really baffled by this - I know how to do this in VB, unmanaged C++ and C# but for some reason I can't accept a ref variable of a managed type in C++. I'm sure there's a simple answer, really - but here's the C# equivalent:</p>
<pre><code>myClass.myFunction(ref variableChangedByfunction);
</code></pre>
<p>I've tried C++ pointers - no dice. I've tried ref keywords. No dice. I tried the <code>[out]</code> keyword. Didn't work.</p>
<p>I can't find any documentation that clearly explains my problem, either.</p>
|
[
{
"answer_id": 2280477,
"author": "rotti2",
"author_id": 207620,
"author_profile": "https://Stackoverflow.com/users/207620",
"pm_score": 1,
"selected": false,
"text": "^ ref out %"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
135,149
|
<p>I'm trying to confirm a user a unplugged my embedded device from a network before performing some maintenance. I'm considering "ping"ing all IP address on my sub-net, but that sounds crude. Is there a broadcast/ARP method that might work better?</p>
|
[
{
"answer_id": 135172,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 2,
"selected": false,
"text": "ping -b 255.255.255.255\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15797/"
] |
135,151
|
<p>The .NET web system I'm working on allows the end user to input HTML formatted text in some situations. In some of those places, we want to leave all the tags, but strip off any trailing break tags (but leave any breaks inside the body of the text.)</p>
<p>What's the best way to do this? (I can think of ways to do this, but I'm sure they're not the best.)</p>
|
[
{
"answer_id": 135165,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 2,
"selected": false,
"text": "while (myHtmlString.EndsWith(\"<br>\"))\n{\n myHtmlString = myHtmlString.SubString(0, myHtmlString.Length - 4);\n}\n"
},
{
"answer_id": 135216,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": true,
"text": "// using System.Text.RegularExpressions;\n\n/// <summary>\n/// Regular expression built for C# on: Thu, Sep 25, 2008, 02:01:36 PM\n/// Using Expresso Version: 2.1.2150, http://www.ultrapico.com\n/// \n/// A description of the regular expression:\n/// \n/// Match expression but don't capture it. [\\<br\\s*/?\\>], any number of repetitions\n/// \\<br\\s*/?\\>\n/// <\n/// br\n/// Whitespace, any number of repetitions\n/// /, zero or one repetitions\n/// >\n/// End of line or string\n/// \n/// \n/// </summary>\npublic static Regex regex = new Regex(\n @\"(?:\\<br\\s*/?\\>)*$\",\n RegexOptions.IgnoreCase\n | RegexOptions.CultureInvariant\n | RegexOptions.IgnorePatternWhitespace\n | RegexOptions.Compiled\n );\nregex.Replace(text, string.Empty);\n"
},
{
"answer_id": 135239,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 1,
"selected": false,
"text": "string s = \"<markup><div>Text</div><br /><br /></markup>\";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(s);\n\nConsole.WriteLine(doc.InnerXml);\n\nXmlElement markup = doc[\"markup\"];\nint childCount = markup.ChildNodes.Count;\nfor (int i = childCount -1; i >= 0; i--)\n{\n if (markup.ChildNodes[i].Name.ToLower() == \"br\")\n {\n markup.RemoveChild(markup.ChildNodes[i]);\n }\n else\n {\n break;\n }\n}\nConsole.WriteLine(\"---\");\nConsole.WriteLine(markup.InnerXml); \nConsole.ReadKey();\n"
},
{
"answer_id": 135260,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "static class StringExtensions\n{\n public static string TrimEnd(this string s, string remove)\n {\n if (s.EndsWith(remove))\n {\n return s.Substring(0, s.Length - remove.Length);\n }\n return s;\n }\n}\n Debug.Assert(\"abc\".TrimEnd(\"<br>\") == \"abc\");\n Debug.Assert(\"abc<br>\".TrimEnd(\"<br>\") == \"abc\");\n Debug.Assert(\"<br>abc\".TrimEnd(\"<br>\") == \"<br>abc\");\n <BR> </BR>"
},
{
"answer_id": 135340,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 2,
"selected": false,
"text": "public static Regex regex = new Regex(\n @\"(?:\\<br[^>]*\\>)*$\",\n RegexOptions.IgnoreCase\n | RegexOptions.CultureInvariant\n | RegexOptions.IgnorePatternWhitespace\n | RegexOptions.Compiled\n);\nregex.Replace(text, string.Empty);\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
135,173
|
<p>I have a table that holds only two columns - a ListID and PersonID. When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person.</p>
<p>Ideally, I would like to call something simple like</p>
<pre><code>UPDATE MailingListSubscription
SET PersonID = @DestPerson
WHERE PersonID = @SourcePerson
</code></pre>
<p>However, if the destination person already exists in this table with the same ListID as the source person, a duplicate entry will be made. How can I perform this action without creating duplicated entries? (ListID, PersonID is the primary key)</p>
<p>EDIT: Multiple ListIDs are used. If SourcePerson is assigned to ListIDs 1, 2, and 3, and DestinationPerson is assigned to ListIDs 3 and 4, then the end result needs to have four rows - DestinationPerson assigned to ListID 1, 2, 3, and 4.</p>
|
[
{
"answer_id": 135252,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "--out with the bad\nDELETE\nFROM MailingListSubscription\nWHERE PersonId = @SourcePerson\n and ListID in (SELECT ListID FROM MailingListSubscription WHERE PersonID = @DestPerson)\n\n--update the rest (good)\nUPDATE MailingListSubscription\nSET PersonId = @DestPerson\nWHERE PersonId = @SourcePerson\n"
},
{
"answer_id": 135590,
"author": "Aheho",
"author_id": 21155,
"author_profile": "https://Stackoverflow.com/users/21155",
"pm_score": 0,
"selected": false,
"text": "Insert into MailingListSubscription\n(\n ListID,\n PersonID\n)\nSelect\n ListID,\n @DestPerson\nFrom\n MailingListSubscription as t1\nWhere\n PersonID = @SourcePerson and\n Not Exists\n (\n Select *\n From MailingListSubscription as t2\n Where\n PersonID = @DestPerson and\n t1.ListID = t2.ListID\n )\n\n\n\nDelete From MailingListSubscription\nWhere\n PersonID = @SourcePerson\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
] |
135,186
|
<p>I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.</p>
<p>Small coding examples like the ones linked to at <a href="http://www.csharp-station.com/HowTo/HttpWebFetch.aspx" rel="nofollow noreferrer">http://www.csharp-station.com/HowTo/HttpWebFetch.aspx</a> tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.</p>
<p>For the record, I'm not building a malicious and/or spam related product.</p>
<p>So how do I go read web pages that require a few steps of normal browsing to reach first?</p>
|
[
{
"answer_id": 135460,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 3,
"selected": false,
"text": " string uri = \"http://www.google.com/search\";\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);\n request.Method = \"POST\";\n request.ContentType = \"application/x-www-form-urlencoded\";\n\n // encode the data to POST:\n string postData = \"q=searchterm&hl=en\";\n byte[] encodedData = new ASCIIEncoding().GetBytes(postData);\n request.ContentLength = encodedData.Length;\n\n Stream requestStream = request.GetRequestStream();\n requestStream.Write(encodedData, 0, encodedData.Length);\n\n // send the request and get the response\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n\n // Do something with the response stream. As an example, we'll\n // stream the response to the console via a 256 character buffer\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n Char[] buffer = new Char[256];\n int count = reader.Read(buffer, 0, 256);\n while (count > 0)\n {\n Console.WriteLine(new String(buffer, 0, count));\n count = reader.Read(buffer, 0, 256);\n }\n } // reader is disposed here\n } // response is disposed here\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
135,203
|
<p>I have always wondered WHaT tHE <em>HecK?!?</em> is the difference between JScript and JavaScript.</p>
|
[
{
"answer_id": 35795222,
"author": "Shiraz",
"author_id": 422663,
"author_profile": "https://Stackoverflow.com/users/422663",
"pm_score": 2,
"selected": false,
"text": "\"string\".substr(-1) \"string\".substr(-1) \"string\"[0] \"string\"[0]"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
135,234
|
<p>What is the difference between <code>ref</code> and <code>out</code> parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?</p>
|
[
{
"answer_id": 135255,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 1,
"selected": false,
"text": "out ref out ref"
},
{
"answer_id": 135257,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 10,
"selected": true,
"text": "out ref int x;\nFoo(out x); // OK\n\nint y;\nFoo(ref y); // Error: y should be initialized before calling the method\n Ref out int.TryParse"
},
{
"answer_id": 135263,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 7,
"selected": false,
"text": "out ref [out] [in,out] out"
},
{
"answer_id": 135275,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 0,
"selected": false,
"text": "out"
},
{
"answer_id": 135292,
"author": "Jacob Proffitt",
"author_id": 1336,
"author_profile": "https://Stackoverflow.com/users/1336",
"pm_score": 0,
"selected": false,
"text": "private void newEmployee()\n{\n Person ceo = Person.FindCEO();\n doStuff(ref ceo);\n}\n\nprivate void doStuff(ref Person employee)\n{\n Person newGuy = new Person();\n employee = newGuy;\n}\n"
},
{
"answer_id": 135403,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 6,
"selected": false,
"text": "ref out ref out ref out // This is not C#\npublic (bool, string) GetWebThing(string name, ref Buffer paramBuffer);\n\n// This is C#\npublic bool GetWebThing(string name, ref Buffer paramBuffer, out string actualUrl);\n ref out ref out ref out ref out out"
},
{
"answer_id": 286170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "namespace outreftry\n{\n class outref\n {\n static void Main(string[] args)\n {\n yyy a = new yyy(); ;\n\n // u can try giving int i=100 but is useless as that value is not passed into\n // the method. Only variable goes into the method and gets changed its\n // value and comes out. \n int i; \n\n a.abc(out i);\n\n System.Console.WriteLine(i);\n }\n }\n class yyy\n {\n\n public void abc(out int i)\n {\n\n i = 10;\n\n }\n\n }\n}\n namespace outreftry\n{\n class outref\n {\n static void Main(string[] args)\n {\n yyy a = new yyy(); ;\n\n int i = 0;\n\n a.abc(ref i);\n\n System.Console.WriteLine(i);\n }\n }\n class yyy\n {\n\n public void abc(ref int i)\n {\n System.Console.WriteLine(i);\n i = 10;\n\n }\n\n }\n}\n 0\n 10\n"
},
{
"answer_id": 3000832,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": false,
"text": "ref out out ref"
},
{
"answer_id": 3000840,
"author": "Alan",
"author_id": 37843,
"author_profile": "https://Stackoverflow.com/users/37843",
"pm_score": 2,
"selected": false,
"text": "out ref"
},
{
"answer_id": 12914635,
"author": "Krishna Thota",
"author_id": 1113226,
"author_profile": "https://Stackoverflow.com/users/1113226",
"pm_score": 3,
"selected": false,
"text": "out ref ref int sampleData = 0; \nsampleMethod(ref sampleData);\n public static void Main() \n{ \n int i = 3; // Variable need to be initialized \n sampleMethod(ref i ); \n}\n\npublic static void sampleMethod(ref int sampleData) \n{ \n sampleData++; \n} \n out int sampleData; \n sampleMethod(out sampleData);\n public static void Main() \n{ \n int i, j; // Variable need not be initialized \n sampleMethod(out i, out j); \n} \npublic static int sampleMethod(out int sampleData1, out int sampleData2) \n{ \n sampleData1 = 10; \n sampleData2 = 20; \n return 0; \n} \n"
},
{
"answer_id": 14656920,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "out ref Out() out Out() Out() out out"
},
{
"answer_id": 43721946,
"author": "jpaugh",
"author_id": 712526,
"author_profile": "https://Stackoverflow.com/users/712526",
"pm_score": 0,
"selected": false,
"text": "out out ref ref"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
] |
135,243
|
<p>Haven't done ASP.NET development since VS 2003, so I'd like to save some time and learn from other's mistakes.</p>
<p>Writing a web services app, but not a WSDL/SOAP/etc. -- more like REST + XML. </p>
<p>Which of the many "New Item" options (Web Form, Generic Handler, ASP.NET Handler, etc.) makes the most sense if I want to handle different HTTP verbs, through the same URI, separately. In a perfect world, I'd like the dispatching done declaratively in the code rather than via web.config -- but if I'm making life too hard that way, I'm open to change.</p>
|
[
{
"answer_id": 135467,
"author": "NerdFury",
"author_id": 6146,
"author_profile": "https://Stackoverflow.com/users/6146",
"pm_score": 1,
"selected": false,
"text": "public enum HttpVerb\n{\n GET, POST, PUT, DELETE\n}\n [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=false)]\npublic class RestMethodAttribute: Attribute\n{\n private HttpVerb _verb;\n\n public RestMethodAttribute(HttpVerb verb)\n {\n _verb = verb;\n }\n\n public HttpVerb Verb\n {\n get { return _verb; }\n }\n}\n public class RestService: IHttpHandler\n{\n private readonly bool _isReusable = true;\n protected HttpContext _context;\n private IDictionary<HttpVerb, MethodInfo> _methods;\n\n public void ProcessRequest(HttpContext context)\n {\n _context = context;\n\n HttpVerb verb = (HttpVerb)Enum.Parse(typeof (HttpVerb), context.Request.HttpMethod);\n\n MethodInfo method = Methods[verb];\n\n method.Invoke(this, null);\n }\n\n private IDictionary<HttpVerb, MethodInfo> Methods\n {\n get\n {\n if(_methods == null)\n {\n _methods = new Dictionary<HttpVerb, MethodInfo>();\n BuildMethodsMap();\n }\n return _methods;\n }\n }\n\n private void BuildMethodsMap()\n {\n Type serviceType = this.GetType();\n MethodInfo[] methods = serviceType.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);\n\n foreach (MethodInfo info in methods)\n {\n RestMethodAttribute[] attribs =\n info.GetCustomAttributes(typeof(RestMethodAttribute), false) as RestMethodAttribute[];\n if(attribs == null || attribs.Length == 0)\n continue;\n\n HttpVerb verb = attribs[0].Verb;\n\n Methods.Add(verb, info);\n }\n\n }\n\n public bool IsReusable\n {\n get { return _isReusable; }\n }\n}\n public class MyRestService: RestService\n{\n [RestMethod(HttpVerb.GET)]\n public void HelloWorld()\n {\n _context.Current.Response.Write(\"Hello World\");\n _context.Current.Response.End();\n }\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
135,246
|
<p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<hr>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<hr>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 135267,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "int32_t int"
},
{
"answer_id": 135311,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 3,
"selected": true,
"text": "0x0000000C 0x0C000000"
},
{
"answer_id": 135360,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "int32_t"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16363/"
] |
135,262
|
<p>I'm programming in C for RAM limited embedded microcontroller with RTOS.</p>
<p>I regularly break my code to short functions, but every function calling require to more stack memory.
Every task needs his stack, and this is one of the significant memory consumers in the project.</p>
<p>Is there an alternative to keep the code well organized and readable, still preserve the memory?</p>
|
[
{
"answer_id": 135282,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": false,
"text": "inline"
},
{
"answer_id": 135294,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "a() b() c() d() a() b() c() d() inline"
},
{
"answer_id": 143691,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 3,
"selected": false,
"text": "\nfoo(int a, int b, int c, int d)\n{\n...\n bar(int a, int b);\n}\n \nstruct my_params {\n int a;\n int b;\n int c;\n int d;\n};\nfoo(struct my_params* p)\n{\n ...\n bar(p);\n};\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22249/"
] |
135,296
|
<p>I frequently come across Windows programs that bundle in MSVCRT (or their more current equivalents) with the program executables. On a typical PC, I would find many copies of the same .DLL's. My understanding is that MSVCRT is the C runtime library, somewhat analogous to glibc/libc.so under *nix.</p>
<p>Why do Windows programs have to bring along their C libraries with them, instead of just sharing the system-wide libc?</p>
<hr />
<p>Update: thanks to Shog9, I started to read about SxS, which has further opened up my eyes to the DLL linkage issues (DLL Hell) - <a href="https://web.archive.org/web/20160305220537/http://blogs.msdn.com/b/martynl/archive/2005/10/13/480880.aspx" rel="nofollow noreferrer">Link</a> is one useful intro to the issue...</p>
|
[
{
"answer_id": 6442130,
"author": "cHao",
"author_id": 319403,
"author_profile": "https://Stackoverflow.com/users/319403",
"pm_score": 4,
"selected": false,
"text": "kernel32"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22329/"
] |
135,303
|
<p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
|
[
{
"answer_id": 135318,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 6,
"selected": true,
"text": "A if C else B\n stringValue = otherString or defaultString\n"
},
{
"answer_id": 135342,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 1,
"selected": false,
"text": "if otherString:\n stringValue = otherString\nelse:\n stringValue = defaultString\n"
},
{
"answer_id": 135354,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": -1,
"selected": false,
"text": "result = question and firstanswer or secondanswer\n result = choice == 7 and \"Seven\" or \"Another Choice\"\n"
},
{
"answer_id": 135450,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "if otherString:\n stringValue = otherString\nelse:\n stringValue = defaultString\n ?: if C = if cond then A else B\n if"
},
{
"answer_id": 135471,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "IsDefaultOrNull IsNullOrEmpty string stringValue = otherString ?? defaultString;\n otherString null"
},
{
"answer_id": 135889,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": -1,
"selected": false,
"text": "stringValue = otherString.blank? ? defaultString : otherString;\n blank?"
},
{
"answer_id": 135907,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 0,
"selected": false,
"text": "finalString = get_override() or defaultString\n"
},
{
"answer_id": 1601685,
"author": "ThomasH",
"author_id": 127465,
"author_profile": "https://Stackoverflow.com/users/127465",
"pm_score": 1,
"selected": false,
"text": " (condExp and [thenExp] or [elseExp])[0]\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
] |
135,314
|
<p>What is the fastest list implementation (in java) in a scenario where the list will be created one element at a time then at a later point be read one element at a time? The reads will be done with an iterator and then the list will then be destroyed.<br>
I know that the Big O notation for get is O(1) and add is O(1) for an ArrayList, while LinkedList is O(n) for get and O(1) for add. Does the iterator behave with the same Big O notation?</p>
|
[
{
"answer_id": 135358,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "LinkedList List<Object> list = new LinkedList<Object>();\nfor (int i = 0; i < list.size(); i++) {\n list.get(i);\n}\n i LinkedList Iterator for for (Object o : list) {\n // ...\n}\n ArrayList"
},
{
"answer_id": 135380,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": true,
"text": "ArrayList ArrayList ArrayList LinkedList ArrayList LinkedList ArrayList ArrayList"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13491/"
] |
135,317
|
<p>When running a CherryPy app it will send server name tag something like CherryPy/version.
Is it possible to rename/overwrite that from the app without modifying CherryPy so it will show something else? </p>
<p>Maybe something like MyAppName/version (CherryPy/version) </p>
|
[
{
"answer_id": 135644,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 2,
"selected": false,
"text": "def __init__(self):\n self.status = None\n self.header_list = None\n self._body = []\n self.time = time.time()\n\n self.headers = http.HeaderMap()\n # Since we know all our keys are titled strings, we can\n # bypass HeaderMap.update and get a big speed boost.\n dict.update(self.headers, {\n \"Content-Type\": 'text/html',\n \"Server\": \"CherryPy/\" + cherrypy.__version__,\n \"Date\": http.HTTPDate(self.time),\n })\n class MyResponse(Response):\n\n def __init__(self):\n Response.__init__(self)\n dict.update(self.headers, {\n \"Server\": \"MyServer/1.0\",\n })\n\nRespObject = MyResponse()\nprint RespObject.headers[\"Server\"]\n"
},
{
"answer_id": 208792,
"author": "daniels",
"author_id": 9789,
"author_profile": "https://Stackoverflow.com/users/9789",
"pm_score": 4,
"selected": true,
"text": "import cherrypy\nfrom cherrypy import _cpwsgi_server \nclass HelloWorld(object):\n def index(self):\n return \"Hello World!\"\n index.exposed = True\n\nserverTag = \"MyApp/%s (CherryPy/%s)\" % (\"1.2.3\", cherrypy.__version__)\n_cpwsgi_server.CPWSGIServer.environ['SERVER_SOFTWARE'] = serverTag\ncherrypy.config.update({'tools.response_headers.on': True,\n 'tools.response_headers.headers': [('Server', serverTag)]})\ncherrypy.quickstart(HelloWorld())\n"
},
{
"answer_id": 15035521,
"author": "Baxter",
"author_id": 184822,
"author_profile": "https://Stackoverflow.com/users/184822",
"pm_score": 3,
"selected": false,
"text": "[/] \nresponse.headers.server = \"CherryPy Dev01\"\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] |
135,330
|
<p>Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in</p>
<p>For example:</p>
<pre><code>a[1]=2;
a[2]=3;
</code></pre>
<p><code>BuiltInIDoNotKnowOf[a]</code> returns <code>{1,2}</code></p>
|
[
{
"answer_id": 138033,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "a[1] = 2\na[2] = 3\na[3] = 5\na[6] = 8\nPart[DownValues[a], All, 1, 1, 1]\n"
},
{
"answer_id": 154704,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 5,
"selected": false,
"text": "keys() a[1] = 2 keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *)\n keys = DownValues[#][[All,1,1,1]]&; (* Keys of a hash/dictionary. *)\n keys[a] a /@ keys[a] a[1,2]=5; a[3,4]=6 SetAttributes[removeHead, {HoldAll}];\nremoveHead[h_[args___]] := {args}\nkeys[f_] := removeHead @@@ DownValues[f][[All,1]]\n {{1,2}, {3,4}} a @@@ keys[a] DownValues Sort@keys[f] keys = DownValues[#,Sort->False][[All,1,1,1]]&;\n Sort DownValues fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n-1] + fib[n-2]\n fib[n_] := fib[n] = fib[n-1] + fib[n-2]\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279/"
] |
135,339
|
<p>Within an n-tier app that makes use of a WCF service to interact with the database, what is the best practice way of making use of LinqToSql classes throughout the app?</p>
<p>I've seen it done a couple of different ways but they seemed like they burned a lot of hours creating extra interfaces, message classes, and the like which reduces the benefit you get from not having to write your data access code.</p>
<p>Is there a good way to do it currently? Are we stuck waiting for the Entity Framework?</p>
|
[
{
"answer_id": 138033,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "a[1] = 2\na[2] = 3\na[3] = 5\na[6] = 8\nPart[DownValues[a], All, 1, 1, 1]\n"
},
{
"answer_id": 154704,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 5,
"selected": false,
"text": "keys() a[1] = 2 keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *)\n keys = DownValues[#][[All,1,1,1]]&; (* Keys of a hash/dictionary. *)\n keys[a] a /@ keys[a] a[1,2]=5; a[3,4]=6 SetAttributes[removeHead, {HoldAll}];\nremoveHead[h_[args___]] := {args}\nkeys[f_] := removeHead @@@ DownValues[f][[All,1]]\n {{1,2}, {3,4}} a @@@ keys[a] DownValues Sort@keys[f] keys = DownValues[#,Sort->False][[All,1,1,1]]&;\n Sort DownValues fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n-1] + fib[n-2]\n fib[n_] := fib[n] = fib[n-1] + fib[n-2]\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860358/"
] |
135,347
|
<p>When should you NOT use a singleton class although it might be very tempting to do so? It would be very nice if we had a list of most common instances of 'singletonitis' that we should take care to avoid.</p>
|
[
{
"answer_id": 135389,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 0,
"selected": false,
"text": "// Its our database! We'll never need another\nclass Database\n{\n};\n Database ourDb;\nDatabase otherDb;\n // Copy-pasted from our home-grown database.\nclass OtherGuysDatabase\n{\n};\n"
},
{
"answer_id": 135465,
"author": "JC.",
"author_id": 3615,
"author_profile": "https://Stackoverflow.com/users/3615",
"pm_score": 1,
"selected": false,
"text": "IService service = IoC.GetImplementationOf<IService>();\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
] |
135,373
|
<p>I've always struggled with how to best include classes into my php code. Pathing is usually an issue but a few minutes ago i found <a href="https://stackoverflow.com/questions/4369/how-to-include-php-files-that-require-an-absolute-path">this question</a> which dramatically helps that. Now I'm reading about __autoload and thinking that it could make the process of developing my applications much easier. The problem is i like to maintain folder structure to separate areas of functionality as opposed to throwing everything into a general /lib folder. So if i override autoload to do a deep search of a class folder including all subfolders, what performance hits can i expect?</p>
<p>Obviously this will depend on scale, depth of the folder structure and number of classes but generally I'm asking on a medium scale project will it cause problems. </p>
|
[
{
"answer_id": 135867,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 1,
"selected": false,
"text": "function __autoload($classname)\n{\n try\n {\n if (class_exists($classname, false) OR interface_exists($classname, false))\n {\n return;\n }\n\n $class = split('_', strtolower(strval($classname)));\n\n if (array_shift($class) != 'majyk')\n {\n throw new Exception('Autoloader tried to load a class that does not belong to us ( ' . $classname . ' )');\n }\n\n switch (count($class))\n {\n case 1: // Core Class - matches Majyk_Foo - include /core/class_foo.php\n $file = MAJYK_DIR . 'core/class_' . $class[0] . '.php';\n break;\n\n case 2: // Subclass - matches Majyk_Foo_Bar - includes /foo/class_bar.php\n $file = MAJYK_DIR . $class[0] . '/class_' . $class[1] . '.php';\n break;\n\n default:\n throw new Exception('Unknown Class Name ( ' . $classname .' )');\n return false;\n }\n\n if (file_exists($file))\n {\n require_once($file);\n\n if (!class_exists($classname, false) AND !interface_exists($classname, false))\n {\n throw new Exception('Class cannot be found ( ' . $classname . ' )');\n }\n }\n else\n {\n throw new Exception('Class File Cannot be found ( ' . str_replace(MAJYK_DIR, '', $file) . ' )');\n }\n\n }\n catch (Exception $e)\n {\n // spl_autoload($classname);\n echo $e->getMessage();\n }\n\n}\n function autoload_foo($classname)\n{\n require_once('foo/' . $classname . '.php');\n}\n\nfunction autoload_bar($classname)\n{\n require_once('bar/' . $classname . '.php');\n}\n\nspl_autoload_register('autoload_foo');\nspl_autoload_register('autoload_bar');\nspl_autoload_register('spl_autoload'); // Default SPL Autoloader\n"
},
{
"answer_id": 136958,
"author": "dcousineau",
"author_id": 20265,
"author_profile": "https://Stackoverflow.com/users/20265",
"pm_score": 0,
"selected": false,
"text": "<?php\n//...\nforeach( $paths as $path )\n{\n if( file_exists($path . $classNameToFilePath) )\n include $path . $classNameToFilePath;\n}\n//...\n?>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7018/"
] |
135,375
|
<p>I have a <code>ListBox</code> <code>DataTemplate</code> in WPF. I want one item to be tight against the left side of the <code>ListBox</code> and another item to be tight against the right side, but I can't figure out how to do this.</p>
<p>So far I have a <code>Grid</code> with three columns, the left and right ones have content and the center is a placeholder with it's width set to "*". Where am I going wrong?</p>
<p>Here is the code:</p>
<pre><code><DataTemplate x:Key="SmallCustomerListItem">
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<WrapPanel HorizontalAlignment="Stretch" Margin="0">
<!--Some content here-->
<TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/>
</WrapPanel>
<ListBox ItemsSource="{Binding Path=PhoneNumbers}" Grid.Column="2" d:DesignWidth="100" d:DesignHeight="50"
Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
</code></pre>
|
[
{
"answer_id": 135741,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "Grid ListBox ItemsPanel VirtualizingStackPanel ListBox.ItemsPanel ColumnDefinition \"*\" HorizontalAlignment=\"Left\" WrapPanel HorizontalAlignment=\"Right\" ListBox ListBox DataTemplate"
},
{
"answer_id": 135750,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 2,
"selected": false,
"text": "WrapPanel ListBox WrapPanel ListBox DockPanel Grid <DockPanel>\n <WrapPanel DockPanel.Dock=\"Left\"></WrapPanel>\n <ListBox DockPanel.Dock=\"Right\"></ListBox>\n</DockPanel>\n WrapPanel ListBox"
},
{
"answer_id": 135848,
"author": "Phobis",
"author_id": 19854,
"author_profile": "https://Stackoverflow.com/users/19854",
"pm_score": 1,
"selected": false,
"text": "Grid ColumnDefinition <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\"/>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"Auto\"/>\n </Grid.ColumnDefinitions>\n Grid DockPanel <DockPanel>\n <WrapPanel DockPanel.Dock=\"Left\">\n <!--Some content here-->\n <TextBlock Text=\"{Binding Path=LastName}\" TextWrapping=\"Wrap\" FontSize=\"24\"/>\n <TextBlock Text=\", \" TextWrapping=\"Wrap\" FontSize=\"24\"/>\n <TextBlock Text=\"{Binding Path=FirstName}\" TextWrapping=\"Wrap\" FontSize=\"24\"/>\n </WrapPanel>\n <ListBox DockPanel.Dock=\"Right\" ItemsSource=\"{Binding Path=PhoneNumbers}\" \n Margin=\"8,0\" Background=\"Transparent\" BorderBrush=\"Transparent\" IsHitTestVisible=\"False\"/>\n <TextBlock />\n </DockPanel>\n TextBlock \"DockPanel.Dock\""
},
{
"answer_id": 135951,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 8,
"selected": true,
"text": "HorizontalContentAlignment=\"Stretch\"\n ListBox"
},
{
"answer_id": 4699138,
"author": "Taeke",
"author_id": 576650,
"author_profile": "https://Stackoverflow.com/users/576650",
"pm_score": 5,
"selected": false,
"text": "<Grid.Width>\n <Binding Path=\"ActualWidth\" \n RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}\" />\n</Grid.Width>\n"
},
{
"answer_id": 12820912,
"author": "vancutterromney",
"author_id": 912207,
"author_profile": "https://Stackoverflow.com/users/912207",
"pm_score": 2,
"selected": false,
"text": "ScrollViewer.HorizontalScrollBarVisibility=\"Hidden\" ListBox <ListBox Width=\"100\" ScrollViewer.HorizontalScrollBarVisibility=\"Hidden\"> \n <Label Content=\"{Binding Path=., Mode=OneWay}\" HorizontalContentAlignment=\"Stretch\" Height=\"30\" Margin=\"-4,0,0,0\" BorderThickness=\"0.5\" BorderBrush=\"Black\" FontFamily=\"Calibri\" >\n <Label.Width>\n <Binding Path=\"Width\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}\" />\n </Label.Width>\n </Label>\n</ListBox >\n"
},
{
"answer_id": 40697569,
"author": "BCA",
"author_id": 1628429,
"author_profile": "https://Stackoverflow.com/users/1628429",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Value converter that adjusts the value of a double according to min and max limiting values, as well as an offset. These values are set by object configuration, handled in XAML resource definition.\n/// </summary>\n[ValueConversion(typeof(double), typeof(double))]\npublic sealed class DoubleLimiterConverter : IValueConverter\n{\n /// <summary>\n /// Minimum value, if set. If not set, there is no minimum limit.\n /// </summary>\n public double? Min { get; set; }\n\n /// <summary>\n /// Maximum value, if set. If not set, there is no minimum limit.\n /// </summary>\n public double? Max { get; set; }\n\n /// <summary>\n /// Offset value to be applied after the limiting is done.\n /// </summary>\n public double Offset { get; set; }\n\n public static double _defaultFailureValue = 0;\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null || !(value is double))\n return _defaultFailureValue;\n\n double dValue = (double)value;\n double minimum = Min.HasValue ? Min.Value : double.NegativeInfinity;\n double maximum = Max.HasValue ? Max.Value : double.PositiveInfinity;\n double retVal = dValue.LimitToRange(minimum, maximum) + Offset;\n return retVal;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n <ListBox.Resources>\n <con:DoubleLimiterConverter x:Key=\"conDoubleLimiter\" Min=\"450\" Offset=\"-2\"/>\n</ListBox.Resources>\n <Grid.Width>\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}\" Converter=\"{StaticResource conDoubleLimiter}\" />\n</Grid.Width>\n"
},
{
"answer_id": 44710028,
"author": "Kevin Hilt",
"author_id": 5178913,
"author_profile": "https://Stackoverflow.com/users/5178913",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Markup;\n\nnamespace Converters\n{\n public class ListBoxItemWidthConverter : MarkupExtension, IValueConverter\n {\n private static ListBoxItemWidthConverter _instance;\n\n #region IValueConverter Members\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return System.Convert.ToInt32(value) - SystemParameters.VerticalScrollBarWidth;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n return _instance ?? (_instance = new ListBoxItemWidthConverter());\n }\n }\n}\n xmlns:converters=\"clr-namespace:Converters\"\n <Grid.Width>\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}\" Converter=\"{converters:ListBoxItemWidthConverter}\"/>\n</Grid.Width>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100/"
] |
135,412
|
<p>I need to build a prototype for an intranet website, and I want to focus on usability (layout, navigability, etc) and leave the theme for later (I have very bad taste, so this will probably be done by someone else)</p>
<p>I know about ASP.NET's capability of switching themes instantly, but how do I have to design the WebForms for it to be easy later? </p>
<ul>
<li>Should I create controls with a class attribute pointing to something that will exist in the future css? </li>
<li>Or do I simply create the controls without worrying about this and it'll be handled easily when we create the theme?</li>
</ul>
|
[
{
"answer_id": 136239,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": false,
"text": " <div class=\"ButtonContainer\">\n <asp:linkbutton runat=\"Server\" cssclass=\"Button Cancel\" command=\"Save\" text=\"Save\" />\n <asp:linkbutton runat=\"Server\" cssclass=\"Button Save\" command=\"Cancel\" text=\"Cancel\" />\n </div>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
135,443
|
<p>There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:</p>
<pre><code>MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });
</code></pre>
<p>In this case, <code>GetMethod()</code> will not return private methods. What <code>BindingFlags</code> do I need to supply to <code>GetMethod()</code> so that it can locate private methods?</p>
|
[
{
"answer_id": 135455,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "BindingFlags.NonPublic GetMethod"
},
{
"answer_id": 135482,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 10,
"selected": true,
"text": "GetMethod MethodInfo dynMethod = this.GetType().GetMethod(\"Draw_\" + itemType, \n BindingFlags.NonPublic | BindingFlags.Instance);\ndynMethod.Invoke(this, new object[] { methodParams });\n"
},
{
"answer_id": 135555,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 6,
"selected": false,
"text": "BindingFlags.NonPublic BindingFlags.Instance MethodInfo dynMethod = this.GetType().GetMethod(\"Draw_\" + itemType, \n BindingFlags.NonPublic | BindingFlags.Instance);\n"
},
{
"answer_id": 25415496,
"author": "cod3monk3y",
"author_id": 1174169,
"author_profile": "https://Stackoverflow.com/users/1174169",
"pm_score": 6,
"selected": false,
"text": "static class AccessExtensions\n{\n public static object call(this object o, string methodName, params object[] args)\n {\n var mi = o.GetType ().GetMethod (methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );\n if (mi != null) {\n return mi.Invoke (o, args);\n }\n return null;\n }\n}\n class Counter\n {\n public int count { get; private set; }\n void incr(int value) { count += value; }\n }\n\n [Test]\n public void making_questionable_life_choices()\n {\n Counter c = new Counter ();\n c.call (\"incr\", 2); // \"incr\" is private !\n c.call (\"incr\", 3);\n Assert.AreEqual (5, c.count);\n }\n"
},
{
"answer_id": 41529500,
"author": "Owen James",
"author_id": 2736798,
"author_profile": "https://Stackoverflow.com/users/2736798",
"pm_score": 5,
"selected": false,
"text": "obj.GetType().GetTypeInfo().GetDeclaredMethod(\"MethodName\").Invoke(obj, yourArgsHere);\n public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)\n{\n var type = typeof(T);\n var method = type.GetTypeInfo().GetDeclaredMethod(methodName);\n return method.Invoke(obj, args);\n}\n obj T await (Task) obj.InvokeMethod(…)"
},
{
"answer_id": 43509885,
"author": "Fab",
"author_id": 5328150,
"author_profile": "https://Stackoverflow.com/users/5328150",
"pm_score": 4,
"selected": false,
"text": "// The following should be done once since this does some reflection\nvar method = this.GetType().GetMethod(\"Draw_\" + itemType, \n BindingFlags.NonPublic | BindingFlags.Instance);\n\n// Here we create a Func that targets the instance of type which has the \n// Draw_ItemType method\nvar draw = (Func<TInput, Output[]>)_method.CreateDelegate(\n typeof(Func<TInput, TOutput[]>), this);\n draw MethodInfo.Invoke draw Func var res = draw(methodParams);\n"
},
{
"answer_id": 48680544,
"author": "Maksim Shamihulau",
"author_id": 836723,
"author_profile": "https://Stackoverflow.com/users/836723",
"pm_score": 2,
"selected": false,
"text": "public static object InvokeMethod(object obj, string methodName, params object[] methodParams)\n{\n var methodParamTypes = methodParams?.Select(p => p.GetType()).ToArray() ?? new Type[] { };\n var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;\n MethodInfo method = null;\n var type = obj.GetType();\n while (method == null && type != null)\n {\n method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, null);\n type = type.BaseType;\n }\n\n return method?.Invoke(obj, methodParams);\n}\n"
},
{
"answer_id": 50480209,
"author": "T.S.",
"author_id": 1704458,
"author_profile": "https://Stackoverflow.com/users/1704458",
"pm_score": 0,
"selected": false,
"text": "var mi = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance );\n mi == null"
},
{
"answer_id": 67282411,
"author": "urglas",
"author_id": 15775993,
"author_profile": "https://Stackoverflow.com/users/15775993",
"pm_score": 1,
"selected": false,
"text": "this.GetType().GetMethod(\"PrivateTestMethod\", BindingFlags.Instance | BindingFlags.NonPublic)\n typeof(CurrentClass).GetMethod(\"PrivateTestMethod\", BindingFlags.Instance | BindingFlags.NonPublic)\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8223/"
] |
135,445
|
<p>I tried to use DriveInfo.IsReady, but it returns false if an unformatted floppy is in the drive.</p>
|
[
{
"answer_id": 135763,
"author": "Jonas Engström",
"author_id": 7634,
"author_profile": "https://Stackoverflow.com/users/7634",
"pm_score": 3,
"selected": true,
"text": "SetLastError(0);\nHANDLE h = CreateFile(\"\\\\\\\\.\\\\A:\", ...);\nif (!ReadFile(h, buf, 512, &bytes_read, 0))\n{\n DWORD err = GetLastError();\n}\n"
},
{
"answer_id": 136211,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "bool MyDll::Class1::HasFloppy( wchar_t driveLetter ) {\nwchar_t path[] = L\"\\\\\\\\.\\\\A:\";\npath[ 4 ] = driveLetter;\n\nSetLastError( 0 );\nHANDLE drive = CreateFile( path, //__in LPCTSTR lpFileName,\n GENERIC_READ, //__in DWORD dwDesiredAccess,\n 0, //__in DWORD dwShareMode,\n 0, //__in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n OPEN_EXISTING, //__in DWORD dwCreationDisposition,\n 0, //__in DWORD dwFlagsAndAttributes,\n 0 //__in_opt HANDLE hTemplateFile\n);\n\nDWORD bytes_read;\nchar buf[ 512 ];\nDWORD err( 0 );\nif( !ReadFile( drive, buf, 512, &bytes_read, 0 ) )\n err = GetLastError();\n\nCloseHandle( drive );\nreturn err != ERROR_NOT_READY;\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
135,448
|
<p>How do I check if an object has a specific property in JavaScript?</p>
<p>Consider:</p>
<pre><code>x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
</code></pre>
<p>Is that the best way to do it?</p>
|
[
{
"answer_id": 135466,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": false,
"text": "Object.prototype.hasOwnProperty.call(x, 'key') x hasOwnProperty typeof x.foo != 'undefined'"
},
{
"answer_id": 135475,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 6,
"selected": false,
"text": "if (x.key !== undefined)\n Object.prototype.hasOwnProperty = function(property) {\n return this[property] !== undefined;\n};\n\nx = {'key': 1};\n\nif (x.hasOwnProperty('key')) {\n alert('have key!');\n}\n\nif (!x.hasOwnProperty('bar')) {\n alert('no bar!');\n}\n Object.prototype.hasOwnProperty = function(property) {\n return typeof this[property] !== 'undefined';\n};\n"
},
{
"answer_id": 135514,
"author": "sheats",
"author_id": 4915,
"author_profile": "https://Stackoverflow.com/users/4915",
"pm_score": 4,
"selected": false,
"text": "if (x.hasOwnProperty('key'))\n if (x.key) // Quick and dirty, but it does the same thing as below.\n\nif (x.key !== undefined)\n"
},
{
"answer_id": 135517,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "if(x.hasOwnProperty(\"key\")){\n // …\n}\n if(x.key){\n // …\n}\n x.key x.key === \"\""
},
{
"answer_id": 135568,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "hasOwnProperty obj.hasOwnProperty undefined if (typeof(x.attribute) !== 'undefined')\n undefined undefined (function (undefined) {\n … your code …\n if (x.attribute !== undefined)\n … mode code …\n})();\n"
},
{
"answer_id": 136411,
"author": "John Resig",
"author_id": 6524,
"author_profile": "https://Stackoverflow.com/users/6524",
"pm_score": 12,
"selected": true,
"text": "Object.hasOwn() Object.hasOwn() Object.hasOwnProperty() Object.create(null) hasOwnProperty() Object.prototype.hasOwnProperty() Object.hasOwn() const object1 = {\n prop: 'exists'\n};\n\nconsole.log(Object.hasOwn(object1, 'prop'));\n// expected output: true\n typeof this[property] x.key object.hasOwnProperty prop in object hasOwnProperty var obj = {\n a: undefined,\n b: null,\n c: false\n};\n\n// a, b, c all found\nfor ( var prop in obj ) {\n document.writeln( \"Object1: \" + prop );\n}\n\nfunction Class(){\n this.a = undefined;\n this.b = null;\n this.c = false;\n}\n\nClass.prototype = {\n a: undefined,\n b: true,\n c: true,\n d: true,\n e: true\n};\n\nvar obj2 = new Class();\n\n// a, b, c, d, e found\nfor ( var prop in obj2 ) {\n document.writeln( \"Object2: \" + prop );\n}\n\nfunction hasOwnProperty(obj, prop) {\n var proto = obj.__proto__ || obj.constructor.prototype;\n return (prop in obj) &&\n (!(prop in proto) || proto[prop] !== obj[prop]);\n}\n\nif ( Object.prototype.hasOwnProperty ) {\n var hasOwnProperty = function(obj, prop) {\n return obj.hasOwnProperty(prop);\n }\n}\n\n// a, b, c found in modern browsers\n// b, c found in Safari 2.0.1 and older\nfor ( var prop in obj2 ) {\n if ( hasOwnProperty(obj2, prop) ) {\n document.writeln( \"Object2 w/ hasOwn: \" + prop );\n }\n}\n hasOwnProperty()"
},
{
"answer_id": 138428,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 5,
"selected": false,
"text": "hasOwnProperty hasOwnProperty undefined var o = {}\no.x = undefined\n\nvar a = o.hasOwnProperty('x') // a is true\nvar b = o.x === undefined // b is also true\n var o = {}\n\nvar a = o.hasOwnProperty('x') // a is now false\nvar b = o.x === undefined // b is still true\n hasOwnProperty !== undefined for..in __prototype__"
},
{
"answer_id": 11315692,
"author": "Brian M. Hunt",
"author_id": 19212,
"author_profile": "https://Stackoverflow.com/users/19212",
"pm_score": 8,
"selected": false,
"text": "_.has(x, 'key');\n Object.prototype.hasOwnProperty hasOwnProperty hasOwnProperty _.has function has(object, key) {\n return object ? hasOwnProperty.call(object, key) : false;\n}\n// hasOwnProperty = Object.prototype.hasOwnProperty\n"
},
{
"answer_id": 14664748,
"author": "Whisher",
"author_id": 356380,
"author_profile": "https://Stackoverflow.com/users/356380",
"pm_score": 8,
"selected": false,
"text": "var x = {\n 'key': 1\n};\n\nif ('key' in x) {\n console.log('has');\n}"
},
{
"answer_id": 16674373,
"author": "Gerard ONeill",
"author_id": 1331672,
"author_profile": "https://Stackoverflow.com/users/1331672",
"pm_score": 5,
"selected": false,
"text": "if ('prop' in obj) { }\n"
},
{
"answer_id": 22740939,
"author": "goonerify",
"author_id": 1445318,
"author_profile": "https://Stackoverflow.com/users/1445318",
"pm_score": 5,
"selected": false,
"text": "const x = {key: 1};\n in console.log(\"key\" in x);\n for - in for (const prop in x) {\n if (prop === \"key\") {\n //Do something\n }\n}\n for-in Object.getOwnPropertyNames(x);\n Reflect.has() console.log(Reflect.has(x, 'key'));\n// expected output: true\n\nconsole.log(Reflect.has(x, 'key2'));\n// expected output: false\n\nconsole.log(Reflect.has(object1, 'toString'));\n// expected output: true\n if (typeof x.key === \"undefined\") {\n console.log(\"undefined\");\n}\n typeof x.key undefined if (x.key === undefined) {\n console.log(\"undefined\");\n}\n undefined"
},
{
"answer_id": 30533729,
"author": "Jamie Hutber",
"author_id": 240363,
"author_profile": "https://Stackoverflow.com/users/240363",
"pm_score": 3,
"selected": false,
"text": "Object.keys array var noInfo = {};\nvar info = {something: 'data'};\n\nObject.keys(noInfo).length //returns 0 or false\nObject.keys(info).length //returns 1 or true\n"
},
{
"answer_id": 32767522,
"author": "rogopag",
"author_id": 355760,
"author_profile": "https://Stackoverflow.com/users/355760",
"pm_score": 3,
"selected": false,
"text": "if (prop in object) { // Do something }\n"
},
{
"answer_id": 38332171,
"author": "arkod",
"author_id": 1506301,
"author_profile": "https://Stackoverflow.com/users/1506301",
"pm_score": 2,
"selected": false,
"text": "var foo = {};\nfoo.bar = \"Yes, this is a proper value!\";\nif (!!foo.bar) {\n // member is set, do something\n}\n"
},
{
"answer_id": 40266120,
"author": "Wilt",
"author_id": 1697459,
"author_profile": "https://Stackoverflow.com/users/1697459",
"pm_score": 4,
"selected": false,
"text": "Reflect x = {'key': 1};\nReflect.has( x, 'key'); // returns true\n Reflect.has Reflect.has()"
},
{
"answer_id": 41184688,
"author": "davidhadas",
"author_id": 1931538,
"author_profile": "https://Stackoverflow.com/users/1931538",
"pm_score": 5,
"selected": false,
"text": "if (obj[x] !== undefined)\n if (obj.hasOwnProperty(x))\n function hasKey1(k,o) { return (x in obj); }\nfunction hasKey2(k,o) { return (obj[x]); }\nfunction hasKey3(k,o) { return (obj[x] !== undefined); }\nfunction hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }\nfunction hasKey5(k,o) { return (obj.hasOwnProperty(x)); }\n if (X in Obj)...\n hasKey1 execution time: 4.51 s\nhasKey2 execution time: 0.90 s\nhasKey3 execution time: 0.76 s\nhasKey4 execution time: 0.93 s\nhasKey5 execution time: 2.15 s\n if (obj.hasOwnProperty(x))... if (typeof(obj[x]) !== 'undefined')... if (obj[x])..."
},
{
"answer_id": 41220962,
"author": "Harm",
"author_id": 882899,
"author_profile": "https://Stackoverflow.com/users/882899",
"pm_score": 2,
"selected": false,
"text": "/**\nGets an argument from array or object.\nThe possible outcome:\n- If the key exists the value is returned.\n- If no key exists the default value is returned.\n- If no default value is specified an empty string is returned.\n@param obj The object or array to be searched.\n@param key The name of the property or key.\n@param defVal Optional default version of the command-line parameter [default \"\"]\n@return The default value in case of an error else the found parameter.\n*/\nfunction getSafeReflectArg( obj, key, defVal) {\n \"use strict\";\n var retVal = (typeof defVal === 'undefined' ? \"\" : defVal);\n if ( Reflect.has( obj, key) ) {\n return Reflect.get( obj, key);\n }\n return retVal;\n} // getSafeReflectArg\n"
},
{
"answer_id": 46221139,
"author": "John Anisere",
"author_id": 8581214,
"author_profile": "https://Stackoverflow.com/users/8581214",
"pm_score": 1,
"selected": false,
"text": "object.hasOwnProperty(property)"
},
{
"answer_id": 47175373,
"author": "vikram jeet singh",
"author_id": 4119501,
"author_profile": "https://Stackoverflow.com/users/4119501",
"pm_score": 2,
"selected": false,
"text": "{ hasOwnProperty: false } // Good\nvar obj = {\"bar\": \"here bar desc\"}\nconsole.log(Object.prototype.hasOwnProperty.call(obj, \"bar\"));\n\n// Best\nconst has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.\nconsole.log(has.call(obj, \"bar\"));"
},
{
"answer_id": 49899370,
"author": "Abdullah Danyal",
"author_id": 7909857,
"author_profile": "https://Stackoverflow.com/users/7909857",
"pm_score": 4,
"selected": false,
"text": "object.hasOwnProperty(key)) { hasOwnProperty: false } (Object.create(null)) Object.prototype.hasOwnProperty.call(object, key) const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.\nconsole.log(has.call(object, key));\n/* Or */\nimport has from 'has'; // https://www.npmjs.com/package/has\nconsole.log(has(object, key));\n"
},
{
"answer_id": 52170045,
"author": "Alex",
"author_id": 2732012,
"author_profile": "https://Stackoverflow.com/users/2732012",
"pm_score": 0,
"selected": false,
"text": "var isProperty = (objectname.keyname || \"\") ? true : false;\n"
},
{
"answer_id": 54196605,
"author": "Komal Bansal",
"author_id": 10150695,
"author_profile": "https://Stackoverflow.com/users/10150695",
"pm_score": 3,
"selected": false,
"text": "var obj = {a:1}\nconsole.log('a' in obj) // 1\nconsole.log(obj.hasOwnProperty('a')) // 2\nconsole.log(Boolean(obj.a)) // 3\n var obj = {\n a: 2,\n __proto__ : {b: 2}\n}\n\nconsole.log('b' in obj)\nconsole.log(Boolean(obj.b)) var obj = {\n a: 2,\n __proto__ : {b: 2}\n}\n\nconsole.log(obj.hasOwnProperty('b')) var obj = {\n b : undefined\n}\n\nconsole.log(Boolean(obj.b))\nconsole.log('b' in obj);"
},
{
"answer_id": 62774235,
"author": "Ntwari Clarance Liberiste",
"author_id": 11698819,
"author_profile": "https://Stackoverflow.com/users/11698819",
"pm_score": 3,
"selected": false,
"text": "hasOwnProperty() const hero = {\n name: 'Batman'\n};\n\nhero.hasOwnProperty('name'); // => true\nhero.hasOwnProperty('realName'); // => false\n in const hero = {\n name: 'Batman'\n};\n\n'name' in hero; // => true\n'realName' in hero; // => false\n undefined const hero = {\n name: 'Batman'\n};\n\nhero.name; // => 'Batman'\nhero.realName; // => undefined\n\n// So consider this\nhero.realName == undefined // => true (which means property does not exists in object)\nhero.name == undefined // => false (which means that property exists in object)\n"
},
{
"answer_id": 65343749,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "in has // SO https://stackoverflow.com/q/135448/860099\n\n\n// src: https://stackoverflow.com/a/14664748/860099\nfunction A(x) {\n return 'key' in x\n}\n\n// src: https://stackoverflow.com/a/11315692/860099\nfunction B(x) {\n return _.has(x, 'key')\n}\n\n// src: https://stackoverflow.com/a/40266120/860099\nfunction C(x) {\n return Reflect.has( x, 'key')\n}\n\n// src: https://stackoverflow.com/q/135448/860099\nfunction D(x) {\n return x.hasOwnProperty('key')\n}\n\n// src: https://stackoverflow.com/a/11315692/860099\nfunction E(x) {\n return Object.prototype.hasOwnProperty.call(x, 'key')\n}\n\n// src: https://stackoverflow.com/a/136411/860099\nfunction F(x) {\n function hasOwnProperty(obj, prop) {\n var proto = obj.__proto__ || obj.constructor.prototype;\n return (prop in obj) &&\n (!(prop in proto) || proto[prop] !== obj[prop]);\n }\n return hasOwnProperty(x,'key')\n}\n\n// src: https://stackoverflow.com/a/135568/860099\nfunction G(x) {\n return typeof(x.key) !== 'undefined'\n}\n\n// src: https://stackoverflow.com/a/22740939/860099\nfunction H(x) {\n return x.key !== undefined\n}\n\n// src: https://stackoverflow.com/a/38332171/860099\nfunction I(x) {\n return !!x.key\n}\n\n// src: https://stackoverflow.com/a/41184688/860099\nfunction J(x) {\n return !!x['key']\n}\n\n// src: https://stackoverflow.com/a/54196605/860099\nfunction K(x) {\n return Boolean(x.key)\n}\n\n\n// --------------------\n// TEST\n// --------------------\n\nlet x1 = {'key': 1};\nlet x2 = {'key': \"1\"};\nlet x3 = {'key': true};\nlet x4 = {'key': []};\nlet x5 = {'key': {}};\nlet x6 = {'key': ()=>{}};\nlet x7 = {'key': ''};\nlet x8 = {'key': 0};\nlet x9 = {'key': false};\nlet x10= {'key': undefined};\nlet x11= {'nokey': 1};\n\n\n\nlet b= x=> x ? 1:0;\n\nconsole.log(' 1 2 3 4 5 6 7 8 9 10 11');\n\n[A,B,C,D,E,F,G,H,I,J,K ].map(f=> { \n console.log(\n `${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} `\n )})\n \nconsole.log('\\nLegend: Columns (cases)');\nconsole.log('1. key = 1 ');\nconsole.log('2. key = \"1\" ');\nconsole.log('3. key = true ');\nconsole.log('4. key = [] ');\nconsole.log('5. key = {} ');\nconsole.log('6. key = ()=>{} ');\nconsole.log('7. key = \"\" ');\nconsole.log('8. key = 0 ');\nconsole.log('9. key = false ');\nconsole.log('10. key = undefined ');\nconsole.log('11. no-key '); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js\" integrity=\"sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==\" crossorigin=\"anonymous\"> </script>\n \nThis shippet only presents functions used in performance tests - it not perform tests itself!"
},
{
"answer_id": 66039801,
"author": "Nitin Jadhav",
"author_id": 741251,
"author_profile": "https://Stackoverflow.com/users/741251",
"pm_score": 0,
"selected": false,
"text": "hasOwnProperty() for(let key of Object.keys(stud)){} for(let key of Object.keys(stud)){\n console.log(key); // will only log object's Own properties\n}\n for-in with hasOwnProperty() function Student() {\n this.name = \"nitin\";\n}\n\nStudent.prototype = {\n grade: 'A'\n}\n\nlet stud = new Student();\n\n// for-in approach\nfor(let key in stud){\n if(stud.hasOwnProperty(key)){\n console.log(key); // only outputs \"name\"\n }\n} \n\n//Object.keys() approach\nfor(let key of Object.keys(stud)){\n console.log(key);\n}\n"
},
{
"answer_id": 66332561,
"author": "majurageerthan",
"author_id": 7765316,
"author_profile": "https://Stackoverflow.com/users/7765316",
"pm_score": 2,
"selected": false,
"text": "const object= {key1: 'data', key2: 'data2'};\n\nObject.keys(object).includes('key1') //returns true\n indexOf"
},
{
"answer_id": 67120164,
"author": "MD SHAYON",
"author_id": 8725395,
"author_profile": "https://Stackoverflow.com/users/8725395",
"pm_score": 1,
"selected": false,
"text": "const object1 = {};\nobject1.property1 = 42;\n\nconsole.log(object1.hasOwnProperty('property1'));\n// expected output: true\n\nconsole.log(object1.hasOwnProperty('toString'));\n// expected output: false\n\nconsole.log(object1.hasOwnProperty('hasOwnProperty'));\n// expected output: false\n"
},
{
"answer_id": 67810564,
"author": "Marco Balestra",
"author_id": 7592319,
"author_profile": "https://Stackoverflow.com/users/7592319",
"pm_score": 3,
"selected": false,
"text": "Object.keys(myObject).includes('myKey')\n myObject.hasOwnProperty('myKey')\n typeof myObject.myKey !== 'undefined'\n"
},
{
"answer_id": 68203057,
"author": "bristweb",
"author_id": 4481226,
"author_profile": "https://Stackoverflow.com/users/4481226",
"pm_score": 2,
"selected": false,
"text": "let obj1 = {prop:undefined};\nconsole.log(1,\"prop\" in obj1);\nconsole.log(1,obj1?.prop);\n\nlet obj2 = undefined;\n//console.log(2,\"prop\" in obj2); would throw because obj2 undefined\nconsole.log(2,\"prop\" in (obj2 ?? {}))\nconsole.log(2,obj2?.prop);\n\nlet obj3 = {prop:false};\nconsole.log(3,\"prop\" in obj3);\nconsole.log(3,!!obj3?.prop);\n\nlet obj4 = {prop:null};\nlet look = \"prop\"\nconsole.log(4,\"prop\" in obj4);\nconsole.log(4,obj4?.[look]);\n\nlet obj5 = {prop:true};\nconsole.log(5,\"prop\" in obj5);\nconsole.log(5,obj5?.prop === true);\n\nlet obj6 = {otherProp:true};\nlook = \"otherProp\"\nconsole.log(6,\"prop\" in obj6);\nconsole.log(6,obj6.look); //should have used bracket notation\n\nlet obj7 = {prop:\"\"};\nconsole.log(7,\"prop\" in obj7);\nconsole.log(7,obj7?.prop || \"empty\"); hasOwn"
},
{
"answer_id": 71533572,
"author": "nassim miled",
"author_id": 8945943,
"author_profile": "https://Stackoverflow.com/users/8945943",
"pm_score": 2,
"selected": false,
"text": "hasOwnProperty Object.hasOwn(obj, propKey)\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915/"
] |
135,451
|
<p>I want to create a list of methods to execute. Each method has the same signature.
I thought about putting delegates in a generic collection, but I keep getting this error:</p>
<blockquote>
<p>'method' is a 'variable' but is used like a 'method'</p>
</blockquote>
<p>In theory, here is what I would like to do:</p>
<pre><code>List<object> methodsToExecute;
int Add(int x, int y)
{ return x+y; }
int Subtract(int x, int y)
{ return x-y; }
delegate int BinaryOp(int x, int y);
methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));
foreach(object method in methodsToExecute)
{
method(1,2);
}
</code></pre>
<p>Any ideas on how to accomplish this?
Thanks!</p>
|
[
{
"answer_id": 135453,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "class Example\n{\n public delegate int AddDelegate(int x, int y);\n\n public List<AddDelegate> methods = new List<AddDelegate>();\n\n int Execute()\n {\n int sum = 0;\n foreach(AddDelegate method in methods)\n {\n sum+=method.Invoke(1, 2);\n }\n return sum;\n }\n}\n"
},
{
"answer_id": 135464,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 5,
"selected": true,
"text": "object BinaryOp delegate int BinaryOp(int x, int y);\n\nList<BinaryOp> methodsToExecute = new List<BinaryOp>();\n\nmethodsToExecute.add(Add);\nmethodsToExecute.add(Subtract);\n\nforeach(BinaryOp method in methodsToExecute)\n{\n method(1,2);\n}\n"
},
{
"answer_id": 135476,
"author": "David Alpert",
"author_id": 8997,
"author_profile": "https://Stackoverflow.com/users/8997",
"pm_score": 2,
"selected": false,
"text": "List<Func<int, int, int>> methodsToExecute = new List<Func<int, int, int>>();\n\nmethodsToExecute.Add(Subtract);\n\nmethodsToExecute.Add[0](1,2); // equivalent to Subtract(1,2)\n"
},
{
"answer_id": 135491,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 2,
"selected": false,
"text": "List<Func<int, int, int>> n = new List<Func<int, int, int>>();\n n.Add((x, y) => x + y);\n n.Add((x, y) => x - y);\n n.ForEach(f => f.Invoke(1, 2));\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8797/"
] |
135,458
|
<p>Suppose I have the following code:</p>
<pre><code>while(TRUE) {
pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(thread, NULL, someFunction, someArgument);
pthread_detach(*thread);
sleep(10);
}
</code></pre>
<p>Will the detached thread free the memory allocated by malloc, or is that something I now have to do?</p>
|
[
{
"answer_id": 135922,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 4,
"selected": true,
"text": "pthread_t thread;\npthread_create(&thread, NULL, someFunction, someArgument);\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/542226/"
] |
135,474
|
<p>For example:</p>
<pre><code>char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);
</code></pre>
<p>Are there any adverse side effects of doing this? </p>
|
[
{
"answer_id": 135486,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 2,
"selected": false,
"text": "free"
},
{
"answer_id": 135492,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 3,
"selected": false,
"text": "NULL"
},
{
"answer_id": 135547,
"author": "lillq",
"author_id": 2064,
"author_profile": "https://Stackoverflow.com/users/2064",
"pm_score": 3,
"selected": false,
"text": "free(myString);\nmyString = NULL;\n NULL free() NULL"
},
{
"answer_id": 137850,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": true,
"text": "free calloc malloc realloc free realloc"
},
{
"answer_id": 145150,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 1,
"selected": false,
"text": "#define my_free(x) do { free(x); x = NULL; } while (0)\n"
},
{
"answer_id": 3575324,
"author": "pinpinokio",
"author_id": 431858,
"author_profile": "https://Stackoverflow.com/users/431858",
"pm_score": -1,
"selected": false,
"text": "char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);\nchar * yourString = myString;\n\nif (myString)\n{\n free(myString);\n myString = NULL;\n}\n// Now this one is safe, because we keep to the rule for \n// setting pointers to NULL after deletion ...\nif (myString)\n{\n free(myString);\n myString = NULL;\n}\n\n// But what about this one:\nif (yourString)\n{\n free(yourString);\n yourString = NULL;\n}\n\n//?!? :)\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] |
135,478
|
<p>I have an ASP.NET web service which does some heavy lifting, like say,some file operations, or generating Excel Sheets from a bunch of crystal reports. I don't want to be blocked by calling this web service, so i want to make the web service call asynchronous. Also, I want to call this web service from a web page, and want some mechanism which will allow me to keep polling the server so that i can i can show some indicator of progress on the screen, like say, the number of files that have been processed. Please note that i do not want a notification on completion of the web method call, rather, i want a live progress status. How do i go about it?</p>
|
[
{
"answer_id": 135502,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 3,
"selected": true,
"text": "http://yourserver.com/app/jobstatus/4133/ text/plain"
},
{
"answer_id": 135592,
"author": "Carra",
"author_id": 21679,
"author_profile": "https://Stackoverflow.com/users/21679",
"pm_score": 2,
"selected": false,
"text": "//...\nprivate localhost.MyWebServiceService _myWebService = new localhost.MyWebServiceService ();\n_myWebService.processDelegate += ProgressUpdate;\n_myWebService.CallHeavyMethod();\n//...\n\nprivate void ProgressUpdate(object sender, ProgressEventArgs e)\n{\n double progress = ((double)e.ProcessedSize / (double)e.TotalSize) * 100.00;\n //Show Progress...\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
] |
135,518
|
<p>In WPF, we are creating custom controls that inherit from button with completely drawn-from-scratch xaml graphics. We have a border around the entire button xaml and we'd like to use that as the location for updating the background when MouseOver=True in a trigger. What we need to know is how do we update the background of the border in this button with a gradient when the mouse hovers over it?</p>
|
[
{
"answer_id": 135638,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": true,
"text": "ControlTemplate Border Name Button <Style\n TargetType=\"{x:Type Button}\">\n <Setter\n Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type Button}\">\n <Border Name=\"customBorder\"\n CornerRadius=\"5\"\n BorderThickness=\"1\"\n BorderBrush=\"Black\"\n Background=\"{StaticResource normalButtonBG}\">\n <ContentPresenter\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\" />\n </Border>\n <ControlTemplate.Triggers>\n <Trigger\n Property=\"IsMouseOver\"\n Value=\"True\">\n <Setter\n TargetName=\"customBorder\"\n Property=\"Background\"\n Value=\"{StaticResource hoverButtonBG}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n"
},
{
"answer_id": 135796,
"author": "Phobis",
"author_id": 19854,
"author_profile": "https://Stackoverflow.com/users/19854",
"pm_score": 0,
"selected": false,
"text": "<Style x:Key=\"ButtonTemplate\"\n TargetType=\"{x:Type Button}\">\n <Setter Property=\"Foreground\"\n Value=\"{StaticResource ButtonForeground}\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate\n TargetType=\"{x:Type Button}\">\n <Grid\n SnapsToDevicePixels=\"True\"\n Margin=\"0,0,0,0\">\n <Border Height=\"20\"\n x:Name=\"ButtonBorder\"\n BorderBrush=\"{DynamicResource BlackBorderBrush}\">\n <TextBlock x:Name=\"button\"\n TextWrapping=\"Wrap\"\n Text=\"{Binding Path=Content, RelativeSource={RelativeSource TemplatedParent}}\"\n SnapsToDevicePixels=\"True\"\n Foreground=\"#FFFFFFFF\"\n Margin=\"6,0,0,0\"\n VerticalAlignment=\"Center\"/>\n </Border>\n </Grid>\n <ControlTemplate.Triggers>\n <!-- Disabled -->\n <Trigger Property=\"IsMouseOver\"\n Value=\"True\">\n <Setter TargetName=\"ButtonBorder\"\n Property=\"Background\"\n Value=\"{DynamicResource ButtonBackgroundMouseOver}\" />\n <Setter TargetName=\"ButtonBorder\"\n Property=\"BorderBrush\"\n Value=\"{DynamicResource ButtonBorderMouseOver}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n <LinearGradientBrush x:Key=\"ButtonBackgroundMouseOver\"\n EndPoint=\"0.5,1\"\n StartPoint=\"0.5,0\">\n <GradientStop Color=\"#FF000000\"\n Offset=\"0.432\"/>\n <GradientStop Color=\"#FF808080\"\n Offset=\"0.9\"/>\n <GradientStop Color=\"#FF848484\"\n Offset=\"0.044\"/>\n <GradientStop Color=\"#FF787878\"\n Offset=\"0.308\"/>\n <GradientStop Color=\"#FF212121\"\n Offset=\"0.676\"/>\n</LinearGradientBrush>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21096/"
] |
135,530
|
<p>I have an index on columns A, B, C, D of table T</p>
<p>I have a query that pulls from T with A, B, C in the WHERE clause.</p>
<p>Will the index be used or will a separate index be needed that only includes A, B, C?</p>
|
[
{
"answer_id": 135570,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "WHERE A like '%x%'\n and B = 1\n and C = 1\n//\nWHERE A = 1\n OR B = 1\n OR C = 1\n//\nWHERE DateAdd(dd, 1, A) = '2008-01-01'\n AND B = 1\n AND C = 1\n"
},
{
"answer_id": 135683,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 1,
"selected": false,
"text": "SELECT Y FROM table WHERE A = alpha and B = beta and C = gamma \n\nSELECT Z FROM table WHERE A = alpha and B = beta and C = gamma \n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11780/"
] |
135,535
|
<p>I'm a PHPer, and am not writing object-oriented code.</p>
<p>What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP?</p>
|
[
{
"answer_id": 135656,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 3,
"selected": false,
"text": "Poll::Display()"
},
{
"answer_id": 135805,
"author": "moffdub",
"author_id": 10759,
"author_profile": "https://Stackoverflow.com/users/10759",
"pm_score": 3,
"selected": false,
"text": "sherry.changePhoneNumber();\nphoneCompany.assignNewPhoneNumberTo(sherry);\nsherry.receive(new PhoneNumber().withAreaCode(\"555\").withNumber(\"194-2677\"));\n"
},
{
"answer_id": 185777,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 3,
"selected": false,
"text": "if fileobjecttype == 'TIFF':\n data = <snip 30 lines of code to read and convert a TIFF file>\nelif fileobjecttype == 'PDF':\n data = <another 45 lines to read a PDF>\nelif fileobjecttype == 'PNG':\n data = <yep, another one>\n class PDFReader(GenericImageReader):\n def normalize(self):\n data = <45 lines to read a PDF>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
] |
135,573
|
<p>I have a project containing at least one DLL along with the executable output. I have added a Deployment Project to this solution, which asked me for a name and working directory upon creation like all projects.</p>
<p>I named this "MyProduc_Installer" and have been able to modify all aspects of the installation process except for changing the name of the installer itself. Throughout the install process, the user sees messages like "Welcome to the MyProduct_Installer Installer." Even in the Add/Remove Programs list, this is the application's ill conceived title.</p>
<p>How do I change this setting? I have tried right click/properties, as well as all the View options. I couldn't find anything in the assembly information for the executable project, or solution properties.</p>
<p>I have tried right-clicking on the project in the Explorer to change the properties, but here is what I see:</p>
<p><img src="https://sites.google.com/site/sizerfx/Home/properties.png?attredirects=0" alt="alt text"></p>
<p>There is no setting here to change the project title.</p>
|
[
{
"answer_id": 5468352,
"author": "CooPzZ",
"author_id": 323806,
"author_profile": "https://Stackoverflow.com/users/323806",
"pm_score": 0,
"selected": false,
"text": "<ProductName>xyz wrong name</ProductName>"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/414107/"
] |
135,591
|
<p>I've seen several products that will track the sales rank of an item on Amazon. Does Amazon have any web-services published that I can use to get the sales rank of a particular item? </p>
<p>I've looked through the AWS and didn't see anything of that nature.</p>
|
[
{
"answer_id": 135627,
"author": "Adam Hughes",
"author_id": 3863,
"author_profile": "https://Stackoverflow.com/users/3863",
"pm_score": 4,
"selected": true,
"text": "http://ecs.amazonaws.com/onca/xml?\nService=AWSECommerceService&\nAWSAccessKeyId=[AWS Access Key ID]&\nOperation=ItemLookup&\nItemId=0976925524&\nResponseGroup=SalesRank&\nVersion=2008-08-19\n <Item>\n <ASIN>0976925524</ASIN> \n <SalesRank>68</SalesRank> \n</Item>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4244/"
] |
135,600
|
<p>When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".</p>
<p>I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions. </p>
<p>But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.</p>
<p>How can I get the unblock to appear on my exe so I can test this functionality?</p>
|
[
{
"answer_id": 135924,
"author": "HitScan",
"author_id": 9490,
"author_profile": "https://Stackoverflow.com/users/9490",
"pm_score": 5,
"selected": true,
"text": "[ZoneTransfer]\nZoneId=3\n [ZoneTransfer]\nZoneId=3\n more Zone.Identifier.txt > file.exe:Zone.Identifier\n"
},
{
"answer_id": 267495,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "CoCreateInstance CLSID_PersistentZoneIdentifier IPersistFile IPersistFile::Load IZoneIdentifier IZoneIdentifier::GetId URLZONE_LOCAL_MACHINE URLZONE_INTERNET URLZONE sdk\\inc\\urlmon.h IZoneIdentifier::Remove IZoneIdentifier::SetId IPersistFile::Save"
},
{
"answer_id": 11018484,
"author": "alrutherford",
"author_id": 669504,
"author_profile": "https://Stackoverflow.com/users/669504",
"pm_score": 1,
"selected": false,
"text": "echo [ZoneTransfer] > Zone.Identifier\necho ZoneId=3 >> Zone.Identifier\nmore Zone.Identifier > %1:Zone.Identifier\n mark.bat myfile.txt\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
135,634
|
<p>In the (otherwise) excellent book <a href="http://www.gotw.ca/publications/c++cs.htm" rel="nofollow noreferrer">C++ Coding Standards</a>, Item 44, titled <strong>"Prefer writing nonmember nonfriend functions"</strong>, Sutter and Alexandrescu recommend that only functions that really need access to the members of a class be themselves members of that class. All other operations which can be written by using only member functions should not be part of the class. They should be nonmembers and nonfriends. The arguments are that:</p>
<ul>
<li>It promotes encapsulation, because there is less code that needs access to the internals of a class.</li>
<li>It makes writing function templates easier, because you don't have to guess each time whether some function is a member or not.</li>
<li>It keeps the class small, which in turn makes it easier to test and maintain.</li>
</ul>
<p>Although I see the value in these argument, I see a huge drawback: <strong>my IDE can't help me find these functions!</strong> Whenever I have an object of some kind, and I want to see what operations are available on it, I can't just type "<code>pMysteriousObject-></code>" and get a list of member functions anymore. </p>
<p>Keeping a clean design is in the end about making your programming life easier. But this would actually make mine much harder.</p>
<p>So I'm wondering if it's really worth the trouble. <strong>How do you deal with that?</strong></p>
|
[
{
"answer_id": 135684,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": true,
"text": "foo() Bar foo() bar() foo() Bar Bar"
},
{
"answer_id": 135712,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "::prefix\n namespace::prefix\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2095/"
] |
135,653
|
<p>I have some tables that I build as a part of my report rollup. I don't need them afterwards at all. Someone mentioned to truncate them as it would be faster. </p>
|
[
{
"answer_id": 2591131,
"author": "Sasikiran",
"author_id": 310790,
"author_profile": "https://Stackoverflow.com/users/310790",
"pm_score": 1,
"selected": false,
"text": "DELETE TRUNCATE TABLE WHERE DELETE TRUNCATE DELETE TRUNCATE TABLE DELETE TRUNCATE TABLE DELETE RESEED TRUNCATE RESEEDS IDENTITY TRUNCATE TABLE FOREIGN KEY TRUNCATE TABLE"
},
{
"answer_id": 47667506,
"author": "Optimizer",
"author_id": 3608072,
"author_profile": "https://Stackoverflow.com/users/3608072",
"pm_score": 3,
"selected": false,
"text": "DROP TABLE [table_name];\n DELETE FROM [table_name]\nWHERE [condition];\n\nDELETE FROM [table_name];\n TRUNCATE TABLE [table_name];\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
135,661
|
<p>Let's collect some tips for evaluating the appropriate use of global.asax.</p>
|
[
{
"answer_id": 850158,
"author": "Slim",
"author_id": 29774,
"author_profile": "https://Stackoverflow.com/users/29774",
"pm_score": 0,
"selected": false,
"text": "Session_Start"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
135,664
|
<p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
|
[
{
"answer_id": 135718,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 5,
"selected": false,
"text": "array"
},
{
"answer_id": 136083,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 5,
"selected": true,
"text": "import asizeof\n\nN = 1000000\nprint asizeof.asizeof(range(N)) / N\n# -> 20 (python 2.5, WinXP, 32-bit Linux)\n# -> 33 (64-bit Linux)\n"
},
{
"answer_id": 139393,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 3,
"selected": false,
"text": "struct PyTuple {\n size_t refcount; // tuple's reference count\n typeobject *type; // tuple type object\n size_t n_items; // number of items in tuple\n PyObject *items[1]; // contains space for n_items elements\n};\n sizeof(size_t) x 2 + sizeof(void*) x (n_items + 1) PyTuple::items[]"
},
{
"answer_id": 159844,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "getsizeof() __sizeof__() kveretennicov@nosignal:~/py/r26rc2$ ./python\nPython 2.6rc2 (r26rc2:66712, Sep 2 2008, 13:11:55) \n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\n>>> import sys\n>>> sys.getsizeof(range(1000000))\n4000032\n>>> sys.getsizeof(tuple(range(1000000)))\n4000024\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
] |
135,670
|
<p>This post is similar to <a href="https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control">this previously asked question.</a> I really want to set up my SVN repository in TTB format, but when creating a project in Visual Studio 2008 (ASP.NET/VB.NET), the structure created tends to be incompatible when considering the solution file, project files, folders for projects, multiple projects within solutions, etc. Does anyone have a script or procedure to take a newly created ASP.NET project and move it to a TTB format as painlessly as possible?</p>
<hr>
<p>Let me be more specific. Suppose I have a project that I'm creating called StackOverflowIsAwesome. I can put that into my local folder structure (let's say that it's c:\working). When I create it, VS creates c:\working\StackOverflowIsAwesome and a whole bunch of subfolders (bin, app_data, etc.). But I want my repository structure to look like...</p>
<pre>
StackOverflowIsAwesome
/trunk
/bin
/app_data
/tags
/branches
</pre>
<p>So, is there a clean way to do this consistently or do I need to resort to constantly moving/modifying files and folders to make this work?</p>
|
[
{
"answer_id": 135806,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 0,
"selected": false,
"text": "/tag\n\n/core_library\n /branch\n /main\n\n/business_logic\n /branch\n /main\n\n/report_library\n /branch\n /main\n\n/my_ui\n /branch\n /main\n"
},
{
"answer_id": 135959,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": -1,
"selected": false,
"text": "projectname\n / trunk\n /bin\n /obj\n /Properties\n projectname.sln\n /tags\n /branches\n"
},
{
"answer_id": 136626,
"author": "JKueck",
"author_id": 6354,
"author_profile": "https://Stackoverflow.com/users/6354",
"pm_score": 1,
"selected": false,
"text": "StackOverflowIsAwesome\n /trunk\n /database\n /datafiles\n /documents\n /build\n /installer\n /lib \n /External_DAL (external that points to shared library)\n /utilities\n /vendor\n /src\n /StackOverFlowIsAwesome\n /StackOverFlowIsAwesome.csprj\n /bin\n /...\n /StackOverFlowIsAwesomeTests\n /StackOverFlowIsAwesomeTests.csprj\n /bin\n /...\n /branches\n /tags\n"
},
{
"answer_id": 138885,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 0,
"selected": false,
"text": "/Project\n /trunk\n /lib/ # Binary imports here (not in svn)\n\n /src # Solution file here\n /Libraries # Library assemblies here\n /StackOverflowIsAwesome.Common\n\n /Products # Delivered products here\n /StackOverflowIsAwesome.Site\n\n /Projects # internal assemblies here\n /StackOverflowIsAwesome.Tests\n /branches\n /1.x\n /tags\n /StackOverflowIsAwesome-1.0\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18009/"
] |
135,688
|
<p>What is the proper way to modify environment variables like PATH in OS X?</p>
<p>I've looked on Google a little bit and found three different files to edit:</p>
<ul>
<li>/etc/paths</li>
<li>~/.profile</li>
<li>~/.tcshrc</li>
</ul>
<p>I don't even have some of these files, and I'm pretty sure that <em>.tcshrc</em> is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined?</p>
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="noreferrer">OS X v10.5</a> (Leopard).</p>
|
[
{
"answer_id": 135697,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 7,
"selected": false,
"text": "~/.MacOSX/environment.plist\n .bash_profile .profile launchd launchctl"
},
{
"answer_id": 135702,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "~/.bashrc ~/.bash_profile ~/.profile ~/.MacOSX/environment.plist"
},
{
"answer_id": 135705,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 2,
"selected": false,
"text": "~/.profile"
},
{
"answer_id": 136182,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": 2,
"selected": false,
"text": "/etc/paths ~/.MacOSX/environment.plist .bashrc .bash_profile .bashrc ln -s .bashrc .bash_profile\n"
},
{
"answer_id": 450246,
"author": "Bruno Ranschaert",
"author_id": 4900,
"author_profile": "https://Stackoverflow.com/users/4900",
"pm_score": 4,
"selected": false,
"text": "M2_HOME /etc/launchd.conf"
},
{
"answer_id": 588442,
"author": "Matthew McCullough",
"author_id": 56039,
"author_profile": "https://Stackoverflow.com/users/56039",
"pm_score": 9,
"selected": false,
"text": "/etc/launchd.conf sudo vi /etc/launchd.conf # Set environment variables here so they are available globally to all apps\n# (and Terminal), including those launched via Spotlight.\n#\n# After editing this file run the following command from the terminal to update\n# environment variables globally without needing to reboot.\n# NOTE: You will still need to restart the relevant application (including\n# Terminal) to pick up the changes!\n# grep -E \"^setenv\" /etc/launchd.conf | xargs -t -L 1 launchctl\n#\n# See http://www.digitaledgesw.com/node/31\n# and http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x/\n#\n# Note that you must hardcode the paths below, don't use environment variables.\n# You also need to surround multiple values in quotes, see MAVEN_OPTS example below.\n#\nsetenv JAVA_VERSION 1.6\nsetenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home\nsetenv GROOVY_HOME /Applications/Dev/groovy\nsetenv GRAILS_HOME /Applications/Dev/grails\nsetenv NEXUS_HOME /Applications/Dev/nexus/nexus-webapp\nsetenv JRUBY_HOME /Applications/Dev/jruby\n\nsetenv ANT_HOME /Applications/Dev/apache-ant\nsetenv ANT_OPTS -Xmx512M\n\nsetenv MAVEN_OPTS \"-Xmx1024M -XX:MaxPermSize=512m\"\nsetenv M2_HOME /Applications/Dev/apache-maven\n\nsetenv JMETER_HOME /Applications/Dev/jakarta-jmeter\n grep xargs export"
},
{
"answer_id": 3756686,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 8,
"selected": false,
"text": "launchctl setenv launchctl setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin\n .bashrc PATH=/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin\nlaunchctl setenv PATH $PATH\n export PATH=/opt/local/bin:/opt/local/sbin:$PATH launchctl config user path /bin:/usr/bin:/mystuff man launchctl /etc/launchd.conf /etc/launchd.conf setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin\n launchd.conf launchd.conf egrep -v '^\\s*#' /etc/launchd.conf | launchctl\n launchctl launchd.conf man launchctl"
},
{
"answer_id": 4917147,
"author": "MiB",
"author_id": 427009,
"author_profile": "https://Stackoverflow.com/users/427009",
"pm_score": 2,
"selected": false,
"text": "launchd.conf .profile ~/.MacOSX/environment.plist"
},
{
"answer_id": 5444960,
"author": "pajato0",
"author_id": 91443,
"author_profile": "https://Stackoverflow.com/users/91443",
"pm_score": 5,
"selected": false,
"text": "~/.profile ~/.bash_profile ~/.bashrc ~/.MacOSX/environment.plist <dict> <key>KEY</key><string>theValue</string> ~/.profile ~/bin/macosx-startup #!/bin/bash\nbash -l -c \"/Applications/Emacs.app/Contents/MacOS/Emacs --batch -l ~/lib/emacs/elisp/macosx/environment-support.el -f generate-environment\"\n ~/lib/emacs/elisp/macosx/envionment-support.el ;;; Provide support for the environment on Mac OS X\n\n(defun generate-environment ()\n \"Dump the current environment into the ~/.MacOSX/environment.plist file.\"\n ;; The system environment is found in the global variable:\n ;; 'initial-environment' as a list of \"KEY=VALUE\" pairs.\n (let ((list initial-environment)\n pair start command key value)\n ;; clear out the current environment settings\n (find-file \"~/.MacOSX/environment.plist\")\n (goto-char (point-min))\n (setq start (search-forward \"<dict>\\n\"))\n (search-forward \"</dict>\")\n (beginning-of-line)\n (delete-region start (point))\n (while list\n (setq pair (split-string (car list) \"=\")\n list (cdr list))\n (setq key (nth 0 pair)\n value (nth 1 pair))\n (insert \" <key>\" key \"</key>\\n\")\n (insert \" <string>\" value \"</string>\\n\")\n\n ;; Enable this variable in launchd\n (setq command (format \"launchctl setenv %s \\\"%s\\\"\" key value))\n (shell-command command))\n ;; Save the buffer.\n (save-buffer)))\n ~/.bash_profile launchd"
},
{
"answer_id": 6604397,
"author": "Russell B",
"author_id": 832593,
"author_profile": "https://Stackoverflow.com/users/832593",
"pm_score": 4,
"selected": false,
"text": "eval $(launchctl export)\n"
},
{
"answer_id": 6640813,
"author": "Rabi",
"author_id": 438466,
"author_profile": "https://Stackoverflow.com/users/438466",
"pm_score": 0,
"selected": false,
"text": "/etc/profile"
},
{
"answer_id": 8264813,
"author": "WoooHaaaa",
"author_id": 802585,
"author_profile": "https://Stackoverflow.com/users/802585",
"pm_score": 6,
"selected": false,
"text": "vim ~/.bash_profile\n export PATH=$PATH:YOUR_PATH_HERE\n source ~/.bash_profile\n"
},
{
"answer_id": 9821213,
"author": "Nicolas Wu",
"author_id": 72224,
"author_profile": "https://Stackoverflow.com/users/72224",
"pm_score": 3,
"selected": false,
"text": "$PATH path_helper /etc/paths /etc/paths.d"
},
{
"answer_id": 14501421,
"author": "Flori",
"author_id": 202151,
"author_profile": "https://Stackoverflow.com/users/202151",
"pm_score": 4,
"selected": false,
"text": "/etc/paths /etc/launchd.conf Info.plist Show package contents <key>LSEnvironment</key>\n<dict>\n <key>PATH</key>\n <string>/Users/flori/.rvm/gems/ruby-1.9.3-p362/bin:/Users/flori/.rvm/gems/ruby-1.9.3-p362@global/bin:/Users/flori/.rvm/rubies/ruby-1.9.3-p326/bin:/Users/flori/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:</string>\n</dict>\n"
},
{
"answer_id": 18972464,
"author": "wired00",
"author_id": 629222,
"author_profile": "https://Stackoverflow.com/users/629222",
"pm_score": 4,
"selected": false,
"text": "sudo nano /etc/paths sudo vim /etc/paths echo $PATH"
},
{
"answer_id": 20681139,
"author": "Charaf JRA",
"author_id": 1618189,
"author_profile": "https://Stackoverflow.com/users/1618189",
"pm_score": 2,
"selected": false,
"text": "touch ~/.bash_profile; open ~/.bash_profile\n export PATH=${PATH}:/Development/android-sdk-macosx/platform-tools:/Development/android-sdk-macosx/tools\n source ~/.bash_profile\n"
},
{
"answer_id": 21834243,
"author": "francois.robert",
"author_id": 1184693,
"author_profile": "https://Stackoverflow.com/users/1184693",
"pm_score": 2,
"selected": false,
"text": ".profile ~/ export MY_VAR=[your value here]\n export JAVA_HOME=/Library/Java/JavaVirtualMachines/current\n source .profile\n"
},
{
"answer_id": 22075073,
"author": "courtlandj",
"author_id": 3201683,
"author_profile": "https://Stackoverflow.com/users/3201683",
"pm_score": 3,
"selected": false,
"text": "source .bashrc\n function export()\n{\n builtin export \"$@\"\n if [[ ${#@} -eq 1 && \"${@//[^=]/}\" ]]\n then\n launchctl setenv \"${@%%=*}\" \"${@#*=}\"\n elif [[ ! \"${@//[^ ]/}\" ]]\n then\n launchctl setenv \"${@}\" \"${!@}\"\n fi\n}\n\nexport -f export\n export LC_CTYPE=en_US.UTF-8\n# ~$ launchctl getenv LC_CTYPE\n# en_US.UTF-8\nPATH=\"/usr/local/bin:${PATH}\"\nPATH=\"/usr/local/opt/coreutils/libexec/gnubin:${PATH}\"\nexport PATH\n# ~$ launchctl getenv PATH\n# /usr/local/opt/coreutils/libexec/gnubin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin\nexport CXX_FLAGS=\"-mmacosx-version-min=10.9\"\n# ~$ launchctl getenv CXX_FLAGS\n# -mmacosx-version-min=10.9\n launchctl getenv myVar"
},
{
"answer_id": 26264377,
"author": "CodeOverRide",
"author_id": 1394838,
"author_profile": "https://Stackoverflow.com/users/1394838",
"pm_score": 3,
"selected": false,
"text": "touch .bash_profile\n open -a TextEdit.app .bash_profile\n export TOMCAT_HOME=/Library/Tomcat/Home\n"
},
{
"answer_id": 26829886,
"author": "Claudio Floreani",
"author_id": 985792,
"author_profile": "https://Stackoverflow.com/users/985792",
"pm_score": 3,
"selected": false,
"text": "~/.profile ~/.bashrc /etc/paths /etc/paths.d/ ~/.MacOSX/environment.plist environment.plist /etc/paths defaults write $HOME/.MacOSX/environment PATH \"$(tr '\\n' ':' </etc/paths)\"\n"
},
{
"answer_id": 28078294,
"author": "ZOXIS",
"author_id": 1150275,
"author_profile": "https://Stackoverflow.com/users/1150275",
"pm_score": 2,
"selected": false,
"text": ".bashrc .bashrc .bash_profile #!/bin/bash\nsource ~/.profile # Get the PATH settings\nsource ~/.bashrc # Get Aliases and Functions\n#\n"
},
{
"answer_id": 29905744,
"author": "Koray Tugay",
"author_id": 1173112,
"author_profile": "https://Stackoverflow.com/users/1173112",
"pm_score": 2,
"selected": false,
"text": "/etc/profile\n /etc/profile .bash_profile\n.bash_login\n.profile\n ~/.bash_profile ~/.bash_login ~/.profile /etc/profile .bash_logout\n ~/.bash_logout /etc/bashrc\n ~/.bashrc /etc/bashrc .bashrc\n ~/.bashrc .bash_profile .bashrc .bashrc .bash_profile"
},
{
"answer_id": 32405815,
"author": "Ersin Er",
"author_id": 258474,
"author_profile": "https://Stackoverflow.com/users/258474",
"pm_score": 6,
"selected": false,
"text": "~/.bash_profile export JAVA_HOME=\"$(/usr/libexec/java_home -v 1.8)\"\nexport GOPATH=\"$HOME/go\"\nexport PATH=\"$PATH:/usr/local/opt/go/libexec/bin:$GOPATH/bin\"\nexport PATH=\"/usr/local/opt/coreutils/libexec/gnubin:$PATH\"\nexport MANPATH=\"/usr/local/opt/coreutils/libexec/gnuman:$MANPATH\"\n plist osx-env-sync.plist ~/Library/LaunchAgents/ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>osx-env-sync</string>\n <key>ProgramArguments</key>\n <array>\n <string>bash</string>\n <string>-l</string>\n <string>-c</string>\n <string>\n $HOME/.osx-env-sync.sh\n </string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n</dict>\n</plist>\n -l ~/.bash_profile ~/.osx-env-sync.sh grep export $HOME/.bash_profile | while IFS=' =' read ignoreexport envvar ignorevalue; do\n launchctl setenv \"${envvar}\" \"${!envvar}\"\ndone\n chmod +x ~/.osx-env-sync.sh\n launchctl load ~/Library/LaunchAgents/osx-env-sync.plist\n ~/.bash_profile launchctl load ... <$HOME>/Library/LaunchAgents/osx-env-sync.plist: Operation already in progress launchctl unload ~/Library/LaunchAgents/osx-env-sync.plist\nlaunchctl load ~/Library/LaunchAgents/osx-env-sync.plist\n"
},
{
"answer_id": 32902449,
"author": "Max Leske",
"author_id": 219324,
"author_profile": "https://Stackoverflow.com/users/219324",
"pm_score": 4,
"selected": false,
"text": "system user launchctl config /usr/bin launchctl setenv PATH <new path> PATH PATH sudo launchctl config user path <new path>\n getenv"
},
{
"answer_id": 48139773,
"author": "David",
"author_id": 7360,
"author_profile": "https://Stackoverflow.com/users/7360",
"pm_score": 3,
"selected": false,
"text": "launchctl /etc/launchd.conf file is no longer consulted for subcommands to run during early boot time;\nthis functionality was removed for security considerations.\n ~/Library/LaunchAgents/my.startup.plist LANG en_US.UTF-8"
},
{
"answer_id": 52823938,
"author": "suther",
"author_id": 1256697,
"author_profile": "https://Stackoverflow.com/users/1256697",
"pm_score": 2,
"selected": false,
"text": "source export bim=fooo\nexport bom=bar\n bimbom.env source ./bimbom.ev echo $bim\n"
},
{
"answer_id": 58517844,
"author": "Thushara Buddhika",
"author_id": 12162813,
"author_profile": "https://Stackoverflow.com/users/12162813",
"pm_score": 0,
"selected": false,
"text": ".bash_profile GOPATH=/usr/local/go/bin/\nMYSQLPATH=/usr/local/opt/mysql@5.6/bin\n\nPATH=$PATH:$GOPATH:$MYSQLPATH\n echo $GOPATH echo$MYSQLPATH echo $PATH"
},
{
"answer_id": 70959181,
"author": "Ben Carp",
"author_id": 7224430,
"author_profile": "https://Stackoverflow.com/users/7224430",
"pm_score": 3,
"selected": false,
"text": "~/.bash_profile ~/.zshrc export varName=varValue \n varValue \" open /Applications/Sourcetree.app\n .zshrc launchctl config user varName varVal /etc/launchd.conf plist"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
135,730
|
<p>What are the different types of indexes, what are the benefits of each?</p>
<p>I heard of covering and clustered indexes, are there more? Where would you use them?</p>
|
[
{
"answer_id": 136272,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 3,
"selected": false,
"text": "create index i on customers (id, name, whatever) where is_active is true;\n select name from customers where is_active is true;\n"
},
{
"answer_id": 142327,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 0,
"selected": false,
"text": "create index i on Customers(name) where is_alive = cast(1 as bit);\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
135,734
|
<p>I am trying to learn Emacs and trying to find best keyboard layout for me. One thing is really annoying me. I have added following lines to .emacs</p>
<pre class="lang-lisp prettyprint-override"><code>(global-set-key "\C-y" 'scroll-up)
(global-set-key "\M-y" 'scroll-down)
</code></pre>
<p>When I hold <kbd>Control</kbd> and press <kbd>y</kbd> a few times, it will page down on every press of <kbd>y</kbd>.</p>
<p><strong>However</strong>, when I hold the <kbd>Windows</kbd> key (mapped as <kbd>Meta</kbd>) and press <kbd>y</kbd> a few times it will only page up on the <strong>first</strong> press of <kbd>y</kbd> and all subsequent presses of <kbd>y</kbd> I get the ‘y’ character inserted in the buffer.</p>
<p>Can the page up behave like page down? I want to hold <kbd>Meta</kbd> and keep pressing <kbd>y</kbd> to scroll multiple pages up.</p>
<p>I am using GNU Emacs 23.0.60.1 (i386-mingw-nt5.1.2600) of 2008-05-12 on LENNART-69DE564 (patched). It is Emacs with EmacsW32 patch. Is this problem with this Emacs? Problem with Meta key?</p>
<p>I tried original GNU Emacs (not patched) and it works OK with <kbd>Alt</kbd>. But my problem is not that I want to scroll without releasing any key. I release key <kbd>y</kbd> and press it multiple times but don't want to have to release <kbd>Meta</kbd> key. Same problem is described here:</p>
<p><a href="http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10" rel="nofollow noreferrer">http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10</a></p>
<p>Problem is not in that I have changed key mapping. It looks like it is a bug in EmacsW32 version. Here is another description of the problem:
<a href="http://www.nabble.com/23.0.60--Unreleased-Meta-Win-modifier-td19213327.html" rel="nofollow noreferrer">Unreleased Meta/Win modifier</a></p>
|
[
{
"answer_id": 293829,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "C-v M-v C-y M-y"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438025/"
] |
135,745
|
<p>I have a simple web service, it takes 2 parameters one is a simple xml security token, the other is usually a long xml string. It works with short strings but longer strings give a 400 error message. maxMessageLength did nothing to allow for longer strings.</p>
|
[
{
"answer_id": 135809,
"author": "Yuval Peled",
"author_id": 20257,
"author_profile": "https://Stackoverflow.com/users/20257",
"pm_score": 2,
"selected": false,
"text": " NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true);\n\n // Allow big arguments on messages. Allow ~500 MB message.\n binding.MaxReceivedMessageSize = 500 * 1024 * 1024;\n\n // Allow unlimited time to send/receive a message. \n // It also prevents closing idle sessions. \n // From MSDN: To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.’\n binding.ReceiveTimeout = TimeSpan.MaxValue;\n binding.SendTimeout = TimeSpan.MaxValue;\n\n XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();\n\n // Remove quotas limitations\n quotas.MaxArrayLength = int.MaxValue;\n quotas.MaxBytesPerRead = int.MaxValue;\n quotas.MaxDepth = int.MaxValue;\n quotas.MaxNameTableCharCount = int.MaxValue;\n quotas.MaxStringContentLength = int.MaxValue;\n binding.ReaderQuotas = quotas;\n"
},
{
"answer_id": 139003,
"author": "user22367",
"author_id": 22367,
"author_profile": "https://Stackoverflow.com/users/22367",
"pm_score": 2,
"selected": false,
"text": "<bindings>\n <wsHttpBinding>\n <binding name=\"WSHttpBinding_IPayroll\" maxReceivedMessageSize=\"6553600\">\n <security mode=\"None\"/>\n <readerQuotas maxDepth=\"32\" \n maxStringContentLength=\"6553600\" \n maxArrayLength=\"16384\"\n maxBytesPerRead=\"4096\" \n maxNameTableCharCount=\"16384\" />\n </binding>\n </wsHttpBinding>\n</bindings>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22367/"
] |
135,754
|
<p>It is typical to have something like this in your cshrc file for setting the path:</p>
<pre><code>set path = ( . $otherpath $path )
</code></pre>
<p>but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?</p>
<p>EDIT: This is one unclean way of doing it:</p>
<pre><code>set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
set path = ( . $otherpaths $path )
endif
</code></pre>
|
[
{
"answer_id": 135783,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 0,
"selected": false,
"text": "set path = (. ~/bin /bin /usr/bin /usr/ucb /usr/bin/X11)\n set path = ($otherPath $path)\n"
},
{
"answer_id": 135831,
"author": "ShoeLace",
"author_id": 3825,
"author_profile": "https://Stackoverflow.com/users/3825",
"pm_score": 3,
"selected": true,
"text": "#!/usr/bin/perl\n#\n# ^^ ensure this is pointing to the correct location.\n#\n# Title: SLimPath\n# Author: David \"Shoe Lace\" Pyke <eselle@users.sourceforge.net >\n# : Tim Nelson \n# Purpose: To create a slim version of my envirnoment path so as to eliminate\n# duplicate entries and ensure that the \".\" path was last.\n# Date Created: April 1st 1999\n# Revision History:\n# 01/04/99: initial tests.. didn't wok verywell at all\n# : retreived path throught '$ENV' call\n# 07/04/99: After an email from Tim Nelson <wayland@ne.com.au> got it to\n# work.\n# : used 'push' to add to array\n# : used 'join' to create a delimited string from a list/array.\n# 16/02/00: fixed cmd-line options to look/work better\n# 25/02/00: made verbosity level-oriented\n#\n#\n\nuse Getopt::Std;\n\nsub printlevel;\n\n$initial_str = \"\";\n$debug_mode = \"\";\n$delim_chr = \":\";\n$opt_v = 1;\n\ngetopts(\"v:hd:l:e:s:\");\n\nOPTS: {\n $opt_h && do {\nprint \"\\n$0 [-v level] [-d level] [-l delim] ( -e varname | -s strname | -h )\";\nprint \"\\nWhere:\";\nprint \"\\n -h This help\";\nprint \"\\n -d Debug level\";\nprint \"\\n -l Delimiter (between path vars)\";\nprint \"\\n -e Specify environment variable (NB: don't include \\$ sign)\";\nprint \"\\n -s String (ie. $0 -s \\$PATH:/looser/bin/)\";\nprint \"\\n -v Verbosity (0 = quiet, 1 = normal, 2 = verbose)\";\nprint \"\\n\";\n exit;\n };\n $opt_d && do {\n printlevel 1, \"You selected debug level $opt_d\\n\";\n $debug_mode = $opt_d;\n };\n $opt_l && do {\n printlevel 1, \"You are going to delimit the string with \\\"$opt_l\\\"\\n\";\n $delim_chr = $opt_l;\n };\n $opt_e && do {\n if($opt_s) { die \"Cannot specify BOTH env var and string\\n\"; }\n printlevel 1, \"Using Environment variable \\\"$opt_e\\\"\\n\";\n $initial_str = $ENV{$opt_e};\n };\n $opt_s && do {\n printlevel 1, \"Using String \\\"$opt_s\\\"\\n\";\n $initial_str = $opt_s;\n };\n}\n\nif( ($#ARGV != 1) and !$opt_e and !$opt_s){\n die \"Nothing to work with -- try $0 -h\\n\";\n}\n\n$what = shift @ARGV;\n# Split path using the delimiter\n@dirs = split(/$delim_chr/, $initial_str);\n\n$dest;\n@newpath = ();\nLOOP: foreach (@dirs){\n # Ensure the directory exists and is a directory\n if(! -e ) { printlevel 1, \"$_ does not exist\\n\"; next; }\n # If the directory is ., set $dot and go around again\n if($_ eq '.') { $dot = 1; next; }\n\n# if ($_ ne `realpath $_`){\n# printlevel 2, \"$_ becomes \".`realpath $_`.\"\\n\";\n# }\n undef $dest;\n #$_=Stdlib::realpath($_,$dest);\n # Check for duplicates and dot path\n foreach $adir (@newpath) { if($_ eq $adir) { \n printlevel 2, \"Duplicate: $_\\n\";\n next LOOP; \n }}\n\n push @newpath, $_;\n}\n\n# Join creates a string from a list/array delimited by the first expression\nprint join($delim_chr, @newpath) . ($dot ? $delim_chr.\".\\n\" : \"\\n\");\n\nprintlevel 1, \"Thank you for using $0\\n\";\nexit;\n\nsub printlevel {\n my($level, $string) = @_;\n\n if($opt_v >= $level) {\n print STDERR $string;\n }\n}\n"
},
{
"answer_id": 136153,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": 2,
"selected": false,
"text": "case $PATH in\n *:$HOME/bin | *:$HOME/bin:* ) ;;\n *) export PATH=$PATH:$HOME/bin\nesac\n"
},
{
"answer_id": 137981,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": ": \"@(#)$Id: clnpath.sh,v 1.6 1999/06/08 23:34:07 jleffler Exp $\"\n#\n# Print minimal version of $PATH, possibly removing some items\n\ncase $# in\n0) chop=\"\"; path=${PATH:?};;\n1) chop=\"\"; path=$1;;\n2) chop=$2; path=$1;;\n*) echo \"Usage: `basename $0 .sh` [$PATH [remove:list]]\" >&2\n exit 1;;\nesac\n\n# Beware of the quotes in the assignment to chop!\necho \"$path\" |\n${AWK:-awk} -F: '#\nBEGIN { # Sort out which path components to omit\n chop=\"'\"$chop\"'\";\n if (chop != \"\") nr = split(chop, remove); else nr = 0;\n for (i = 1; i <= nr; i++)\n omit[remove[i]] = 1;\n }\n{\n for (i = 1; i <= NF; i++)\n {\n x=$i;\n if (x == \"\") x = \".\";\n if (omit[x] == 0 && path[x]++ == 0)\n {\n output = output pad x;\n pad = \":\";\n }\n }\n print output;\n}'\n export PATH=$(clnpath /new/bin:/other/bin:$PATH /old/bin:/extra/bin)\n"
},
{
"answer_id": 148702,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 2,
"selected": false,
"text": "set path=(`echo $path | tr ' ' '\\n' | sort | uniq | tr '\\n' ' '`)\n"
},
{
"answer_id": 154979,
"author": "dr_pepper",
"author_id": 18415,
"author_profile": "https://Stackoverflow.com/users/18415",
"pm_score": 2,
"selected": false,
"text": "echo $path | tr ' ' '\\n' | perl -e 'while (<>) { print $_ unless $s{$_}++; }' | tr '\\n' ' '"
},
{
"answer_id": 5048977,
"author": "MestreLion",
"author_id": 624066,
"author_profile": "https://Stackoverflow.com/users/624066",
"pm_score": 4,
"selected": false,
"text": "tr \":\" \"\\n\" | grep -x if ! $(echo \"$PATH\" | tr \":\" \"\\n\" | grep -qx \"$dir\") ; then PATH=$PATH:$dir ; fi\n append_path()\n{\n local SAVED_IFS=\"$IFS\"\n local dir\n IFS=:\n for dir in $1 ; do\n if ! $( echo \"$PATH\" | tr \":\" \"\\n\" | grep -qx \"$dir\" ) ; then\n PATH=$PATH:$dir\n fi\n done\n IFS=\"$SAVED_IFS\"\n}\n append_path \"/test:$HOME/bin:/example/my dir/space is not an issue\"\n !#/bin/sh awk sed"
},
{
"answer_id": 9044243,
"author": "bnjf",
"author_id": 1175002,
"author_profile": "https://Stackoverflow.com/users/1175002",
"pm_score": 2,
"selected": false,
"text": "$ PATH=$(echo $PATH | sed -e 's/$/:/;s/^/:/;s/:/::/g;:a;s#\\(:[^:]\\{1,\\}:\\)\\(.*\\)\\1#\\1\\2#g;ta;s/::*/:/g;s/^://;s/:$//;')\n $ NEWPATH=/bin:/usr/bin:/bin:/usr/local/bin:/usr/local/bin:/bin\n$ echo $NEWPATH | sed -e 's/$/:/; s/^/:/; s/:/::/g; :a; s#\\(:[^:]\\{1,\\}:\\)\\(.*\\)\\1#\\1\\2#g; t a; s/::*/:/g; s/^://; s/:$//;'\n/bin:/usr/bin:/usr/local/bin\n$\n"
},
{
"answer_id": 21564464,
"author": "jpabel",
"author_id": 3257507,
"author_profile": "https://Stackoverflow.com/users/3257507",
"pm_score": 1,
"selected": false,
"text": "#!/bin/csh\n# ABSTRACT\n# /bin/csh function-like aliases for manipulating environment\n# variables containing paths.\n#\n# BUGS\n# - These *MUST* be single line aliases to avoid parsing problems apparently related\n# to if-then-else\n# - Aliases currently perform tests in inefficient in order to avoid parsing problems\n# - Extremely fragile - use bash instead!!\n#\n# AUTHOR\n# J. P. Abelanet - 11/11/10\n\n# Function-like alias to add a path to the front of an environment variable\n# containing colon (':') delimited paths, without path duplication\n#\n# Usage: prepend_path ENVVARIABLE /path/to/prepend\nalias prepend_path \\\n 'set arg2=\"\\!:2\"; if ($?\\!:1 == 0) setenv \\!:1 \"$arg2\"; if ($?\\!:1 && $\\!:1 !~ {,*:}\"$arg2\"{:*,}) setenv \\!:1 \"$arg2\":\"$\\!:1\";'\n\n# Function-like alias to add a path to the back of any environment variable \n# containing colon (':') delimited paths, without path duplication\n#\n# Usage: append_path ENVVARIABLE /path/to/append\nalias append_path \\\n 'set arg2=\"\\!:2\"; if ($?\\!:1 == 0) setenv \\!:1 \"$arg2\"; if ($?\\!:1 && $\\!:1 !~ {,*:}\"$arg2\"{:*,}) setenv \\!:1 \"$\\!:1\":\"$arg2\";'\n"
},
{
"answer_id": 28584356,
"author": "BOC",
"author_id": 2051109,
"author_profile": "https://Stackoverflow.com/users/2051109",
"pm_score": 0,
"selected": false,
"text": "export PATH=$(perl -e 'print join \":\", grep {!$h{$_}++} split \":\", \"'$otherpath:$PATH\\\")\n set path = ( `echo $otherpath $path | tr ' ' '\\n' | perl -ne 'print $_ unless $h{$_}++' | tr '\\n' ' '`)\n"
},
{
"answer_id": 58641778,
"author": "Dotan Dimet",
"author_id": 117896,
"author_profile": "https://Stackoverflow.com/users/117896",
"pm_score": 1,
"selected": false,
"text": "cat foo.csh # or .tcshrc or whatever:\nset -f path = (/bin /usr/bin . ) # initial value\nset -f path = ($path /mycode /hercode /usr/bin ) # add things, both new and duplicates\n source % source foo.csh\n % echo $PATH\n % /bin:/usr/bin:.:/mycode:/hercode\n % source foo.csh\n % echo $PATH\n % /bin:/usr/bin:.:/mycode:/hercode\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415/"
] |
135,755
|
<p>How do you find the version of an installed Perl module?</p>
<p>This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my <code>.bashrc</code></p>
<pre><code>function perlmodver {
perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \
" is installed.\n"' $1
}
</code></pre>
|
[
{
"answer_id": 135760,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 6,
"selected": false,
"text": "perl -MSome::Module -le 'print $Some::Module::VERSION'\n"
},
{
"answer_id": 135773,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 3,
"selected": false,
"text": "$ perl -MCPAN -e 'print \"$CPAN::VERSION\\n\"'\n1.9205\n"
},
{
"answer_id": 135863,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 2,
"selected": false,
"text": ".pm $ perlver CPAN DBD-Pg Getopt::Long\nCPAN 1.7602 is\n /usr/lib/perl5/5.8.8/CPAN.pm\nDBD::Pg 1.49 is\n /usr/lib/perl5/vendor_perl/5.8.8/i686-linux/DBD/Pg.pm\nGetopt::Long 2.36 is\n /usr/lib/perl5/vendor_perl/5.8.8/Getopt/Long.pm\n"
},
{
"answer_id": 135928,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": 1,
"selected": false,
"text": "perl -MSome::Module=99999 -ex\nSome::Module version 99999 required--this is only version 1.9205 at ...\n perl -e'use Some::Module 99999'\nSome::Module version 99999 required--this is only version 1.9205 at ...\n"
},
{
"answer_id": 135978,
"author": "Penfold",
"author_id": 11952,
"author_profile": "https://Stackoverflow.com/users/11952",
"pm_score": 5,
"selected": false,
"text": "perl -MFoo::Bar\\ 9999\n use Foo::Bar 9999;\n Foo::Bar version 9999 required--this is only version 1.1.\nBEGIN failed--compilation aborted.\n"
},
{
"answer_id": 136218,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 7,
"selected": true,
"text": "cpan -D -O -a"
},
{
"answer_id": 136229,
"author": "jmcnamara",
"author_id": 10238,
"author_profile": "https://Stackoverflow.com/users/10238",
"pm_score": 5,
"selected": false,
"text": "perl -le 'eval \"require $ARGV[0]\" and print $ARGV[0]->VERSION' Some::Module\n"
},
{
"answer_id": 136356,
"author": "Drew Stephens",
"author_id": 17339,
"author_profile": "https://Stackoverflow.com/users/17339",
"pm_score": 3,
"selected": false,
"text": "function perlmodver {\n perl -M$1 -e 'print $ARGV[0]->VERSION . \"\\n\"' $1\n} \n"
},
{
"answer_id": 21977953,
"author": "BMW",
"author_id": 498256,
"author_profile": "https://Stackoverflow.com/users/498256",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/perl\n\nuse strict;\nuse ExtUtils::Installed;\n\nmy @modules;\nmy $installed = ExtUtils::Installed->new();\n\nif (scalar(@ARGV) > 0) {\n\n @modules = @ARGV;\n\n} else {\n\n @modules = $installed->modules();\n\n}\n\nprint \"Module\\tVersion\\n\";\n\nforeach (@modules) {\n\n print $_ . \"\\t\" . $installed->version($_) . \"\\n\";\n\n}\n"
},
{
"answer_id": 31879196,
"author": "smonff",
"author_id": 954777,
"author_profile": "https://Stackoverflow.com/users/954777",
"pm_score": 0,
"selected": false,
"text": "$ module-version\n\nThe version of App::module::version in /home/yourself/perl5/lib/perl5 is 1.004\n"
},
{
"answer_id": 47397132,
"author": "Jpsy",
"author_id": 430742,
"author_profile": "https://Stackoverflow.com/users/430742",
"pm_score": 2,
"selected": false,
"text": "perl -e 'use Search::Elasticsearch; print $Search::Elasticsearch::VERSION;'\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17339/"
] |
135,759
|
<p>Why can't I create a <code>class</code> in <code>VB.NET</code> that <code>inherits</code> <code>System.IO.Directory</code>? According to Lutz Roeder, it is <em>not</em> declared as <code>NotInheritable</code>!</p>
<p>I want to create a <code>utility class</code> that adds functionality to the <code>Directory class</code>. For instance, I want to add a <code>Directory.Move</code> function.</p>
<p>Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool.</p>
|
[
{
"answer_id": 135772,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 5,
"selected": true,
"text": "namespace System.IO\n{\n // Summary:\n // Exposes static methods for creating, moving, and enumerating through directories\n // and subdirectories. This class cannot be inherited.\n [ComVisible(true)]\n public static class Directory\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54420/"
] |
135,777
|
<h2>Seeking a method to:</h2>
<h2>Take whitespace separated tokens in a String; return a suggested Word</h2>
<p><br>
<strong>ie:</strong><br>
Google Search can take <em>"fonetic wrd nterpreterr"</em>,<br>
and atop of the result page it shows <em>"Did you mean: phonetic word interpreter"</em></p>
<p><em>A solution in any of the C* languages or Java would be preferred.</em></p>
<p><br>
<strong>Are there any existing Open Libraries which perform such functionality?</strong></p>
<p><strong>Or is there a way to Utilise a Google API to request a suggested word?</strong></p>
|
[
{
"answer_id": 707323,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 2,
"selected": false,
"text": "startup()\n{\n set the spelling engines word suggestion limit to 1\n}\n\noption 1()\n{\n int currentPosition = engine.NextWord(start the search at word 0, querystring);\n\n if(currentPosition == -1)\n return empty string; // Query is a-ok.\n\n while(currentPosition != -1)\n {\n queryString = engine.ReplaceWord(engine.CurrentWord, queryString, the suggestion with index 0);\n currentPosition = engine.NextWord(currentPosition, querystring);\n }\n\n return queryString;\n}\n"
},
{
"answer_id": 707367,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "void match(trie t, char* w, string s, int budget){\n if (budget < 0) return;\n if (*w=='\\0') print s;\n foreach (char c, subtrie t1 in t){\n /* try matching or replacing c */\n match(t1, w+1, s+c, (*w==c ? budget : budget-1));\n /* try deleting c */\n match(t1, w, s, budget-1);\n }\n /* try inserting *w */\n match(t, w+1, s + *w, budget-1);\n}\n"
},
{
"answer_id": 707502,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 5,
"selected": true,
"text": ">>> import spellch\n>>> [spellch.correct(w) for w in 'fonetic wrd nterpreterr'.split()]\n['phonetic', 'word', 'interpreters']\n"
},
{
"answer_id": 718607,
"author": "wentbackward",
"author_id": 87100,
"author_profile": "https://Stackoverflow.com/users/87100",
"pm_score": 2,
"selected": false,
"text": "String[] l=spellChecker.suggestSimilar(\"sevanty\", 2);\n//l[0] = \"seventy\"\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
135,782
|
<p>A lot of my C# code follows this pattern:</p>
<pre><code>void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
</code></pre>
<p>Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?</p>
|
[
{
"answer_id": 135813,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "public class LogArgs\n{\n\n public string MethodName { get; set; }\n public string ClassName { get; set; }\n public Dictionary<string, object> Paramters { get; set; }\n\n\n public LogArgs()\n {\n this.Paramters = new Dictionary<string, object>();\n }\n\n}\n LogArgs args = new LogArgs { ClassName = \"ClassName\", MethodName = \"MethodName\" };\nargs.Paramters.Add(\"Param1\", param1);\nargs.Paramters.Add(\"Param2\", param2);\nargs.Paramters.Add(\"Param3\", param3);\n\nbase.Logger.MethodStartLog(args);\n base.Logger.LogError(args, ex);\n"
},
{
"answer_id": 135827,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "try\n{\n ...\n}\ncatch(Exception ex)\n{\n log(ex);\n throw;\n}\n"
},
{
"answer_id": 135838,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 1,
"selected": false,
"text": " public void LogError(string message, params object[] parameters)\n {\n if (parameters.Length > 0)\n LogError(string.Format(message, parameters));\n else\n LogError(message);\n }\n"
},
{
"answer_id": 136041,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 6,
"selected": true,
"text": "private static void MyMethod(string s, int x, int y)\n{\n try\n {\n throw new NotImplementedException();\n }\n catch (Exception ex)\n {\n LogError(MethodBase.GetCurrentMethod(), ex, s, x, y);\n }\n}\n\nprivate static void LogError(MethodBase method, Exception ex, params object[] values)\n{\n ParameterInfo[] parms = method.GetParameters();\n object[] namevalues = new object[2 * parms.Length];\n\n string msg = \"Error in \" + method.Name + \"(\";\n for (int i = 0, j = 0; i < parms.Length; i++, j += 2)\n {\n msg += \"{\" + j + \"}={\" + (j + 1) + \"}, \";\n namevalues[j] = parms[i].Name;\n if (i < values.Length) namevalues[j + 1] = values[i];\n }\n msg += \"exception=\" + ex.Message + \")\";\n Console.WriteLine(string.Format(msg, namevalues));\n}\n"
},
{
"answer_id": 136167,
"author": "Jacob",
"author_id": 22107,
"author_profile": "https://Stackoverflow.com/users/22107",
"pm_score": 3,
"selected": false,
"text": "public class LogExceptionAttribute : OnExceptionAspect\n{\n public override void OnException(MethodExecutionEventArgs eventArgs)\n {\n log.error(\"Exception occurred in method {0}\", eventArgs); \n }\n}\n\n[LoggingOnExceptionAspect]\npublic foo(int number, string word, Person customer)\n{\n // ... something here throws an exception\n}\n"
},
{
"answer_id": 37281373,
"author": "joym8",
"author_id": 1541224,
"author_profile": "https://Stackoverflow.com/users/1541224",
"pm_score": 0,
"selected": false,
"text": "[Log]"
},
{
"answer_id": 71048965,
"author": "Aaron Gibson",
"author_id": 2357370,
"author_profile": "https://Stackoverflow.com/users/2357370",
"pm_score": 0,
"selected": false,
"text": "public void ConfigureServices(HostBuilderContext hostBuilder, IServiceCollection services)\n {\n services.AddOptions();\n services.AddSingleton<IHostedService, HostedService>();\n\n services.AddSingleton<IMyClass, MyClass>();\n\n // Logging added for both the hosted service and the example class\n services.Decorate<IMyClass, ProxyLogger<IMyClass>>();\n services.Decorate<IHostedService, ProxyLogger<IHostedService>>();\n }\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
135,799
|
<p>I've been using the macro from <a href="http://weblogs.asp.net/koenv/archive/2008/02/14/quick-attach-and-detach-debugger.aspx" rel="nofollow noreferrer">this blog entry</a> for attaching the Visual Studio debugger to an already running instance of the Web Application I'm currently working on. However, if I have more than one instance of the Visual Studio web server running it's pot luck which one it'll attach to.</p>
<p>Is there a way to determine what port is configured in the Web project so I can modify the macro to filter its choice of process to that one?</p>
<hr>
<p>Further Info</p>
<p>I'm aware that you can set the port number to a static one - I've done just that from the get-go, what I'm trying to determine is how to <em>programatically</em> determine the defined port-number so I can modify the macro (in the linked blog entry) and ensure it connects to the right instance of the Visual Studio web server.</p>
<p>The way I have things running is I have two (or more) instances of Visual Studio running, each of which contains a Solution, which contains a web project and one or more other projects - typically an Installer project), so when I trigger the macro from a given instance of Visual Studio, I want to find the Web Project within that instances loaded solution and determine the port it's running against.</p>
|
[
{
"answer_id": 226484,
"author": "Annagram",
"author_id": 29324,
"author_profile": "https://Stackoverflow.com/users/29324",
"pm_score": 2,
"selected": false,
"text": "Sub GetWebProjectPorts()\n Dim ports As String\n\n For Each prj As Project In DTE.Solution.Projects\n For Each p As EnvDTE.Property In prj.Properties\n If p.Name.Contains(\"DevelopmentServerPort\") Then\n If Not String.IsNullOrEmpty(ports) Then\n ports += \",\"\n End If\n ports += p.Value.ToString()\n End If\n Next\n Next\n\n MsgBox(ports)\nEnd Sub\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872/"
] |
135,801
|
<p>I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript?</p>
|
[
{
"answer_id": 135855,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": -1,
"selected": false,
"text": "function getCookie(c_name) {\nif (document.cookie.length>0)\n {\n c_start=document.cookie.indexOf(c_name + \"=\")\n if (c_start!=-1)\n { \n c_start=c_start + c_name.length+1 \n c_end=document.cookie.indexOf(\";\",c_start)\n if (c_end==-1) c_end=document.cookie.length\n return unescape(document.cookie.substring(c_start,c_end))\n } \n }\nreturn \"\"\n"
},
{
"answer_id": 180271,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "function ReadCookie(name)\n{\n name += '=';\n var parts = document.cookie.split(/;\\s*/);\n for (var i = 0; i < parts.length; i++)\n {\n var part = parts[i];\n if (part.indexOf(name) == 0)\n return part.substring(name.length)\n }\n return null;\n}\n"
},
{
"answer_id": 11109684,
"author": "TheZ",
"author_id": 1217408,
"author_profile": "https://Stackoverflow.com/users/1217408",
"pm_score": 2,
"selected": false,
"text": "function getCookie(c_name) {\n var nameEQ = c_name + '=';\n var c_start = 0;\n var c_end = 0;\n if (document.cookie.substr(0, nameEQ.length) === nameEQ) {\n return document.cookie.substring(nameEQ.length, document.cookie.indexOf(';', nameEQ.length));\n } else {\n c_start = document.cookie.indexOf('; ' + nameEQ);\n if(c_start !== -1){\n c_start += nameEQ.length + 2;\n c_end = document.cookie.indexOf(';', c_start);\n if (c_end === -1) {c_end = document.cookie.length;}\n return document.cookie.substring(c_start, c_end);\n }\n }\n return null;\n}\n function getCookie(c_name){\n var ret = window.testCookie.match(new RegExp(\"(?:^|;)\\\\s*\"+c_name+\"=([^;]*)\"));\n return (ret !== null ? ret[1] : null);\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
] |
135,802
|
<p>I'm looking for the concept to <strong>spawn a process</strong> such that:</p>
<ul>
<li>it has only access to certain libraries/APIs</li>
<li>it cannot acess the file system or only specific parts</li>
<li>it can <strong>do least harm should malicious code run in it</strong></li>
</ul>
<p>This concept is known as sandbox or jail.</p>
<p>It is required to do this <strong>for each major Operating system (Windows, MacOSX and Linux)</strong> and the question is conceptual (as in what to do, <strong>which APIs to use and and what to observe</strong>) rather then language specific.</p>
<h2>answer requirements</h2>
<p>I <strong>really</strong> want to accept an answer and give you 20 points for that. I cannot accept my own answer, and I don't have it yet anyway. So if you <strong>really</strong> want your answer to be accepted, please observe:</p>
<ul>
<li>The answer has to be specific and complete</li>
<li>With specific I mean that it is more then a pointer to some resource on the internet. It has to summarize what the resource says about the topic at least.</li>
<li>It may or may not contain example code, but if it does please write it in C</li>
<li>I cannot accept an answer that is 2/3 complete even if the 2/3 that are there are perfect.</li>
</ul>
<h2>this question FAQ</h2>
<ul>
<li>Is this homework? No.</li>
<li>Why do you ask this like a homework question? If you ask a specific question and you want to get a specific answer, and you know how that answer should look like, even though you don't know <em>the</em> answer, that's the style of question you get.</li>
<li>If you know how it should look like, why do you ask? 1) because I don't know all the answer 2) because on the internet there's no single place that contains all the details to this question in one place. Please also read the stackoverflow FAQ</li>
<li>Why is the main part of your question how to answer this question? Because nobody reads the FAQ.</li>
</ul>
|
[
{
"answer_id": 153111,
"author": "Trance Diviner",
"author_id": 7365,
"author_profile": "https://Stackoverflow.com/users/7365",
"pm_score": 4,
"selected": false,
"text": "(allow process-exec (regex #\"^/usr/sbin/portmap$\"))\n(allow file-read-data file-read-metadata (regex\n #\"^/etc\"\n #\"^/usr/lib/.*\\.dylib$\"\n #\"^/var\"\n #\"^/private/var/db/dyld/\"\n #\"^/dev/urandom$\"))\n(allow file-write-data (regex\n #\"^/dev/dtracehelper$\"))\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19435/"
] |
135,803
|
<blockquote>
<p>System.InvalidOperationException: DragDrop registration did not
succeed. ---> System.Threading.ThreadStateException:</p>
</blockquote>
<p>What does this exception mean? I get it at this line trying to add a panel to a panel at runtime...</p>
<pre><code>splitReport.Panel1.Controls.Add(ChartPanel);
</code></pre>
<p>Working in VS2008 C#</p>
|
[
{
"answer_id": 160867,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": false,
"text": "[STAThread] Thread.CurrentThread.SetApartmentState( ApartmentState.STA ) Thread ApartmentState System.Threading [STAThread]"
},
{
"answer_id": 2205399,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 2,
"selected": false,
"text": "bin"
},
{
"answer_id": 5897823,
"author": "T.K.",
"author_id": 391618,
"author_profile": "https://Stackoverflow.com/users/391618",
"pm_score": 2,
"selected": false,
"text": "[STAThread] Main() BackgroundWorker.DoWork Invoke Main() [STAThread]"
},
{
"answer_id": 7227339,
"author": "Sai Sherlekar",
"author_id": 730593,
"author_profile": "https://Stackoverflow.com/users/730593",
"pm_score": 3,
"selected": false,
"text": "function abc\n{\n Thread t = new Thread(new ThreadStart(xyz));\n t.SetApartmentState(ApartmentState.STA);\n t.Start( ); \n}\nfunction xyz\n{\n the code of Windows form..or whatever which is causing the error\n}\n"
},
{
"answer_id": 18462689,
"author": "zionpi",
"author_id": 1066501,
"author_profile": "https://Stackoverflow.com/users/1066501",
"pm_score": 0,
"selected": false,
"text": "[STAThreadAttribute] this.Invoke(new InvokeHandler(delegate() \n{\n//Your method here!\n}));\n private delegate void InvokeHandler();\n"
},
{
"answer_id": 24139839,
"author": "Conrad de Wet",
"author_id": 2542014,
"author_profile": "https://Stackoverflow.com/users/2542014",
"pm_score": 1,
"selected": false,
"text": "private void DoSomethingOnGui()\n{\n if (this.InvokeRequired)\n {\n this.Invoke((MethodInvoker)delegate\n {\n Safe_DoSomethingOnGui();\n });\n }\n else\n {\n Safe_DoSomethingOnGui();\n }\n}\nprivate void Safe_DoSomethingOnGui()\n{\n // Do whatever you want with the GUI\n}\n private void DoSomethingOnGui(object o)\n{\n if (this.InvokeRequired)\n {\n this.Invoke((MethodInvoker)delegate\n {\n Safe_DoSomethingOnGui(o);\n });\n }\n else\n {\n Safe_DoSomethingOnGui(o);\n }\n}\nprivate void Safe_DoSomethingOnGui(object o)\n{\n // Do whatever you want with the GUI and o\n}\n"
},
{
"answer_id": 28553467,
"author": "Kosmas",
"author_id": 2833737,
"author_profile": "https://Stackoverflow.com/users/2833737",
"pm_score": 1,
"selected": false,
"text": "MessageBox.Show(this, ...) this"
},
{
"answer_id": 32665641,
"author": "RAVI VAGHELA",
"author_id": 4255952,
"author_profile": "https://Stackoverflow.com/users/4255952",
"pm_score": 1,
"selected": false,
"text": "BeginInvoke((MethodInvoker)delegate\n{\n//write your code here...\n\n});\n"
},
{
"answer_id": 69099195,
"author": "S0und",
"author_id": 1809169,
"author_profile": "https://Stackoverflow.com/users/1809169",
"pm_score": 1,
"selected": false,
"text": "async Task Main() [STAThread]\n static async Task Main()\n {\n }\n void [STAThread]\n static void Main()\n {\n }\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
135,826
|
<p>I am looking for some stats on current browsers for how long it takes to render a table using plain HTML versus a hacked-up CSS puritan method that avoids using actual <code>TABLE</code>, <code>TR</code>, <code>TD</code> etc. tags.</p>
<p><strong>I am not looking for what's proper, only for what's faster</strong>, particularly on Firefox 3, although I am also interested in the stats for other browsers. Of <em>course</em> TABLE tags are designed for tables. That's not the question.</p>
|
[
{
"answer_id": 135860,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 0,
"selected": false,
"text": "<thead> <tfoot>"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16777/"
] |
135,834
|
<p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
|
[
{
"answer_id": 4892651,
"author": "MajesticRa",
"author_id": 548894,
"author_profile": "https://Stackoverflow.com/users/548894",
"pm_score": 7,
"selected": false,
"text": "CppCamelStyleFunctions() looks_more_pythonish"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14028/"
] |
135,835
|
<p>I am trying to load a small sample of records from a large database into a test database.</p>
<p>How do you tell mysqldump to only give you n records out of 8 million?</p>
<p>Thanks</p>
|
[
{
"answer_id": 135900,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 8,
"selected": false,
"text": "mysqldump --opt --where=\"1 limit 1000000\" database\n"
},
{
"answer_id": 19830993,
"author": "Casper André Casse",
"author_id": 1665847,
"author_profile": "https://Stackoverflow.com/users/1665847",
"pm_score": 6,
"selected": false,
"text": "n mysqldump --opt --where=\"1 limit 1000000\" database table > dump.sql\n 1000000 table dump.sql"
},
{
"answer_id": 46113423,
"author": "Andreas Bergström",
"author_id": 1202214,
"author_profile": "https://Stackoverflow.com/users/1202214",
"pm_score": 4,
"selected": false,
"text": "mysqldump --opt --where=\"1 ORDER BY id DESC limit 1000000\" --all-databases > dump.sql\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
135,841
|
<p>As just stated in a recent <a href="https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory">question</a> and <a href="https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory#135772">answer</a>, you can't inherit from a static class. How does one enforce the rules that go along with static classes inside VB.NET? Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn't seem to be a way.</p>
|
[
{
"answer_id": 135852,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 8,
"selected": true,
"text": "NotInheritable Shared Module"
},
{
"answer_id": 16497226,
"author": "Mentor",
"author_id": 1520418,
"author_profile": "https://Stackoverflow.com/users/1520418",
"pm_score": 2,
"selected": false,
"text": "Friend NotInheritable Class DB\n Public Shared AGE As Integer = 20\nEnd Class\n Dim myage As Integer = DB.AGE\n"
},
{
"answer_id": 18922541,
"author": "Gary Newsom",
"author_id": 2800150,
"author_profile": "https://Stackoverflow.com/users/2800150",
"pm_score": 6,
"selected": false,
"text": "NotInheritable Class MyStaticClass\n\n ''' <summary>\n ''' Prevent instantiation.\n ''' </summary>\n Private Sub New()\n\n End Sub\n\n Public Shared Function MyMethod() As String\n\n End Function\n\nEnd Class\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8505/"
] |
135,845
|
<p>A colleague of mine states that <strong>booleans as method arguments are not acceptable</strong>. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.</p>
<p>What's easier to understand?</p>
<pre><code>file.writeData( data, true );
</code></pre>
<p>Or</p>
<pre><code>enum WriteMode {
Append,
Overwrite
};
file.writeData( data, Append );
</code></pre>
<p>Now I got it! ;-)<br>
This is definitely an example where an enumeration as second parameter makes the code much more readable.</p>
<p>So, what's your opinion on this topic?</p>
|
[
{
"answer_id": 135882,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 2,
"selected": false,
"text": "KeepWritingData (DataAvailable());\n bool DataAvailable()\n{\n return true; //data is ALWAYS available!\n}\n\nvoid KeepWritingData (bool keepGoing)\n{\n if (keepGoing)\n {\n ...\n }\n}\n"
},
{
"answer_id": 135891,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "CommentService.SetApprovalStatus(commentId, false);\n"
},
{
"answer_id": 135911,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 2,
"selected": false,
"text": "dim append as boolean = true\nfile.writeData( data, append );\n dim shouldAppend as boolean = true\nfile.writeData( data, shouldAppend );\n"
},
{
"answer_id": 135917,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 5,
"selected": false,
"text": "lock.setIsLocked(True);\n enum LockState { Locked, Unlocked };\nlock.setLockState(Locked);\n"
},
{
"answer_id": 135987,
"author": "Chris Lundie",
"author_id": 20685,
"author_profile": "https://Stackoverflow.com/users/20685",
"pm_score": 3,
"selected": false,
"text": "file.writeData(data, overwrite=true)\n [file writeData:data overwrite:YES]\n"
},
{
"answer_id": 136107,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 4,
"selected": false,
"text": "ProcessBatch(true, false, false, true, false, false, true);\n public void Write(bool toOptical);\n public void WriteOptical();\npublic void WriteMagnetic();\n Write() Write(Enum.Optical)"
},
{
"answer_id": 136112,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "var worker = new BackgroundWorker(workerReportsProgress: true);\n var worker = new BackgroundWorker { WorkerReportsProgress = true };\n validates_presence_of :name, :allow_nil => true\n connect_to_database( persistent=true )\n"
},
{
"answer_id": 136259,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "WriteMode illegalButWorks = (WriteMode)1000000;\nfile.Write( data, illegalButWorks );\n if (!Enum.IsDefined(typeof(WriteMode), userValue))\n throw new ArgumentException(\"userValue\");\n Enum.IsDefined public static bool CheckWriteModeEnumValue(WriteMode writeMode)\n{\n switch( writeMode )\n {\n case WriteMode.Append:\n case WriteMode.OverWrite:\n break;\n default:\n Debug.Assert(false, \"The WriteMode '\" + writeMode + \"' is not valid.\");\n return false;\n }\n return true;\n}\n [Flags] ToString() Enum.Parse() ToString() Enum.Parse() [Flags]"
},
{
"answer_id": 136637,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 2,
"selected": false,
"text": "public bool IsFoo\npublic bool IsBar\n enum FooBarType { IsFoo, IsBar, IsNeither };\n"
},
{
"answer_id": 137290,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": -1,
"selected": false,
"text": "var v = CallMethod(pData = data, pFileMode = WriteMode, pIsDirty = true);\n"
},
{
"answer_id": 193881,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 0,
"selected": false,
"text": "file.appendData( data ); \nfile.overwriteData( data );\n Enum.Parse(str); \nEnum.Parse(str, true); // ignore case\n Enum.Parse(str, ignoreCase: true);\n"
},
{
"answer_id": 1670946,
"author": "Pascal Thivent",
"author_id": 70604,
"author_profile": "https://Stackoverflow.com/users/70604",
"pm_score": 4,
"selected": false,
"text": "file.append(data) file.overwrite(data)"
},
{
"answer_id": 2525810,
"author": "fastcodejava",
"author_id": 184730,
"author_profile": "https://Stackoverflow.com/users/184730",
"pm_score": -1,
"selected": false,
"text": "true false Enum OVERWRITE APPEND"
},
{
"answer_id": 10653485,
"author": "Haris Krajina",
"author_id": 776301,
"author_profile": "https://Stackoverflow.com/users/776301",
"pm_score": 0,
"selected": false,
"text": "public void writeData(Stream data, boolean is_overwrite)\n"
},
{
"answer_id": 16882897,
"author": "Robert Martin",
"author_id": 895795,
"author_profile": "https://Stackoverflow.com/users/895795",
"pm_score": 0,
"selected": false,
"text": "bool void writeData( DataObject data, bool use_append_mode );\n file.writeData( data, true );\n file.writeData( data, true /* use_append_mode */);\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
] |
135,849
|
<p>I'm trying to host a python script using an apache web server, but the server tries to run the script instead of just offering it for download.</p>
<p>I do not have direct access to server, and adding the line</p>
<pre><code>AddType text/plain .py
</code></pre>
<p>to .htaccess in the root folder does not appear to work, though I could be doing something wrong.</p>
<p>How do I get the server to just send the file as text instead of trying to run it?</p>
<p>-Edit</p>
<p>Changing the name does not work. Script.py.safe still give a 500 Server error when you click it. </p>
<p>I should also mention that the .htaccess file does work, but for some reason that one addType line is not working. Either because it's not overriding something, or the line is wrong.</p>
|
[
{
"answer_id": 135890,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "<IfModule mime_module>\n <Files *.py>\n ForceType text/plain\n </Files>\n</IfModule>\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30/"
] |
135,896
|
<p>Does anyone know of a web site where I can find a list of 32-bit MIPS instructions/opcodes, with the following features:</p>
<ul>
<li>Clearly distinguishes between real opcodes and assembly-language macros (pseudo-instructions)</li>
<li>Describes the instruction behavior including differences depending on privilege level.
<li>Indicates in which instruction set revision the instruction was introduced/revised (e.g. MIPS I, MIPS II, MIPS32, etc.)</li>
<li>Includes privileged instructions such as syscall.</li>
</ul>
<p>I am aware of numerous web sites which document "part of" the instruction set, mostly for teaching purposes. They tend to leave out or only partially describe floating-point and privileged instructions.</p>
<p>In case you're wondering, I'm looking at Verilog code for a MIPS processor subset, and trying to figure out exactly to what extent it complies with the instruction sets of any real MIPS processors!</p>
|
[
{
"answer_id": 136240,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 0,
"selected": false,
"text": "nor"
},
{
"answer_id": 47432637,
"author": "Peter Cordes",
"author_id": 224132,
"author_profile": "https://Stackoverflow.com/users/224132",
"pm_score": 1,
"selected": false,
"text": "balc offset<<2 BALC SWC2 SWC2 COP2 LDXC1 fd, index(base) div dmult ll sc mul mult lwl lwr"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20789/"
] |
135,909
|
<p>I run into this occasionally and always forget how to do it.</p>
<p>One of those things that pop up ever so often.</p>
<p>Also, what's the formula to convert angles expressed in radians to degrees and back again?</p>
|
[
{
"answer_id": 135927,
"author": "thesmallprint",
"author_id": 12765,
"author_profile": "https://Stackoverflow.com/users/12765",
"pm_score": 3,
"selected": false,
"text": "function convert($type, $num) {\n if ($type == \"rads\") {\n $result = $num*180/pi();\n }\n\n if ($type == \"degs\") {\n $result = $num*pi()/180;\n }\n\n return $result;\n }\n"
},
{
"answer_id": 135930,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 9,
"selected": true,
"text": "radians = degrees * (pi/180)\n\ndegrees = radians * (180/pi)\n"
},
{
"answer_id": 135939,
"author": "Axeman",
"author_id": 22108,
"author_profile": "https://Stackoverflow.com/users/22108",
"pm_score": -1,
"selected": false,
"text": "radians = (degrees/360) * 2 * pi\n"
},
{
"answer_id": 9961946,
"author": "Warpling",
"author_id": 522498,
"author_profile": "https://Stackoverflow.com/users/522498",
"pm_score": 1,
"selected": false,
"text": "// deg2rad * degrees = radians\n#define deg2rad (3.14159265/180.0)\n// rad2deg * radians = degrees\n#define rad2deg (180/3.14159265)\n"
},
{
"answer_id": 37829037,
"author": "Rayiez",
"author_id": 2155902,
"author_profile": "https://Stackoverflow.com/users/2155902",
"pm_score": 3,
"selected": false,
"text": "radians = degrees * (Math.PI/180);\n\ndegrees = radians * (180/Math.PI);\n"
},
{
"answer_id": 42229595,
"author": "Koray",
"author_id": 1266873,
"author_profile": "https://Stackoverflow.com/users/1266873",
"pm_score": 0,
"selected": false,
"text": " public static double Conv_DegreesToRadians(this double degrees)\n {\n //return degrees * (Math.PI / 180d);\n return degrees * 0.017453292519943295d;\n }\n public static double Conv_RadiansToDegrees(this double radians)\n {\n //return radians * (180d / Math.PI);\n return radians * 57.295779513082323d;\n }\n"
},
{
"answer_id": 62242217,
"author": "Netsi1964",
"author_id": 192080,
"author_profile": "https://Stackoverflow.com/users/192080",
"pm_score": 0,
"selected": false,
"text": "rad(deg) deg(rad) getAngle(point1,point2) getDistance(point1,point2) x y Object.prototype.rad = (deg) => Math.PI/180 * deg;\nObject.prototype.deg = (rad) => 180/Math.PI * rad;\nObject.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);\nObject.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683/"
] |
135,919
|
<p>I haven't been able to find an adequate answer to what exactly the following error means:</p>
<p><code>java.net.SocketException: Software caused connection abort: recv failed</code> </p>
<p>Notes:</p>
<ul>
<li>This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail.</li>
<li>The only solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case).</li>
<li>The URI is definitely available (as confirmed by asking the browser to do the fetch).</li>
</ul>
<p>Relevant code:</p>
<pre><code>BufferedReader reader;
try {
URL url = new URL(URI);
reader = new BufferedReader(new InputStreamReader(url.openStream())));
} catch( MalformedURLException e ) {
throw new IOException("Expecting a well-formed URL: " + e);
}//end try: Have a stream
String buffer;
StringBuilder result = new StringBuilder();
while( null != (buffer = reader.readLine()) ) {
result.append(buffer);
}//end while: Got the contents.
reader.close();
</code></pre>
|
[
{
"answer_id": 10246311,
"author": "Michael J. Gray",
"author_id": 468904,
"author_profile": "https://Stackoverflow.com/users/468904",
"pm_score": 1,
"selected": false,
"text": "shutdownInput shutdownOutput"
},
{
"answer_id": 25479748,
"author": "Sergio",
"author_id": 3974252,
"author_profile": "https://Stackoverflow.com/users/3974252",
"pm_score": 0,
"selected": false,
"text": "sc.setSoLinger(true, 10);\n setSoLinger()"
},
{
"answer_id": 29322850,
"author": "rustyx",
"author_id": 485343,
"author_profile": "https://Stackoverflow.com/users/485343",
"pm_score": 4,
"selected": false,
"text": "URL.open() HttpClient httpClient = HttpClients.custom()\n .setConnectionTimeToLive(20, TimeUnit.SECONDS)\n .setMaxConnTotal(400).setMaxConnPerRoute(400)\n .setDefaultRequestConfig(RequestConfig.custom()\n .setSocketTimeout(30000).setConnectTimeout(5000).build())\n .setRetryHandler(new DefaultHttpRequestRetryHandler(5, true))\n .build();\n// the httpClient should be re-used because it is pooled and thread-safe.\n\nHttpGet request = new HttpGet(uri);\nHttpResponse response = httpClient.execute(request);\nreader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));\n// handle response ...\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12815/"
] |
135,929
|
<p>I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell.</p>
<pre><code>declare @ConstraintName varchar(255)
set @ConstraintName = 'PK_Whatever'
IF LEFT(@ConstraintName, 2) = 'PK'
BEGIN
--can't drop primary keys
END
</code></pre>
<p>The error I get is:</p>
<pre><code>Incorrect syntax near 'END'.
</code></pre>
<p>If I add something after the comment, i.e. <code>PRINT @ConstraintName</code>, it works fine.</p>
|
[
{
"answer_id": 135962,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "BEGIN\n -- This is a comment\n NULL;\nEND\n"
},
{
"answer_id": 139140,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 1,
"selected": false,
"text": "declare @ConstraintName varchar(255)\nset @ConstraintName = 'PK_Whatever'\n\n--can't drop primary keys\nIF LEFT(@ConstraintName, 2) = 'PK'\nBEGIN\n --do nothing here\n DECLARE @Dummy bit --required to compile\nEND\n"
},
{
"answer_id": 140477,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "If left(@constraintname,2 <> 'PK'\nBEGIN\n -- Drop your constraint here\n ALTER TABLE dbo.mytable DROP constraint ... -- etc\nEND\n"
},
{
"answer_id": 141005,
"author": "GilM",
"author_id": 10192,
"author_profile": "https://Stackoverflow.com/users/10192",
"pm_score": 2,
"selected": false,
"text": "SELECT NULL IF LEFT(@ConstraintName, 2) = 'PK'\nBEGIN\n DECLARE @Dummy bit -- Do nothing here, but this is required to compile\nEND\n"
},
{
"answer_id": 497854,
"author": "Omer Bokhari",
"author_id": 56829,
"author_profile": "https://Stackoverflow.com/users/56829",
"pm_score": 0,
"selected": false,
"text": "-- drop only if not primary\nIF LEFT (@ConstraintName, 2) <> 'PK'\nBEGIN\n --do something here\nEND\n"
},
{
"answer_id": 19792263,
"author": "Alex KeySmith",
"author_id": 141022,
"author_profile": "https://Stackoverflow.com/users/141022",
"pm_score": 2,
"selected": false,
"text": "BEGIN\n DONOTHING:\nEND\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73794/"
] |
135,934
|
<p>I need to show a camera capture dialog in a compact framework 3.7 application by pinvoking SHCameraCapture from the dll Aygshell.dll. I cannont use the managed object CameraCaptureDialog because of limitations with the technology I'm working with. Instead, I need to access it by Pinvoking it.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/aa454995.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa454995.aspx</a> for documentation on the function. The function takes in a struct that defines the parameters of the dialog. e.g. where to save the file, what resolution to use.</p>
<p>I would imaging that I would have to define a copy of the struct in C# and decorate the sturct with the attribute StructLayout. I also imagine that the code would involve [DllImport("aygshell.dll")]. Any sample code of how to call this would be much appreciated.</p>
|
[
{
"answer_id": 138398,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 0,
"selected": false,
"text": "struct SHCAMERACAPTURE {\n public Int32 cbSize;\n public IntPtr hwndOwner;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] \n public string szFile;\n\n [MarshalAs(UnmanagedType.LPStr)] \n string pszInitialDir;\n\n [MarshalAs(UnmanagedType.LPStr)] \n string pszDefaultFileName;\n\n [MarshalAs(UnmanagedType.LPStr)] \n string pszTitle;\n\n Int32 StillQuality;\n Int32 VideoTypes;\n Int32 nResolutionWidth;\n Int32 nResolutionHeight;\n Int32 nVideoTimeLimit;\n Int32 Mode;\n}\n\n[DllImport(\"aygshell.dll\")]\nstatic extern int SHCameraCapture(ref SHCAMERACAPTURE pshcc);\n"
},
{
"answer_id": 140281,
"author": "Peter Walke",
"author_id": 12497,
"author_profile": "https://Stackoverflow.com/users/12497",
"pm_score": 1,
"selected": false,
"text": "public partial class Form1 : Form\n{\n [DllImport(\"aygshell.dll\")]\n static extern int SHCameraCapture(ref SHCAMERACAPTURE pshcc);\n\n [StructLayout(LayoutKind.Sequential)]\n struct SHCAMERACAPTURE\n {\n public Int32 cbSize;\n public IntPtr hwndOwner;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string szFile;\n [MarshalAs(UnmanagedType.LPStr)]\n public string pszInitialDir;\n [MarshalAs(UnmanagedType.LPStr)]\n public string pszDefaultFileName;\n [MarshalAs(UnmanagedType.LPStr)]\n public string pszTitle;\n public Int32 StillQuality;\n public Int32 VideoTypes;\n public Int32 nResolutionWidth;\n public Int32 nResolutionHeight;\n public Int32 nVideoTimeLimit;\n public Int32 Mode;\n }\n private void ShowCamera()\n {\n SHCAMERACAPTURE captureData = new SHCAMERACAPTURE\n {\n cbSize = sizeof (Int64),\n hwndOwner = (IntPtr)0,\n szFile = \"\\\\My Documents\",\n pszDefaultFileName = \"picture.jpg\",\n pszTitle = \"Camera Demo\",\n StillQuality = 0,\n VideoTypes = 1,\n nResolutionWidth = 480,\n nResolutionHeight = 640,\n nVideoTimeLimit = 0,\n Mode = 0\n };\n SHCameraCapture(ref captureData);\n }\n private void button1_Click(object sender, EventArgs e)\n {\n ShowCamera();\n }\n"
},
{
"answer_id": 619763,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "#region Enumerations\n\npublic enum CAMERACAPTURE_STILLQUALITY\n{\n CAMERACAPTURE_STILLQUALITY_DEFAULT = 0,\n CAMERACAPTURE_STILLQUALITY_LOW = 1,\n CAMERACAPTURE_STILLQUALITY_NORMAL = 2,\n CAMERACAPTURE_STILLQUALITY_HIGH = 3\n}\npublic enum CAMERACAPTURE_VIDEOTYPES\n{\n CAMERACAPTURE_VIDEOTYPE_ALL = 0xFFFF,\n CAMERACAPTURE_VIDEOTYPE_STANDARD = 1,\n CAMERACAPTURE_VIDEOTYPE_MESSAGING = 2\n}\n\npublic enum CAMERACAPTURE_MODE\n{\n CAMERACAPTURE_MODE_STILL = 0,\n CAMERACAPTURE_MODE_VIDEOONLY = 1,\n CAMERACAPTURE_MODE_VIDEOWITHAUDIO = 2\n}\n\n#endregion //Enumerations\n\n#region Structures\n\n[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]\npublic struct struSHCAMERACAPTURE\n{\n public uint cbSize;\n public IntPtr hwndOwner;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public String szFile;\n [MarshalAs(UnmanagedType.LPTStr)]\n public String pszInitialDir; //LPCTSTR\n [MarshalAs(UnmanagedType.LPTStr)]\n public String pszDefaultFileName; //LPCTSTR\n [MarshalAs(UnmanagedType.LPTStr)]\n public String pszTitle; //LPCTSTR\n public CAMERACAPTURE_STILLQUALITY StillQuality;\n public CAMERACAPTURE_VIDEOTYPES VideoTypes;\n public uint nResolutionWidth;\n public uint nResolutionHeight;\n public uint nVideoTimeLimit;\n public CAMERACAPTURE_MODE Mode;\n}\n#endregion //Structures\n\n#region API\n[DllImport(\"Aygshell.dll\", SetLastError = true,CharSet=CharSet.Unicode)]\npublic static extern int SHCameraCapture\n(\n ref struSHCAMERACAPTURE pshCamCapture\n);\n\nprivate string StartImager(String strImgDir, String strImgFile, uint uintImgHeight,\n uint uintImgWidth)\n\ntry\n{\n struSHCAMERACAPTURE shCamCapture = new struSHCAMERACAPTURE();\n\n shCamCapture.cbSize = (uint)Marshal.SizeOf(shCamCapture);\n shCamCapture.hwndOwner = IntPtr.Zero;\n shCamCapture.szFile = \"\\\\\" + strImgFile; //strImgDir + \"\\\\\" + strImgFile;\n shCamCapture.pszInitialDir = \"\\\\\"; // strImgDir;\n shCamCapture.pszDefaultFileName = strImgFile;\n shCamCapture.pszTitle = \"PTT Image Capture\";\n shCamCapture.StillQuality = 0; // CAMERACAPTURE_STILLQUALITY.CAMERACAPTURE_STILLQUALITY_NORMAL;\n shCamCapture.VideoTypes = CAMERACAPTURE_VIDEOTYPES.CAMERACAPTURE_VIDEOTYPE_STANDARD;\n shCamCapture.nResolutionHeight = 0; // uintImgHeight;\n shCamCapture.nResolutionWidth = 0; // uintImgWidth;\n shCamCapture.nVideoTimeLimit = 10;\n shCamCapture.Mode = 0; // CAMERACAPTURE_MODE.CAMERACAPTURE_MODE_STILL;\n\n //IntPtr intptrCamCaptr = IntPtr.Zero;\n\n //Marshal.StructureToPtr(shCamCapture, intptrCamCaptr, true);\n\n int intResult = SHCameraCapture(ref shCamCapture);\n if (intResult != 0)\n {\n Win32Exception Win32 = new Win32Exception(intResult);\n MessageBox.Show(\"Error: \" + Win32.Message);\n } \n\n return strCaptrErr;\n}\n\ncatch (Exception ex)\n{\n MessageBox.Show(\"Error StartImager : \" + ex.ToString() + \" - \" + strCaptrErr\n , \"Nomad Imager Test\");\n return \"\";\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12497/"
] |
135,938
|
<p>It's not a matter of life or death but I wonder if this could be possible:</p>
<p>I got a couple of events from one type of custom event (FormEvent) now I got a FormListener that listens to all those events and handles them according to the event type. Instead of adding one eventListener at the time I wish to add all events at once.</p>
<p>so now it looks like this:</p>
<pre><code> private function addListeners():void {
addEventListener(FormEvent.SHOW_FORM, formListener);
addEventListener(FormEvent.SEND_FORM, formListener);
addEventListener(FormEvent.CANCEL_FORM, formListener);
}
private function formListener(event:formEvent):void {
switch(event.type){
case "show.form":
// handle show form stuff
break;
case "send.form":
// handle send form stuff
break;
case "cancel.form":
// handle cancel form stuff
break;
}
}
</code></pre>
<p>but instead of adding every event one at the time I would rather be doing something like</p>
<pre><code> private function addListeners():void {
addEventListener(FormEvent.*, formListener);
}
</code></pre>
<p>I wonder if something like this is possible, i would love it. I work with loads of events :)</p>
|
[
{
"answer_id": 136258,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 0,
"selected": false,
"text": "private function addMultipleEventListeners( evts:Array, callback:function ):void\n{\n for each( var evt:Event in evts )\n {\n addEventListener( evt, callback );\n }\n}\n var evts:Array = [ FormEvent.SHOW_FORM, FormEvent.SEND_FORM, FormEvent.CANCEL_FORM ];\naddMultipleEventListeners( evts, formListener );\n"
},
{
"answer_id": 137417,
"author": "Brian Hodge",
"author_id": 20628,
"author_profile": "https://Stackoverflow.com/users/20628",
"pm_score": 4,
"selected": true,
"text": "\npackage com.yourDomain.events\n{\n import flash.events.Event;\n public class FormEvent extends Event\n {\n //Public Properties\n public static const CANCEL_FORM:int = \"0\";\n public static const SHOW_FORM:int = \"1\";\n public static const SEND_FORM:int = \"2\";\n\n public static const STATE_CHANGED:String = \"stateChanged\";\n\n //Private Properties\n private var formState:int;\n\n public function FormEvent(formState:int):void\n {\n super(STATE_CHANGED);\n formState = formState;\n }\n }\n}\n \npackage com.yourDomain.ui\n{\n import flash.events.Event;\n import flash.events.EventDispatcher;\n import com.yourDomain.events.FormEvent;\n public class Form extends EventDispatcher\n {\n public function Form():void\n {\n //Anything you want form to do upon instantiation goes here.\n }\n public function cancelForm():void\n {\n dispatchEvent(new Event(FormEvent.CANCEL_FORM);\n }\n public function showForm():void\n {\n dispatchEvent(new Event(FormEvent.SHOW_FORM);\n }\n public function sendForm():void\n {\n dispatchEvent(new Event(FormEvent.SEND_FORM);\n }\n }\n}\n \npackage com.yourDomain.ui\n{\n import com.yourDomain.ui.Form;\n import com.yourDomain.events.FormEvent;\n //Form is in the same package so we need not import it.\n public class MainDocumentClass\n {\n private var _theForm:Form;\n\n public function MainDocumentClass():void\n {\n _theForm = new Form();\n _theForm.addEventListener(FormEvent.STATE_CHANGED, onFormStateChange, false, 0, true);\n /*\n The following three method calls each cause the\n FormEvent.STATE_CHANGE event to be dispatched. \n onFormStateChange is notified and checks what \n the last change actually was.\n */\n _theForm.cancelForm();\n _theForm.showForm();\n _theForm.sendForm();\n }\n private function onFormStateChange(e:FormEvent):void\n {\n switch(e.formState)\n {\n case CANCEL_FORM:\n trace('The form was canceled');\n break;\n case SHOW_FORM:\n trace('The form was revealed');\n break;\n case SEND_FORM:\n trace('The form was sent');\n break;\n }\n }\n } \n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
] |
135,944
|
<p>Stored procs in SQL Server sometimes finish with a return code, as opposed to a recordset of data. I've seen ASP code that's able to get this return code, but I can't figure out how to get this code with PHP's mssql driver.</p>
<p>mssql_get_last_message() always returns nothing, and I'm thinking it's because it only returns the very last line that came from the server. When we run the proc in another application (outside PHP), there is blank line following the return code.</p>
<p>Has anyone figured out how to get return codes from SQL stored procs using PHP's mssql driver?</p>
|
[
{
"answer_id": 135963,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": true,
"text": "DECLARE @return_code INT\nEXEC @return_code = your_stored_procedure 1123\nSELECT @return_code\n"
},
{
"answer_id": 135972,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "SELECT @@ERROR AS ErrorCode\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12308/"
] |
135,971
|
<p>If you have two jars in your classpath that contain different versions of the same class, the classpath order becomes critical.</p>
<p>I am looking for a tool that can detect and flag such potential conflicts in a given classpath or set of folders.</p>
<p>Certainly a script that starts:</p>
<pre><code>classes=`mktemp`
for i in `find . -name "*.jar"`
do
echo "File: $i" > $classes
jar tf $i > $classes
...
done
</code></pre>
<p>with some clever sort/uniq/diff/grep/awk later on has potential, but I was wondering if anyone knows of any existing solutions.</p>
|
[
{
"answer_id": 136292,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 2,
"selected": false,
"text": "import java.io.*;\nimport java.util.zip.*;\n\n\npublic class ListZipContent{\n public static void main( String [] args ) throws IOException {\n System.out.println( \"start \" + new java.util.Date() );\n String pattern = args.length == 1 ? args[0] : \"OracleDriver.class\";// Guess which class I was looking for :) \n File file = new File(\".\");\n FileFilter fileFilter = new FileFilter(){\n public boolean accept( File file ){\n return file.isDirectory() || file.getName().endsWith( \"jar\" );\n }\n };\n Command command = new Command( pattern );\n executeRecursively( command, file, fileFilter );\n System.out.println( \"finish \" + new java.util.Date() );\n }\n private static void executeRecursively( Command command, File dir , FileFilter filter ) throws IOException {\n if( !dir.isDirectory() ){\n System.out.println( \"not a directory \" + dir );\n return;\n }\n for( File file : dir.listFiles( filter ) ){\n if( file.isDirectory()){\n executeRecursively( command,file , filter );\n }else{\n command.executeOn( file );\n }\n }\n }\n}\nclass Command {\n\n private String pattern;\n public Command( String pattern ){\n this.pattern = pattern;\n }\n\n public void executeOn( File file ) throws IOException {\n if( pattern == null ) { \n System.out.println( \"Pattern is null \");\n return;\n }\n\n String fileName = file.getName();\n boolean jarNameAlreadyPrinted = false;\n\n ZipInputStream zis = null;\n try{\n zis = new ZipInputStream( new FileInputStream( file ) );\n\n ZipEntry ze;\n while(( ze = zis.getNextEntry() ) != null ) {\n if( ze.getName().endsWith( pattern )){\n if( !jarNameAlreadyPrinted ){\n System.out.println(\"Contents of: \" + file.getCanonicalPath() );\n jarNameAlreadyPrinted = true;\n }\n System.out.println( \" \" + ze.getName() );\n }\n zis.closeEntry();\n }\n }finally{\n if( zis != null ) try {\n zis.close();\n }catch( Throwable t ){}\n }\n }\n}\n"
},
{
"answer_id": 37078036,
"author": "Chris Seline",
"author_id": 738764,
"author_profile": "https://Stackoverflow.com/users/738764",
"pm_score": 2,
"selected": false,
"text": "ls *.jar | xargs -n1 -iFILE unzip -l FILE | grep class | sed \"s,.* ,,\" | tr \"/\" \".\" | sort | uniq -d | xargs -n1 -iCLASS grep -l CLASS *.jar | sort -u\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
] |
135,995
|
<p>So, I want to define a singleton method for an object, but I want to do it using a closure.</p>
<p>For example,</p>
<pre><code>def define_say(obj, msg)
def obj.say
puts msg
end
end
o = Object.new
define_say o, "hello world!"
o.say
</code></pre>
<p>This doesn't work because defining a singleton method via "def" is not a closure, so I get an exception that "msg" is an undefined variable or method.</p>
<p>What I would like to do is something like using the "define_method" method in the Module class, but as far as I can tell, this can only be used to define a method on a class... but I want a Singleton Method...</p>
<p>So, I would love to write it something like this:</p>
<pre><code>def define_say(obj, msg)
obj.define_singleton_method(:say) {
puts msg
}
end
</code></pre>
<p>Does anyone know how I can achieve this without having to create a method to store a Proc and then use the Proc within a singleton method? (basically, I want a clean, non-hacky way of doing this)</p>
|
[
{
"answer_id": 136194,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "def define_say(obj, msg)\n # Get a handle to the singleton class of obj\n metaclass = class << obj; self; end \n\n # add the method using define_method instead of def x.say so we can use a closure\n metaclass.send :define_method, :say do\n puts msg\n end\nend\n >> s = \"my string\"\n=> \"my string\"\n>> define_say(s, \"I am S\")\n=> #<Proc:0xb6ed55b0@(irb):11>\n>> s.say\nI am S\n=> nil\n"
},
{
"answer_id": 6447238,
"author": "asymmetric",
"author_id": 112538,
"author_profile": "https://Stackoverflow.com/users/112538",
"pm_score": 4,
"selected": false,
"text": "Object#define_singleton_method def define_say(obj, msg)\n obj.define_singleton_method(:say) do\n puts msg\n end\nend\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/135995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
136,033
|
<p>I despise the PHP language, and I'm quite certain that I'm not alone. But the great thing about PHP is the way that mod_php takes and hides the gory details of integrating with the apache runtime, and achieves CGI-like request isolation and decent performance.</p>
<p>What's the shortest-distance approach to getting the same simplicity, speed and isolation as PHP's runtime environment, with Perl semantics? I feel like raw mod_perl gives me too much rope to hang myself with: cross-request globals, messy config, too many template engines to choose from. </p>
<p>FastCGI? HTML::Mason? I'd like to do development largely in Perl, if only I had a framework that let me.</p>
|
[
{
"answer_id": 137293,
"author": "Zed",
"author_id": 19202,
"author_profile": "https://Stackoverflow.com/users/19202",
"pm_score": 2,
"selected": false,
"text": "<html> <body> <p>The value of 2+2 is: <?php echo 2+2; ?></p> </body></html> The value of 2+2 is: 4 <html><body><p>The value of 2+2 is: <% 2+2 %></p></body></html>"
},
{
"answer_id": 139363,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 2,
"selected": false,
"text": "use CGI;\nuse DBI;\n $_POST['param']\n$_GET['param']\n my $q = new CGI;\n$q->param('param'); # same for post or get\n $dbh = mysql_connect('localhost', 'mysql_user', 'mysql_password');\n$sth = mysql_query(\"SELECT 1 FROM table\", $dbh);\nwhile($row = mysql_fetch_assoc($sth))\n{\n // do something with $row\n}\n my $dbh = DBI->connect('DBI:mysql:host=localhost;', 'mysql_user', 'mysql_password');\nmy $sth = $dbh->prepare(\"SELECT 1 FROM table\");\n$sth->execute();\nwhile(my $row = $sth->fetchrow_hashref)\n{\n # do stuff with row\n}\n"
},
{
"answer_id": 139938,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 3,
"selected": false,
"text": "% my $noun = 'World';\nHello <% $noun %>!\nHow are ya?\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22369/"
] |
136,034
|
<p>I've looked around for a good example of this, but I haven't run into one yet. I want to pass a custom string array from java to oracle and back, using the IBATIS framework. Does anyone have a good link to an example? I'm calling stored procs from IBATIS.</p>
<p>Thanks</p>
|
[
{
"answer_id": 137693,
"author": "bsanders",
"author_id": 22200,
"author_profile": "https://Stackoverflow.com/users/22200",
"pm_score": 2,
"selected": false,
"text": "TypeHandler TypeHandlerCallback Connection public class ArrayTypeHandler implements TypeHandler {\n\n public void setParameter(PreparedStatement ps, int i, Object param, String jdbcType)\n throws SQLException {\n if (param == null) {\n ps.setNull(i, Types.ARRAY);\n } else {\n Connection conn = ps.getConnection();\n Array loc = conn.createArrayOf(\"myArrayType\", (Object[]) param);\n ps.setArray(i, loc);\n }\n }\n\n public Object getResult(CallableStatement statement, int i)\n throws SQLException {\n return statement.getArray(i).getArray();\n }\n ...\n}\n <?xml version=\"1.0\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"arrayTest\">\n\n <parameterMap id=\"storedprocParams\" class=\"map\">\n <parameter property=\"result\" mode=\"OUT\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/>\n <parameter property=\"argument\" mode=\"IN\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/>\n </parameterMap>\n\n <procedure id=\"storedproc\" parameterMap=\"arrayTest.storedprocParams\">\n {? = call My_Array_Function( ? )}\n </procedure>\n\n</sqlMap>\n"
},
{
"answer_id": 150572,
"author": "Justin",
"author_id": 22365,
"author_profile": "https://Stackoverflow.com/users/22365",
"pm_score": 2,
"selected": false,
"text": "public Object getResult(CallableStatement statement, int i) throws SQLException {\n return statement.getArray(i).getArray(); //getting null pointer exception here\n}\n\npublic void setParameter(PreparedStatement ps, int i, Object param, String jdbcType) throws SQLException {\n if (param == null) {\n ps.setNull(i, Types.ARRAY);\n\n } else {\n String[] a = (String[]) param;\n //ARRAY aOracle = ARRAY.toARRAY(a, (OracleConnection)ps.getConnection());\n\n //com.ibm.ws.rsadapter.jdbc.WSJdbcConnection\n w = (com.ibm.ws.rsadapter.jdbc.WSJdbcConnection)ps.getConnection());\n\n //com.ibm.ws.rsadapter.jdbc.WSJdbcObject x;\n Connection nativeConnection = Connection)WSJdbcUtil.getNativeConnection((WSJdbcConnection)ps.getConnection());\n\n ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor(\"F2_LIST\", nativeConnection);\n ARRAY dataArray = new ARRAY(descriptor, nativeConnection, a);\n ps.setArray(i, dataArray);\n }\n}\n --stored procedure to take a | delimited ids\n PROCEDURE array_test (argument IN f2_list, result OUT f2_list) \n AS\n l_procname_v VARCHAR2 (50) := 'array_test';\n l_param_list VARCHAR2 (2000)\n := l_procname_v || ' param_values: p_string: ';\n\n p_status_n NUMBER;\n p_message_v VARCHAR2 (2000);\n ret_list f2_list := new f2_list();\n l_count_v varchar2(200);\n BEGIN\n\n l_count_v := argument.COUNT;\n for x in 1..argument.count\n LOOP\n pkg_az_common_util.az_debug (package_nm,\n l_procname_v,\n pkg_az_data_type_def.debug_num,\n argument(x)\n );\n end loop;\n\n pkg_az_common_util.az_debug (package_nm,\n l_procname_v,\n pkg_az_data_type_def.debug_num,\n l_count_v\n );\n ret_list.extend();\n ret_list(1) := 'W';\n ret_list.extend();\n ret_list(2) := 'X';\n ret_list.extend();\n ret_list(3) := 'Y';\n ret_list.extend();\n ret_list(4) := 'Z';\n\n result := ret_list;\n\n\n EXCEPTION\n WHEN OTHERS\n THEN\n p_status_n := pkg_az_common_util.get_error_code;\n p_message_v :=\n TO_CHAR (p_status_n)\n || '|'\n || 'Oracle Internal Exception('\n || l_procname_v\n || ')'\n || '|'\n || TO_CHAR (SQLCODE)\n || '|'\n || SQLERRM\n || l_param_list;\n standard_pkg.log_error (package_nm,\n l_procname_v,\n SQLCODE,\n p_message_v\n );\n\n IF p_status_n = 1\n THEN\n RAISE;\n END IF;\n END array_test;\n Map queryParamsTest = new HashMap();\n\n String[] testArray = {\"A\", \"B\", \"C\"};\n\n queryParamsTest.put(\"argument\", testArray);\n\n\n\n DaoUtils.executeQuery(super.getSqlMapClientTemplate(),\n \"arrayTest\", queryParamsTest, queryParamsTest\n .toString()); //just executes query\n\n\n String[] resultArray = (String[])queryParamsTest.get(\"result\");\n\n for(int x = 0; x< resultArray.length; x++)\n {\n System.out.println(\"Result: \" + resultArray[x]);\n }\n\n\n\n<parameterMap id=\"storedprocParams\" class=\"map\"> \n <parameter property=\"argument\" mode=\"IN\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/> \n <parameter property=\"result\" mode=\"OUT\" jdbcType=\"ARRAY\" typeHandler=\"ArrayTypeHandler\"/> \n </parameterMap> \n <procedure id=\"arrayTest\" parameterMap=\"storedprocParams\"> \n {call pkg_az_basic_dev.array_test(?, ? )} \n </procedure>\n"
},
{
"answer_id": 153452,
"author": "bsanders",
"author_id": 22200,
"author_profile": "https://Stackoverflow.com/users/22200",
"pm_score": 0,
"selected": false,
"text": "statement.getObject(i)"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22365/"
] |
136,035
|
<p>It is discouraged to simply catch <code>System.Exception</code>. Instead, only the "known" exceptions should be caught.</p>
<p>Now, this sometimes leads to unnecessary repetitive code, for example:</p>
<pre><code>try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
</code></pre>
<p>I wonder: Is there a way to catch both exceptions and only call the <code>WebId = Guid.Empty</code> call once?</p>
<p>The given example is rather simple, as it's only a <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" rel="noreferrer"><code>GUID</code></a>. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the <code>object</code>. However, if there is an unexpected exception, I still want to throw that higher.</p>
|
[
{
"answer_id": 136038,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": false,
"text": "catch (Exception ex)\n{\n switch (ex.GetType().Name)\n {\n case \"System.FormatException\":\n case \"System.OverflowException\":\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n}\n"
},
{
"answer_id": 136046,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": 4,
"selected": false,
"text": "try\n{\n WebId = Guid.Empty;\n WebId = new Guid(queryString[\"web\"]);\n}\ncatch (FormatException)\n{\n}\ncatch (OverflowException)\n{\n}\n"
},
{
"answer_id": 136092,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 12,
"selected": true,
"text": "System.Exception catch (Exception ex) \n{ \n if (ex is FormatException || ex is OverflowException)\n {\n WebId = Guid.Empty;\n return;\n }\n \n throw;\n}\n"
},
{
"answer_id": 136094,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "catch (Exception ex)\n{\n Type exType = ex.GetType();\n if (exType == typeof(System.FormatException) || \n exType == typeof(System.OverflowException)\n {\n WebId = Guid.Empty;\n } else {\n throw;\n }\n}\n"
},
{
"answer_id": 136114,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 8,
"selected": false,
"text": "Catch ex As Exception When TypeOf ex Is FormatException OrElse TypeOf ex Is OverflowException\n Action onError = () => WebId = Guid.Empty;\ntry\n{\n // something\n}\ncatch (FormatException)\n{\n onError();\n}\ncatch (OverflowException)\n{\n onError();\n}\n"
},
{
"answer_id": 419531,
"author": "Konstantin Spirin",
"author_id": 1423922,
"author_profile": "https://Stackoverflow.com/users/1423922",
"pm_score": 5,
"selected": false,
"text": "catch (Exception ex) when (ex is FormatException or OverflowException)\n{\n WebId = Guid.Empty;\n}\n catch (Exception ex)\n{\n if (ex is not FormatException and not OverflowException)\n throw;\n\n WebId = Guid.Empty;\n}\n"
},
{
"answer_id": 3373810,
"author": "Matt",
"author_id": 179310,
"author_profile": "https://Stackoverflow.com/users/179310",
"pm_score": 4,
"selected": false,
"text": "bool exThrown = false;\n\ntry\n{\n // Something\n}\ncatch (FormatException) {\n exThrown = true;\n}\ncatch (OverflowException) {\n exThrown = true;\n}\n\nif (exThrown)\n{\n // Something else\n}\n"
},
{
"answer_id": 12222312,
"author": "bsara",
"author_id": 1203288,
"author_profile": "https://Stackoverflow.com/users/1203288",
"pm_score": 4,
"selected": false,
"text": "public void TryCatch(...)\n{\n try\n {\n // something\n return;\n }\n catch (FormatException) {}\n catch (OverflowException) {}\n\n WebId = Guid.Empty;\n}\n WebId = Guid.Empty; ...\ncatch (Exception)\n{\n // something, if anything\n return; // only need this if you follow the example I gave and put it all in a method\n}\n"
},
{
"answer_id": 15987704,
"author": "Athari",
"author_id": 293099,
"author_profile": "https://Stackoverflow.com/users/293099",
"pm_score": 7,
"selected": false,
"text": "Guid.TryParse(queryString[\"web\"], out WebId);\n Guid.Empty Guid.TryParse(queryString[\"web\"], out Guid webId);\n (bool success, Guid result) TryParseGuid(string input) =>\n (Guid.TryParse(input, out Guid result), result);\n WebId = TryParseGuid(queryString[\"web\"]).result;\n// or\nvar tuple = TryParseGuid(queryString[\"web\"]);\nWebId = tuple.success ? tuple.result : DefaultWebId;\n"
},
{
"answer_id": 16623758,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 4,
"selected": false,
"text": "static void Main() \n{ \n Action body = () => { ...your code... };\n\n body.Catch<InvalidOperationException>() \n .Catch<BadCodeException>() \n .Catch<AnotherException>(ex => { ...handler... })(); \n}\n Catch"
},
{
"answer_id": 19329123,
"author": "Craig Tullis",
"author_id": 618649,
"author_profile": "https://Stackoverflow.com/users/618649",
"pm_score": 10,
"selected": false,
"text": "catch (Exception ex) when (ex is ... || ex is ... ) catch (Exception ex) when (\n ex is ...\n || ex is ...\n || ex is ...\n)\n private void TestMethod ()\n{\n Action<Exception> errorHandler = ( ex ) => {\n // write to a log, whatever...\n };\n\n try\n {\n // try some stuff\n }\n catch ( FormatException ex ) { errorHandler ( ex ); }\n catch ( OverflowException ex ) { errorHandler ( ex ); }\n catch ( ArgumentNullException ex ) { errorHandler ( ex ); }\n}\n try\n{\n // try some stuff\n}\ncatch( FormatException ex ){}\ncatch( OverflowException ex ){}\ncatch( ArgumentNullException ex ){}\n // sorta sucks, let's be honest...\ntry\n{\n // try some stuff\n}\ncatch( Exception ex )\n{\n if (ex is FormatException ||\n ex is OverflowException ||\n ex is ArgumentNullException)\n {\n // write to a log, whatever...\n return;\n }\n throw;\n}\n /* write to a log, whatever... */ return; ErrorHandler if is if // super sucks...\ncatch( Exception ex )\n{\n if ( ex is FormatException || ex is OverflowException || ex is ArgumentNullException )\n {\n // write to a log, whatever...\n return;\n }\n throw;\n}\n"
},
{
"answer_id": 20253816,
"author": "HodlDwon",
"author_id": 1718702,
"author_profile": "https://Stackoverflow.com/users/1718702",
"pm_score": 3,
"selected": false,
"text": "type || ex is ... if (ex.GetType().IsAnyOf(\n typeof(FormatException),\n typeof(ArgumentException)))\n{\n // Handle\n}\nelse\n throw;\n namespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter matches at least one of the passed in comparisons.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_comparisons\">Values to compare against.</param>\n /// <returns>True if a match is found.</returns>\n /// <exception cref=\"ArgumentNullException\"></exception>\n public static bool IsAnyOf<T>(this T p_parameter, params T[] p_comparisons)\n {\n // Validate\n p_parameter\n .CannotBeNull(\"p_parameter\");\n p_comparisons\n .CannotBeNullOrEmpty(\"p_comparisons\");\n\n // Test for any match\n foreach (var item in p_comparisons)\n if (p_parameter.Equals(item))\n return true;\n\n // Return no matches found\n return false;\n }\n }\n}\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Common.FluentValidation;\n\nnamespace IsAnyOfExceptionHandlerSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n // High Level Error Handler (Log and Crash App)\n try\n {\n Foo();\n }\n catch (OutOfMemoryException ex)\n {\n Console.WriteLine(\"FATAL ERROR! System Crashing. \" + ex.Message);\n Console.ReadKey();\n }\n }\n\n static void Foo()\n {\n // Init\n List<Action<string>> TestActions = new List<Action<string>>()\n {\n (key) => { throw new FormatException(); },\n (key) => { throw new ArgumentException(); },\n (key) => { throw new KeyNotFoundException();},\n (key) => { throw new OutOfMemoryException(); },\n };\n\n // Run\n foreach (var FooAction in TestActions)\n {\n // Mid-Level Error Handler (Appends Data for Log)\n try\n {\n // Init\n var SomeKeyPassedToFoo = \"FooParam\";\n\n // Low-Level Handler (Handle/Log and Keep going)\n try\n {\n FooAction(SomeKeyPassedToFoo);\n }\n catch (Exception ex)\n {\n if (ex.GetType().IsAnyOf(\n typeof(FormatException),\n typeof(ArgumentException)))\n {\n // Handle\n Console.WriteLine(\"ex was {0}\", ex.GetType().Name);\n Console.ReadKey();\n }\n else\n {\n // Add some Debug info\n ex.Data.Add(\"SomeKeyPassedToFoo\", SomeKeyPassedToFoo.ToString());\n throw;\n }\n }\n }\n catch (KeyNotFoundException ex)\n {\n // Handle differently\n Console.WriteLine(ex.Message);\n\n int Count = 0;\n if (!Validate.IsAnyNull(ex, ex.Data, ex.Data.Keys))\n foreach (var Key in ex.Data.Keys)\n Console.WriteLine(\n \"[{0}][\\\"{1}\\\" = {2}]\",\n Count, Key, ex.Data[Key]);\n\n Console.ReadKey();\n }\n }\n }\n }\n}\n\nnamespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter matches at least one of the passed in comparisons.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_comparisons\">Values to compare against.</param>\n /// <returns>True if a match is found.</returns>\n /// <exception cref=\"ArgumentNullException\"></exception>\n public static bool IsAnyOf<T>(this T p_parameter, params T[] p_comparisons)\n {\n // Validate\n p_parameter\n .CannotBeNull(\"p_parameter\");\n p_comparisons\n .CannotBeNullOrEmpty(\"p_comparisons\");\n\n // Test for any match\n foreach (var item in p_comparisons)\n if (p_parameter.Equals(item))\n return true;\n\n // Return no matches found\n return false;\n }\n\n /// <summary>\n /// Validates if any passed in parameter is equal to null.\n /// </summary>\n /// <param name=\"p_parameters\">Parameters to test for Null.</param>\n /// <returns>True if one or more parameters are null.</returns>\n public static bool IsAnyNull(params object[] p_parameters)\n {\n p_parameters\n .CannotBeNullOrEmpty(\"p_parameters\");\n\n foreach (var item in p_parameters)\n if (item == null)\n return true;\n\n return false;\n }\n }\n}\n\nnamespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter is not null, throwing a detailed exception message if the test fails.\n /// </summary>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_name\">Name of tested parameter to assist with debugging.</param>\n /// <exception cref=\"ArgumentNullException\"></exception>\n public static void CannotBeNull(this object p_parameter, string p_name)\n {\n if (p_parameter == null)\n throw\n new\n ArgumentNullException(\n string.Format(\"Parameter \\\"{0}\\\" cannot be null.\",\n p_name), default(Exception));\n }\n }\n}\n\nnamespace Common.FluentValidation\n{\n public static partial class Validate\n {\n /// <summary>\n /// Validates the passed in parameter is not null or an empty collection, throwing a detailed exception message if the test fails.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_name\">Name of tested parameter to assist with debugging.</param>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"ArgumentOutOfRangeException\"></exception>\n public static void CannotBeNullOrEmpty<T>(this ICollection<T> p_parameter, string p_name)\n {\n if (p_parameter == null)\n throw new ArgumentNullException(\"Collection cannot be null.\\r\\nParameter_Name: \" + p_name, default(Exception));\n\n if (p_parameter.Count <= 0)\n throw new ArgumentOutOfRangeException(\"Collection cannot be empty.\\r\\nParameter_Name: \" + p_name, default(Exception));\n }\n\n /// <summary>\n /// Validates the passed in parameter is not null or empty, throwing a detailed exception message if the test fails.\n /// </summary>\n /// <param name=\"p_parameter\">Parameter to validate.</param>\n /// <param name=\"p_name\">Name of tested parameter to assist with debugging.</param>\n /// <exception cref=\"ArgumentException\"></exception>\n public static void CannotBeNullOrEmpty(this string p_parameter, string p_name)\n {\n if (string.IsNullOrEmpty(p_parameter))\n throw new ArgumentException(\"String cannot be null or empty.\\r\\nParameter_Name: \" + p_name, default(Exception));\n }\n }\n}\n Exception using System;\nusing System.Collections.Generic;\nusing Common.FluentValidation;\nusing NUnit.Framework;\n\nnamespace UnitTests.Common.Fluent_Validations\n{\n [TestFixture]\n public class IsAnyOf_Tests\n {\n [Test, ExpectedException(typeof(ArgumentNullException))]\n public void IsAnyOf_ArgumentNullException_ShouldNotMatch_ArgumentException_Test()\n {\n Action TestMethod = () => { throw new ArgumentNullException(); };\n\n try\n {\n TestMethod();\n }\n catch (Exception ex)\n {\n if (ex.GetType().IsAnyOf(\n typeof(ArgumentException), /*Note: ArgumentNullException derrived from ArgumentException*/\n typeof(FormatException),\n typeof(KeyNotFoundException)))\n {\n // Handle expected Exceptions\n return;\n }\n\n //else throw original\n throw;\n }\n }\n\n [Test, ExpectedException(typeof(OutOfMemoryException))]\n public void IsAnyOf_OutOfMemoryException_ShouldMatch_OutOfMemoryException_Test()\n {\n Action TestMethod = () => { throw new OutOfMemoryException(); };\n\n try\n {\n TestMethod();\n }\n catch (Exception ex)\n {\n if (ex.GetType().IsAnyOf(\n typeof(OutOfMemoryException),\n typeof(StackOverflowException)))\n throw;\n\n /*else... Handle other exception types, typically by logging to file*/\n }\n }\n }\n}\n"
},
{
"answer_id": 22864936,
"author": "Joe",
"author_id": 1324810,
"author_profile": "https://Stackoverflow.com/users/1324810",
"pm_score": 9,
"selected": false,
"text": "if try { … }\ncatch (Exception e) when (MyFilter(e))\n{\n …\n}\n MyFilter private bool MyFilter(Exception e)\n{\n return e is ArgumentNullException || e is FormatException;\n}\n try { … }\ncatch (Exception e) when (e is ArgumentNullException || e is FormatException)\n{\n …\n}\n if catch"
},
{
"answer_id": 26483624,
"author": "atlaste",
"author_id": 1031591,
"author_profile": "https://Stackoverflow.com/users/1031591",
"pm_score": 3,
"selected": false,
"text": "// Won't compile... damn\npublic static void Main()\n{\n try\n {\n throw new ArgumentOutOfRangeException();\n }\n catch (ArgumentOutOfRangeException)\n catch (IndexOutOfRangeException) \n {\n // ... handle\n }\n // Won't compile... damn\ntry\n{\n throw new ArgumentOutOfRangeException();\n}\ncatch (ArgumentOutOfRangeException e) {\n goto theOtherHandler;\n}\ncatch (IndexOutOfRangeException e) {\ntheOtherHandler:\n Console.WriteLine(\"Handle!\");\n}\n Exception ex;\n try\n {\n throw new ArgumentException(); // for demo purposes; won't be caught.\n goto noCatch;\n }\n catch (ArgumentOutOfRangeException e) {\n ex = e;\n }\n catch (IndexOutOfRangeException e) {\n ex = e;\n }\n\n Console.WriteLine(\"Handle the exception 'ex' here :-)\");\n // throw ex ?\n\nnoCatch:\n Console.WriteLine(\"We're done with the exception handling.\");\n Exception ex = null;\ntry\n{\n throw new ArgumentException();\n}\ncatch (ArgumentOutOfRangeException e)\n{\n ex = e;\n}\ncatch (IndexOutOfRangeException e)\n{\n ex = e;\n}\nif (ex != null)\n{\n Console.WriteLine(\"Handle the exception here :-)\");\n}\n private static bool Handle(Exception e)\n{\n Console.WriteLine(\"Handle the exception here :-)\");\n return true; // false will re-throw;\n}\n\npublic static void Main()\n{\n try\n {\n throw new OutOfMemoryException();\n }\n catch (ArgumentException e)\n {\n if (!Handle(e)) { throw; }\n }\n catch (IndexOutOfRangeException e)\n {\n if (!Handle(e)) { throw; }\n }\n\n Console.WriteLine(\"We're done with the exception handling.\");\n try\n{\n throw new ArgumentException();\n}\ncatch (Exception e)\n{\n Exception ex = (Exception)(e as ArgumentException) ?? (e as IndexOutOfRangeException);\n if (ex != null)\n {\n Console.WriteLine(\"Handle the exception here :-)\");\n // throw ?\n }\n else \n {\n throw;\n }\n}\n"
},
{
"answer_id": 27366344,
"author": "Stefan T",
"author_id": 2802543,
"author_profile": "https://Stackoverflow.com/users/2802543",
"pm_score": 4,
"selected": false,
"text": "catch(Exception ex)\n{ \n if (!(ex is SomeException || ex is OtherException)) throw;\n\n // Handle exception\n}\n catch(Exception ex) { if (!(ex is SomeException || ex is OtherException)) throw;\n\n // Handle exception\n}\n catch(Exception ex) when (ex is SomeException || ex is OtherException)\n{\n // Handle exception\n}\n"
},
{
"answer_id": 29390908,
"author": "Maniero",
"author_id": 221800,
"author_profile": "https://Stackoverflow.com/users/221800",
"pm_score": 7,
"selected": false,
"text": "catch (Exception ex) when (ex is FormatException || ex is OverflowException) {\n WebId = Guid.Empty;\n}\n catch (Exception ex) { \n if (ex is FormatException || ex is OverflowException) {\n WebId = Guid.Empty;\n }\n throw;\n}\n"
},
{
"answer_id": 30343421,
"author": "Kashif",
"author_id": 636740,
"author_profile": "https://Stackoverflow.com/users/636740",
"pm_score": -1,
"selected": false,
"text": "try\n{\n DoSomeHttpRequest();\n}\ncatch (System.Web.HttpException e)\n{\n switch (e.GetHttpCode())\n {\n case 400:\n WriteLine(\"Bad Request\");\n case 500:\n WriteLine(\"Internal Server Error\");\n default:\n WriteLine(\"Generic Error\");\n }\n}\n"
},
{
"answer_id": 32931248,
"author": "SHM",
"author_id": 2924454,
"author_profile": "https://Stackoverflow.com/users/2924454",
"pm_score": 4,
"selected": false,
"text": " try\n {\n throw new OverflowException();\n }\n catch(Exception e ) when ((e is DivideByZeroException) || (e is OverflowException))\n {\n // this will execute iff e is DividedByZeroEx or OverflowEx\n Console.WriteLine(\"E\");\n }\n"
},
{
"answer_id": 32998804,
"author": "Tamir Vered",
"author_id": 3256506,
"author_profile": "https://Stackoverflow.com/users/3256506",
"pm_score": 5,
"selected": false,
"text": "if catch C# 6.0 Exception Filters VB.NET MSIL try\n{\n WebId = new Guid(queryString[\"web\"]);\n}\ncatch (Exception exception) when (exception is FormatException || ex is OverflowException)\n{\n WebId = Guid.Empty;\n}\n Exception InvalidDataException ArgumentNullException when static int a = 8;\n\n...\n\ncatch (Exception exception) when (exception is InvalidDataException && a == 8)\n{\n Console.WriteLine(\"Catch\");\n}\n if catch Exception Filters Exceptions true catch static int a = 7;\n\nstatic int b = 0;\n\n...\n\ntry\n{\n throw new InvalidDataException();\n}\ncatch (Exception exception) when (exception is InvalidDataException && a / b == 2)\n{\n Console.WriteLine(\"Catch\");\n}\ncatch (Exception exception) when (exception is InvalidDataException || exception is ArgumentException)\n{\n Console.WriteLine(\"General catch\");\n}\n true Exception Filter static int a = 8;\n\nstatic int b = 4;\n\n...\n\ntry\n{\n throw new InvalidDataException();\n}\ncatch (Exception exception) when (exception is InvalidDataException && a / b == 2)\n{\n Console.WriteLine(\"Catch\");\n}\ncatch (Exception exception) when (exception is InvalidDataException || exception is ArgumentException)\n{\n Console.WriteLine(\"General catch\");\n}\n MSIL if Filters Exceptions Filter 1 Filter 2 Exception endfilter Catch 1 Catch 2 Guid Guid.TryParse"
},
{
"answer_id": 39638025,
"author": "MakePeaceGreatAgain",
"author_id": 2528063,
"author_profile": "https://Stackoverflow.com/users/2528063",
"pm_score": 3,
"selected": false,
"text": "MyClass instance;\ntry { instance = ... }\ncatch(Exception1 e) { Reset(instance); }\ncatch(Exception2 e) { Reset(instance); }\ncatch(Exception) { throw; }\n\nvoid Reset(MyClass instance) { /* reset the state of the instance */ }\n try { ... }\ncatch(Exception e) when(e is Exception1 || e is Exception2)\n{ \n Reset(instance); \n}\n"
},
{
"answer_id": 43439006,
"author": "Trevor",
"author_id": 4826364,
"author_profile": "https://Stackoverflow.com/users/4826364",
"pm_score": 3,
"selected": false,
"text": " try\n {\n // do some work here\n }\n catch (WebException ex)\n {\n // catch a web excpetion\n }\n catch (ArgumentException ex)\n {\n // do some stuff\n }\n catch (Exception ex)\n {\n // you should really surface your errors but this is for example only\n throw new Exception(\"An error occurred: \" + ex.Message);\n }\n"
},
{
"answer_id": 47316654,
"author": "Jeffrey Rennie",
"author_id": 4987709,
"author_profile": "https://Stackoverflow.com/users/4987709",
"pm_score": 3,
"selected": false,
"text": "try\n{\n WebId = Guid.Empty;\n Guid newGuid = new Guid(queryString[\"web\"]);\n // More initialization code goes here like \n // newGuid.x = y;\n WebId = newGuid;\n}\ncatch (FormatException) {}\ncatch (OverflowException) {}\n try\n{\n WebId = new Guid(queryString[\"web\"]);\n // More initialization code goes here.\n}\ncatch (FormatException) {\n Reset(WebId);\n}\ncatch (OverflowException) {\n Reset(WebId);\n}\n"
},
{
"answer_id": 48112962,
"author": "Fabian",
"author_id": 4226080,
"author_profile": "https://Stackoverflow.com/users/4226080",
"pm_score": 6,
"selected": false,
"text": "catch (Exception ex)\n{\n switch (ex)\n {\n case FormatException _:\n case OverflowException _:\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n}\n catch (Exception ex)\n{\n switch (ex)\n {\n case FormatException:\n case OverflowException:\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n} \n catch (Exception ex)\n{\n WebId = ex switch\n {\n _ when ex is FormatException || ex is OverflowException => Guid.Empty,\n _ => throw ex\n };\n}\n catch (Exception ex)\n{\n WebId = ex switch\n {\n _ when ex is FormatException || ex is OverflowException => Guid.Empty,\n _ => throw ex.Capture()\n };\n}\n\npublic static Exception Capture(this Exception ex)\n{\n ExceptionDispatchInfo.Capture(ex).Throw();\n return ex;\n}\n catch (Exception ex)\n{\n switch (ex)\n {\n case FormatException or OverflowException:\n WebId = Guid.Empty;\n break;\n default:\n throw;\n }\n} \n\ncatch (Exception ex)\n{\n WebId = ex switch\n {\n _ when ex is FormatException or OverflowException => Guid.Empty,\n _ => throw ex.Capture()\n };\n}\n"
},
{
"answer_id": 48403612,
"author": "Żubrówka",
"author_id": 861926,
"author_profile": "https://Stackoverflow.com/users/861926",
"pm_score": 2,
"selected": false,
"text": "try\n{\n // ...\n}\ncatch (FormatException)\n{\n DoSomething();\n}\ncatch (OverflowException)\n{\n DoSomething();\n}\n\n// ...\n\nprivate void DoSomething()\n{\n // ...\n}\n"
},
{
"answer_id": 51286385,
"author": "Mat J",
"author_id": 219933,
"author_profile": "https://Stackoverflow.com/users/219933",
"pm_score": 7,
"selected": false,
"text": "try\n{\n WebId = new Guid(queryString[\"web\"]);\n}\ncatch (Exception ex) when(ex is FormatException || ex is OverflowException)\n{\n WebId = Guid.Empty;\n}\n try\n{\n await Task.WaitAll(tasks);\n}\ncatch (Exception ex) when( ex is AggregateException ae &&\n ae.InnerExceptions.Count > tasks.Count/2)\n{\n //More than half of the tasks failed maybe..? \n}\n"
},
{
"answer_id": 53672256,
"author": "George",
"author_id": 5077953,
"author_profile": "https://Stackoverflow.com/users/5077953",
"pm_score": 1,
"selected": false,
"text": "try\n{\n //do something\n}\ncatch (Exception ex) when (ex.Message.Equals(\"the_error_message1_here\"))\n{\n//do whatever you like\n} \ncatch (Exception ex) when (ex.Message.Equals(\"the_error_message2_here\"))\n{\n//do whatever you like\n} \n"
},
{
"answer_id": 56327837,
"author": "Evgeny Gorbovoy",
"author_id": 2362847,
"author_profile": "https://Stackoverflow.com/users/2362847",
"pm_score": 0,
"selected": false,
"text": " Catch<FormatException, OverflowException>(() =>\n {\n WebId = new Guid(queryString[\"web\"]);\n },\n exception =>\n {\n WebId = Guid.Empty;\n });\n [DebuggerNonUserCode]\n public static void Catch<TException1, TException2>(Action tryBlock,\n Action<Exception> catchBlock)\n {\n CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));\n }\n\n [DebuggerNonUserCode]\n public static void Catch<TException1, TException2, TException3>(Action tryBlock,\n Action<Exception> catchBlock)\n {\n CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));\n }\n [DebuggerNonUserCode]\n public static void CatchMany(Action tryBlock, Action<Exception> catchBlock,\n params Type[] exceptionTypes)\n {\n try\n {\n tryBlock();\n }\n catch (Exception exception)\n {\n if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);\n else throw;\n }\n }\n"
},
{
"answer_id": 65602786,
"author": "Nechemia Hoffmann",
"author_id": 7711481,
"author_profile": "https://Stackoverflow.com/users/7711481",
"pm_score": 6,
"selected": false,
"text": "try\n{\n WebId = new Guid(queryString[\"web\"]);\n}\ncatch (Exception e) when (e is FormatException or OverflowException)\n{\n WebId = Guid.Empty;\n}\n"
},
{
"answer_id": 70051532,
"author": "Saleem Kalro",
"author_id": 4059234,
"author_profile": "https://Stackoverflow.com/users/4059234",
"pm_score": -1,
"selected": false,
"text": " try\n {\n WebId = new Guid(queryString[\"web\"]);\n }\n catch (Exception ex)\n {\n string ExpTyp = ex.GetType().Name;\n if (ExpTyp == \"FormatException\")\n {\n WebId = Guid.Empty;\n }\n else if (ExpTyp == \"OverflowException\")\n {\n WebId = Guid.Empty;\n }\n }\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
136,050
|
<p>Is there a way to prevent VS2008 creating browse info file files for C++ projects.<br>
I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed.</p>
<p>EDIT - it's also needed for go to declaration/definition</p>
|
[
{
"answer_id": 1910905,
"author": "Adisak",
"author_id": 14904,
"author_profile": "https://Stackoverflow.com/users/14904",
"pm_score": 3,
"selected": true,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\9.0\\Languages\\Language Services\\C/C++] \"IntellisenseOptions\"=dword:00000000\n \"IntellisenseOptions\"=dword:00000007\n \"IntellisenseOptions\"=dword:00000005\n ISENSE_NORMAL = 0 'normal (Intellisense On)\nISENSE_NOBG = &H1 'no bg parsing (Intellisense Updating Off - although NCB file will be opened r/w and repersisted at shutdown)\nISENSE_NOQUERY = &H2 'no queries (don't run any ISense queries)\nISENSE_NCBRO = &H4 'no saving of NCB (must be set before opening NCB, doesn't affect updating or queries, just persisting of NCB)\nISENSE_OFF = &H7 \n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10897/"
] |
136,052
|
<p>I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook. </p>
<p>I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?</p>
<p>Thanks</p>
|
[
{
"answer_id": 136061,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "\\r\\c \\n \\r\\n"
},
{
"answer_id": 136095,
"author": "Robert Wilkinson",
"author_id": 2184,
"author_profile": "https://Stackoverflow.com/users/2184",
"pm_score": 6,
"selected": true,
"text": "\\r\\n"
},
{
"answer_id": 136106,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "\\n"
},
{
"answer_id": 136189,
"author": "hova",
"author_id": 2170,
"author_profile": "https://Stackoverflow.com/users/2170",
"pm_score": 2,
"selected": false,
"text": "<br />"
},
{
"answer_id": 1825716,
"author": "Mohammad Rasool Javeed",
"author_id": 222057,
"author_profile": "https://Stackoverflow.com/users/222057",
"pm_score": -1,
"selected": false,
"text": "message.setContent(new String(body.getBytes(), \"iso-8859-1\"),\n \"text/html; charset=\\\"iso-8859-1\\\"\");\n"
},
{
"answer_id": 4439717,
"author": "Mark",
"author_id": 542005,
"author_profile": "https://Stackoverflow.com/users/542005",
"pm_score": 3,
"selected": false,
"text": "%0D%0A"
},
{
"answer_id": 5026795,
"author": "stephg",
"author_id": 621027,
"author_profile": "https://Stackoverflow.com/users/621027",
"pm_score": 5,
"selected": false,
"text": "This is my heading in the mail\\t\\n\nJust here Outlook is forced to begin a new line.\n"
},
{
"answer_id": 10382822,
"author": "Mohamed Selim",
"author_id": 1365684,
"author_profile": "https://Stackoverflow.com/users/1365684",
"pm_score": -1,
"selected": false,
"text": "Dim S As String\n S = \"Some Text\" & Chr(13)\n S = S + \"Some Text\" & Chr(13)\n"
},
{
"answer_id": 15893103,
"author": "Jackie",
"author_id": 410289,
"author_profile": "https://Stackoverflow.com/users/410289",
"pm_score": -1,
"selected": false,
"text": "< p/>"
},
{
"answer_id": 18452219,
"author": "thiru",
"author_id": 2719339,
"author_profile": "https://Stackoverflow.com/users/2719339",
"pm_score": 0,
"selected": false,
"text": "StringBuffer"
},
{
"answer_id": 18945306,
"author": "DreamZeppelin",
"author_id": 2804478,
"author_profile": "https://Stackoverflow.com/users/2804478",
"pm_score": 1,
"selected": false,
"text": "MimeBodyPart messageBodyPart = new MimeBodyPart();\nmessageBodyPart.setContent(message, \"text/plain\");\n"
},
{
"answer_id": 18986330,
"author": "Christian Casutt",
"author_id": 270085,
"author_profile": "https://Stackoverflow.com/users/270085",
"pm_score": 0,
"selected": false,
"text": "<pre> pre {\n font-family: Verdana, Geneva, sans-serif;\n}\n <td width=\"70%\"><pre>Entry Date/Time: 2013-09-19 17:06:25\nEntered By: Chris\n\nworklog mania\n\n____________________________________________________________________________________________________\n\nEntry Date/Time: 2013-09-19 17:05:42\nEntered By: Chris\n\nthis is a new Worklog Entry</pre></td>\n"
},
{
"answer_id": 19607068,
"author": "Lingfa",
"author_id": 2923002,
"author_profile": "https://Stackoverflow.com/users/2923002",
"pm_score": 0,
"selected": false,
"text": "<a href="mailto:someone@gmail.com?Subject=TEST&amp;body=Hi there,%0A%0AHow are you?%0A%0AThanks">email to me</a>\n"
},
{
"answer_id": 26063084,
"author": "AlCoPaine",
"author_id": 4083896,
"author_profile": "https://Stackoverflow.com/users/4083896",
"pm_score": 2,
"selected": false,
"text": "encodeURIComponent() var formattedBody = \"FirstLine \\n Second Line \\n Third Line\";\nvar mailToLink = \"mailto:x@y.com?body=\" + encodeURIComponent(formattedBody);\n FirstLine\nSecondLine\nThirdLine\n"
},
{
"answer_id": 26914106,
"author": "Kumar",
"author_id": 2007533,
"author_profile": "https://Stackoverflow.com/users/2007533",
"pm_score": 0,
"selected": false,
"text": "\\f"
},
{
"answer_id": 33282222,
"author": "David",
"author_id": 3943411,
"author_profile": "https://Stackoverflow.com/users/3943411",
"pm_score": -1,
"selected": false,
"text": "<pre></pre> var email_body = htmlEncode($(\"#Body\").val());\n\n function htmlEncode(value) {\n return \"<pre>\" + $('<div/>').text(value).html() + \"</pre>\";\n}\n"
},
{
"answer_id": 41330648,
"author": "vik",
"author_id": 3329417,
"author_profile": "https://Stackoverflow.com/users/3329417",
"pm_score": 0,
"selected": false,
"text": "message.setBody(MessageBody.getMessageBodyFromText(msg));\nBodyType type = BodyType.Text;\nmessage.getBody().setBodyType(type);\n"
},
{
"answer_id": 62329394,
"author": "Sri",
"author_id": 9435958,
"author_profile": "https://Stackoverflow.com/users/9435958",
"pm_score": 0,
"selected": false,
"text": "\\t\\n - for new line in Email service JavaMailSender\n\nString mailMessage = JSONObject.toJSONString(\"Your message\").replace(\",\", \"\\t\\n\").trim();\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098/"
] |
136,067
|
<p>I am working on a web app that uses Perl and I need to look into speeding up portions of the app. </p>
<p>I thought I'd start profiling the particular calls for the portion I wish to investigate. I've done some searching on profiling Perl code, but unfortunately most of what I find says that I should run my perl code with <code>-d:DProf myapp</code> from the command line. That doesn't quite work for me since my code is within a web app. I did find a way to get the profiling to work with apache, but unfortunately, the "most used" modules that came back from the profiler were all CPAN modules -- Class::xyz, etc etc etc. Not terribly helpful.</p>
<p>Does anyone know of a good way besides me injecting "timer" code into the methods I wish to profile to target just these methods? I've thought of writing a test script and profiling that but due to the nature of the code I'm working on that would require a bit more work than I'm hoping to have to do. </p>
|
[
{
"answer_id": 136402,
"author": "Sam Kington",
"author_id": 6832,
"author_profile": "https://Stackoverflow.com/users/6832",
"pm_score": 3,
"selected": false,
"text": "\nhttp://example.com/scripts/example.pl?action=browse&search=grommet&restrict=blah\n \nperl -d:NYTProf documentroot/scripts/example.pl 'action=browse&search=grommet&restrict=blah'\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22390/"
] |
136,097
|
<p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod" rel="noreferrer"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod" rel="noreferrer"><code>@classmethod</code></a>?</p>
|
[
{
"answer_id": 136138,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 10,
"selected": false,
"text": "dict.fromkeys() >>> class DictSubclass(dict):\n... def __repr__(self):\n... return \"DictSubclass\"\n... \n>>> dict.fromkeys(\"abc\")\n{'a': None, 'c': None, 'b': None}\n>>> DictSubclass.fromkeys(\"abc\")\nDictSubclass\n>>> \n"
},
{
"answer_id": 136149,
"author": "Terence Simpson",
"author_id": 22395,
"author_profile": "https://Stackoverflow.com/users/22395",
"pm_score": 8,
"selected": false,
"text": "@classmethod @staticmethod"
},
{
"answer_id": 136246,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 5,
"selected": false,
"text": "@staticmethod >>> class C(object):\n... pass\n... \n>>> def f():\n... pass\n... \n>>> staticmethod(f).__get__(None, C)\n<function f at 0x5c1cf0>\n>>> classmethod(f).__get__(None, C)\n<bound method type.f of <class '__main__.C'>>\n classmethod >>> class CMeta(type):\n... def foo(cls):\n... print cls\n... \n>>> class C(object):\n... __metaclass__ = CMeta\n... \n>>> C.foo()\n<class '__main__.C'>\n"
},
{
"answer_id": 1669524,
"author": "unutbu",
"author_id": 190597,
"author_profile": "https://Stackoverflow.com/users/190597",
"pm_score": 13,
"selected": true,
"text": "foo class_foo static_foo class A(object):\n def foo(self, x):\n print(f\"executing foo({self}, {x})\")\n\n @classmethod\n def class_foo(cls, x):\n print(f\"executing class_foo({cls}, {x})\")\n\n @staticmethod\n def static_foo(x):\n print(f\"executing static_foo({x})\")\n\na = A()\n a a.foo(1)\n# executing foo(<__main__.A object at 0xb7dbef0c>, 1)\n self a.class_foo(1)\n# executing class_foo(<class '__main__.A'>, 1)\n class_foo A.foo(1) A.class_foo(1) A.class_foo(1)\n# executing class_foo(<class '__main__.A'>, 1)\n self cls a.static_foo(1)\n# executing static_foo(1)\n\nA.static_foo('hi')\n# executing static_foo(hi)\n foo a.foo a foo a.foo a foo print(a.foo)\n# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>\n a.class_foo a class_foo A class_foo print(a.class_foo)\n# <bound method type.class_foo of <class '__main__.A'>>\n a.static_foo static_foo a.static_foo print(a.static_foo)\n# <function static_foo at 0xb7d479cc>\n static_foo A print(A.static_foo)\n# <function static_foo at 0xb7d479cc>\n"
},
{
"answer_id": 1669579,
"author": "Chris B.",
"author_id": 45176,
"author_profile": "https://Stackoverflow.com/users/45176",
"pm_score": 7,
"selected": false,
"text": "class C:\n @classmethod\n def f(cls, arg1, arg2, ...): ... \n @classmethod C.f() C().f() staticmethod() class C:\n @staticmethod\n def f(arg1, arg2, ...): ... \n @staticmethod C.f() C().f() classmethod()"
},
{
"answer_id": 9428384,
"author": "Jens Timmerman",
"author_id": 869482,
"author_profile": "https://Stackoverflow.com/users/869482",
"pm_score": 5,
"selected": false,
"text": "class Cluster(object):\n\n def _is_cluster_for(cls, name):\n \"\"\"\n see if this class is the cluster with this name\n this is a classmethod\n \"\"\" \n return cls.__name__ == name\n _is_cluster_for = classmethod(_is_cluster_for)\n\n #static method\n def getCluster(name):\n \"\"\"\n static factory method, should be in Cluster class\n returns a cluster object for the given name\n \"\"\"\n for cls in Cluster.__subclasses__():\n if cls._is_cluster_for(name):\n return cls()\n getCluster = staticmethod(getCluster)\n _is_cluster_for"
},
{
"answer_id": 13920259,
"author": "Cathal Garvey",
"author_id": 1910875,
"author_profile": "https://Stackoverflow.com/users/1910875",
"pm_score": -1,
"selected": false,
"text": "@staticmethod staticmethod() @staticmethod"
},
{
"answer_id": 28117800,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 6,
"selected": false,
"text": "class Foo(object):\n\n def a_normal_instance_method(self, arg_1, kwarg_2=None):\n '''\n Return a value that is a function of the instance with its\n attributes, and other arguments such as arg_1 and kwarg2\n '''\n\n @staticmethod\n def a_static_method(arg_0):\n '''\n Return a value that is a function of arg_0. It does not know the \n instance or class it is called from.\n '''\n\n @classmethod\n def a_class_method(cls, arg1):\n '''\n Return a value that is a function of the class and other arguments.\n respects subclassing, it is called with the class it is called from.\n '''\n a_normal_instance_method ', '\n join ['a', 'b', 'c'] >>> ', '.join(['a', 'b', 'c'])\n'a, b, c'\n str.join ':' >>> join_with_colons = ':'.join \n >>> join_with_colons('abcde')\n'a:b:c:d:e'\n>>> join_with_colons(['FF', 'FF', 'FF', 'FF', 'FF', 'FF'])\n'FF:FF:FF:FF:FF:FF'\n str.maketrans string str.translate string str.maketrans # demonstrate same function whether called from instance or not:\n>>> ', '.maketrans('ABC', 'abc')\n{65: 97, 66: 98, 67: 99}\n>>> str.maketrans('ABC', 'abc')\n{65: 97, 66: 98, 67: 99}\n >>> import string\n>>> 'ABCDEFG'.translate(string.maketrans('ABC', 'abc'))\n'abcDEFG'\n dict.fromkeys >>> dict.fromkeys(['a', 'b', 'c'])\n{'c': None, 'b': None, 'a': None}\n >>> class MyDict(dict): 'A dict subclass, use to demo classmethods'\n>>> md = MyDict.fromkeys(['a', 'b', 'c'])\n>>> md\n{'a': None, 'c': None, 'b': None}\n>>> type(md)\n<class '__main__.MyDict'>\n classmethod staticmethod"
},
{
"answer_id": 30329887,
"author": "Nathan Tregillus",
"author_id": 51847,
"author_profile": "https://Stackoverflow.com/users/51847",
"pm_score": 6,
"selected": false,
"text": "@classmethod @staticmethod @classmethod @staticmethod"
},
{
"answer_id": 33727452,
"author": "zangw",
"author_id": 3011380,
"author_profile": "https://Stackoverflow.com/users/3011380",
"pm_score": 5,
"selected": false,
"text": "@staticmethod @classmethod @classmethod"
},
{
"answer_id": 36798076,
"author": "Du D.",
"author_id": 1302259,
"author_profile": "https://Stackoverflow.com/users/1302259",
"pm_score": 7,
"selected": false,
"text": "class Apple:\n\n _counter = 0\n\n @staticmethod\n def about_apple():\n print('Apple is good for you.')\n\n # note you can still access other member of the class\n # but you have to use the class instance \n # which is not very nice, because you have repeat yourself\n # \n # For example:\n # @staticmethod\n # print('Number of apples have been juiced: %s' % Apple._counter)\n #\n # @classmethod\n # print('Number of apples have been juiced: %s' % cls._counter)\n #\n # @classmethod is especially useful when you move your function to another class,\n # you don't have to rename the referenced class \n\n @classmethod\n def make_apple_juice(cls, number_of_apples):\n print('Making juice:')\n for i in range(number_of_apples):\n cls._juice_this(i)\n\n @classmethod\n def _juice_this(cls, apple):\n print('Juicing apple %d...' % apple)\n cls._counter += 1\n"
},
{
"answer_id": 39589894,
"author": "Rizwan Mumtaz",
"author_id": 1224003,
"author_profile": "https://Stackoverflow.com/users/1224003",
"pm_score": 4,
"selected": false,
"text": "class A(object):\n x = 0\n\n def say_hi(self):\n pass\n\n @staticmethod\n def say_hi_static():\n pass\n\n @classmethod\n def say_hi_class(cls):\n pass\n\n def run_self(self):\n self.x += 1\n print self.x # outputs 1\n self.say_hi()\n self.say_hi_static()\n self.say_hi_class()\n\n @staticmethod\n def run_static():\n print A.x # outputs 0\n # A.say_hi() # wrong\n A.say_hi_static()\n A.say_hi_class()\n\n @classmethod\n def run_class(cls):\n print cls.x # outputs 0\n # cls.say_hi() # wrong\n cls.say_hi_static()\n cls.say_hi_class()\n # A.run_self() # wrong\nA.run_static()\nA.run_class()\n"
},
{
"answer_id": 39776104,
"author": "Adam Parkin",
"author_id": 808804,
"author_profile": "https://Stackoverflow.com/users/808804",
"pm_score": 5,
"selected": false,
"text": "class Foo(object):\n @staticmethod\n def bar():\n return \"In Foo\"\n bar() class Foo2(Foo):\n @staticmethod\n def bar():\n return \"In Foo2\"\n bar() Foo2 Foo2 magic() Foo2 bar() class Foo2(Foo):\n @staticmethod\n def bar():\n return \"In Foo2\"\n @staticmethod\n def magic():\n return \"Something useful you'd like to use in bar, but now can't\" \n Foo2.magic() bar() Foo2 bar() Foo bar() classmethod class Foo(object):\n @classmethod\n def bar(cls):\n return \"In Foo\"\n\nclass Foo2(Foo):\n @classmethod\n def bar(cls):\n return \"In Foo2 \" + cls.magic()\n @classmethod\n def magic(cls):\n return \"MAGIC\"\n\nprint Foo2().bar()\n In Foo2 MAGIC staticmethod"
},
{
"answer_id": 39829692,
"author": "Laxmi",
"author_id": 6755093,
"author_profile": "https://Stackoverflow.com/users/6755093",
"pm_score": 5,
"selected": false,
"text": "@staticmethod\ndef some_static_method(*args, **kwds):\n pass\n @classmethod\n def some_class_method(cls, *args, **kwds):\n pass\n"
},
{
"answer_id": 46664125,
"author": "Gaurang Shah",
"author_id": 2504762,
"author_profile": "https://Stackoverflow.com/users/2504762",
"pm_score": 6,
"selected": false,
"text": "classmethod Person first_name last_name Person class Person(object):\n\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n first_name class Person(object):\n\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n def __init__(self, first_name):\n self.first_name = first_name\n @classmethod class Person(object):\n\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n @classmethod\n def get_person(cls, first_name):\n return cls(first_name, \"\")\n first_name @staticmethod \ndef validate_name(name):\n return len(name) <= 20\n class name Person.validate_name(\"Gaurang Shah\")\n"
},
{
"answer_id": 47591541,
"author": "Tushar Vazirani",
"author_id": 2695804,
"author_profile": "https://Stackoverflow.com/users/2695804",
"pm_score": 3,
"selected": false,
"text": "class A(object):\n m=54\n\n @classmethod\n def class_method(cls):\n print \"m is %d\" % cls.m\n class X(object):\n m=54 #will not be referenced\n\n @staticmethod\n def static_method():\n print \"Referencing/calling a variable or function outside this class. E.g. Some global variable/function.\"\n"
},
{
"answer_id": 48250384,
"author": "Selva",
"author_id": 2604954,
"author_profile": "https://Stackoverflow.com/users/2604954",
"pm_score": 5,
"selected": false,
"text": ">>> class Klaus:\n @classmethod\n def classmthd(*args):\n return args\n\n @staticmethod\n def staticmthd(*args):\n return args\n\n# 1. Call classmethod without any arg\n>>> Klaus.classmthd() \n(__main__.Klaus,) # the class gets passed as the first argument\n\n# 2. Call classmethod with 1 arg\n>>> Klaus.classmthd('chumma')\n(__main__.Klaus, 'chumma')\n\n# 3. Call staticmethod without any arg\n>>> Klaus.staticmthd() \n()\n\n# 4. Call staticmethod with 1 arg\n>>> Klaus.staticmthd('chumma')\n('chumma',)\n"
},
{
"answer_id": 51015649,
"author": "Michael Swartz",
"author_id": 1476365,
"author_profile": "https://Stackoverflow.com/users/1476365",
"pm_score": 3,
"selected": false,
"text": "@classmethod @staticmethod @staticmethod @staticmethod #!python3\n\nfrom os import system\nsystem('cls')\n# % % % % % % % % % % % % % % % % % % % %\n\nclass DemoClass(object):\n # instance methods need a class instance and\n # can access the instance through 'self'\n def instance_method_1(self):\n return 'called from inside the instance_method_1()'\n\n def instance_method_2(self):\n # an instance outside the class indirectly calls the static_method\n return self.static_method() + ' via instance_method_2()'\n\n # class methods don't need a class instance, they can't access the\n # instance (self) but they have access to the class itself via 'cls'\n @classmethod\n def class_method(cls):\n return 'called from inside the class_method()'\n\n # static methods don't have access to 'cls' or 'self', they work like\n # regular functions but belong to the class' namespace\n @staticmethod\n def static_method():\n return 'called from inside the static_method()'\n# % % % % % % % % % % % % % % % % % % % %\n\n# works even if the class hasn't been instantiated\nprint(DemoClass.class_method() + '\\n')\n''' called from inside the class_method() '''\n\n# works even if the class hasn't been instantiated\nprint(DemoClass.static_method() + '\\n')\n''' called from inside the static_method() '''\n# % % % % % % % % % % % % % % % % % % % %\n\n# >>>>> all methods types can be called on a class instance <<<<<\n# instantiate the class\ndemoclassObj = DemoClass()\n\n# call instance_method_1()\nprint(democlassObj.instance_method_1() + '\\n')\n''' called from inside the instance_method_1() '''\n\n# # indirectly call static_method through instance_method_2(), there's really no use\n# for this since a @staticmethod can be called whether the class has been\n# instantiated or not\nprint(democlassObj.instance_method_2() + '\\n')\n''' called from inside the static_method() via instance_method_2() '''\n\n# call class_method()\nprint(democlassObj.class_method() + '\\n')\n''' called from inside the class_method() '''\n\n# call static_method()\nprint(democlassObj.static_method())\n''' called from inside the static_method() '''\n\n\"\"\"\n# whether the class is instantiated or not, this doesn't work\nprint(DemoClass.instance_method_1() + '\\n')\n'''\nTypeError: TypeError: unbound method instancemethod() must be called with\nDemoClass instance as first argument (got nothing instead)\n'''\n\"\"\"\n"
},
{
"answer_id": 54347204,
"author": "David Schumann",
"author_id": 1175081,
"author_profile": "https://Stackoverflow.com/users/1175081",
"pm_score": 3,
"selected": false,
"text": "class A:\n def foo(): # no self parameter, no decorator\n pass\n class B:\n @staticmethod\n def foo(): # no self parameter\n pass\n >>> A.foo()\nTypeError\n>>> A().foo()\nTypeError\n>>> B.foo()\n>>> B().foo()\n >>> A.foo()\n>>> A().foo()\nTypeError\n>>> B.foo()\n>>> B().foo()\n @staticmethod @staticmethod"
},
{
"answer_id": 56236639,
"author": "blue_note",
"author_id": 3208297,
"author_profile": "https://Stackoverflow.com/users/3208297",
"pm_score": 6,
"selected": false,
"text": "self def f(self, x, y)\n self this self @classmethod\ndef f(cls, x, y)\n self self @staticmethod\ndef f(x, y)\n classmethod staticmethod Math class Point\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n @classmethod\n def frompolar(cls, radius, angle):\n \"\"\"The `cls` argument is the `Point` class itself\"\"\"\n return cls(radius * cos(angle), radius * sin(angle))\n\n @staticmethod\n def angle(x, y):\n \"\"\"this could be outside the class, but we put it here \njust because we think it is logically related to the class.\"\"\"\n return atan(y, x)\n\n\np1 = Point(3, 2)\np2 = Point.frompolar(3, pi/4)\n\nangle = Point.angle(3, 2)\n\n"
},
{
"answer_id": 58951325,
"author": "Jacky1205",
"author_id": 3291269,
"author_profile": "https://Stackoverflow.com/users/3291269",
"pm_score": 3,
"selected": false,
"text": "staticmethod classmethod class StaticMethod(object):\n \"Emulate PyStaticMethod_Type() in Objects/funcobject.c\"\n\n def __init__(self, f):\n self.f = f\n\n def __get__(self, obj, objtype=None):\n return self.f\n\n\nclass ClassMethod(object):\n \"Emulate PyClassMethod_Type() in Objects/funcobject.c\"\n def __init__(self, f):\n self.f = f\n\n def __get__(self, obj, cls=None):\n def inner(*args, **kwargs):\n if cls is None:\n cls = type(obj)\n return self.f(cls, *args, **kwargs)\n return inner\n"
},
{
"answer_id": 60492563,
"author": "mirek",
"author_id": 2520298,
"author_profile": "https://Stackoverflow.com/users/2520298",
"pm_score": 0,
"selected": false,
"text": "self.<attribute(s)> self.__class__.<attribute(s)> b=2 b=4 .b==2 cls.b .b==4 self.b .b==2 self.__class__.b self.attribute(s)"
},
{
"answer_id": 63197044,
"author": "Ale",
"author_id": 1593459,
"author_profile": "https://Stackoverflow.com/users/1593459",
"pm_score": 2,
"selected": false,
"text": "class A: \n def foo(self, x): \n print(\"executing foo(%s, %s)\" % (self, x)) \n \n @classmethod\n def class_foo(cls, x): \n print(\"executing class_foo(%s, %s)\" % (cls, x))\n \n @staticmethod \n def static_foo(x): \n print(\"executing static_foo(%s)\" % x)\n\nclass B(A):\n pass\n class_foo A.class_foo(1)\n# => executing class_foo(<class '__main__.A'>, 1)\nB.class_foo(1)\n# => executing class_foo(<class '__main__.B'>, 1)\n static_foo A B A.static_foo(1)\n# => executing static_foo(1)\nB.static_foo(1)\n# => executing static_foo(1)\n staticmethod class A:\n @classmethod\n def class_qux(cls, x):\n print(f\"executing class_qux({cls}, {x})\")\n \n @classmethod\n def class_bar(cls, x):\n cls.class_qux(x)\n\n @staticmethod\n def static_bar(x):\n A.class_qux(x)\n\nclass B(A):\n pass\n\nA.class_bar(1)\n# => executing class_qux(<class '__main__.A'>, 1)\nB.class_bar(1)\n# => executing class_qux(<class '__main__.B'>, 1)\nA.static_bar(1)\n# => executing class_qux(<class '__main__.A'>, 1)\nB.static_bar(1)\n# => executing class_qux(<class '__main__.A'>, 1)\n"
},
{
"answer_id": 64732009,
"author": "Milovan Tomašević",
"author_id": 13155046,
"author_profile": "https://Stackoverflow.com/users/13155046",
"pm_score": 3,
"selected": false,
"text": "+ + - + - - class MyClass:\n ''' \n Instance method has a mandatory first attribute self which represent the instance itself. \n Instance method must be called by a instantiated instance.\n '''\n def method(self):\n return 'instance method called', self\n \n '''\n Class method has a mandatory first attribute cls which represent the class itself. \n Class method can be called by an instance or by the class directly. \n Its most common using scenario is to define a factory method.\n '''\n @classmethod\n def class_method(cls):\n return 'class method called', cls\n \n '''\n Static method doesn’t have any attributes of instances or the class. \n It also can be called by an instance or by the class directly. \n Its most common using scenario is to define some helper or utility functions which are closely relative to the class.\n '''\n @staticmethod\n def static_method():\n return 'static method called'\n\n\nobj = MyClass()\nprint(obj.method())\nprint(obj.class_method()) # MyClass.class_method()\nprint(obj.static_method()) # MyClass.static_method()\n ('instance method called', <__main__.MyClass object at 0x100fb3940>)\n('class method called', <class '__main__.MyClass'>)\nstatic method called\n class Student:\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n @classmethod\n def get_from_string(cls, name_string: str):\n first_name, last_name = name_string.split()\n if Student.validate_name(first_name) and Student.validate_name(last_name):\n return cls(first_name, last_name)\n else:\n print('Invalid Names')\n\n @staticmethod\n def validate_name(name):\n return len(name) <= 10\n\n\nstackoverflow_student = Student.get_from_string('Name Surname')\nprint(stackoverflow_student.first_name) # Name\nprint(stackoverflow_student.last_name) # Surname\n"
},
{
"answer_id": 65754079,
"author": "illuminato",
"author_id": 2975438,
"author_profile": "https://Stackoverflow.com/users/2975438",
"pm_score": 4,
"selected": false,
"text": "@classmethod\n@staticmethod\n@property\n self class DecoratorTest(object):\n\n def __init__(self):\n pass\n\n def doubler(self, x):\n return x*2\n\n @classmethod\n def class_doubler(cls, x): # we need to use 'cls' instead of 'self'; 'cls' reference to the class instead of an instance of the class\n return x*2\n\n @staticmethod\n def static_doubler(x): # no need adding 'self' here; static_doubler() could be just a function not inside the class\n return x*2\n decor = DecoratorTest()\n\nprint(decor.doubler(5))\n# 10\n\nprint(decor.class_doubler(5)) # a call with an instance of a class\n# 10\nprint(DecoratorTest.class_doubler(5)) # a direct call by the class itself\n# 10\n\n# staticmethod could be called in the same way as classmethod.\nprint(decor.static_doubler(5)) # as an instance of the class\n# 10\nprint(DecoratorTest.static_doubler(5)) # or as a direct call \n# 10\n @property"
},
{
"answer_id": 66020869,
"author": "Sia",
"author_id": 2821756,
"author_profile": "https://Stackoverflow.com/users/2821756",
"pm_score": 2,
"selected": false,
"text": "staticmethod classmethod staticmethod"
},
{
"answer_id": 66049235,
"author": "Giorgos Myrianthous",
"author_id": 7131757,
"author_profile": "https://Stackoverflow.com/users/7131757",
"pm_score": 2,
"selected": false,
"text": "class Employee:\n\n NO_OF_EMPLOYEES = 0\n \n def __init__(self, first_name, last_name, salary):\n self.first_name = first_name\n self.last_name = last_name\n self.salary = salary\n self.increment_employees()\n\n def give_raise(self, amount):\n self.salary += amount\n\n @classmethod\n def employee_from_full_name(cls, full_name, salary):\n split_name = full_name.split(' ')\n first_name = split_name[0]\n last_name = split_name[1]\n return cls(first_name, last_name, salary)\n\n @classmethod\n def increment_employees(cls):\n cls.NO_OF_EMPLOYEES += 1\n\n @staticmethod\n def get_employee_legal_obligations_txt():\n legal_obligations = \"\"\"\n 1. An employee must complete 8 hours per working day\n 2. ...\n \"\"\"\n return legal_obligations\n Employee first_name last_name salary employee_1 = Employee('Andrew', 'Brown', 85000)\nprint(employee_1.first_name)\nprint(employee_1.salary)\n\n'Andrew'\n85000\n employee_from_full_name employee_2 = Employee.employee_from_full_name('John Black', 95000)\nprint(employee_2.first_name)\nprint(employee_2.salary)\n\n'John'\n95000\n employee_from_full_name employee_1 = Employee('Andrew', 'Brown', 85000)\nemployee_2 = employee_1.employee_from_full_name('John Black', 95000)\n NO_OF_EMPLOYEES employee_1 = Employee('Andrew', 'Brown', 85000)\nprint(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')\nemployee_2 = Employee.employee_from_full_name('John Black', 95000)\nprint(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')\n\nNumber of employees: 1\nNumber of employees: 2\n self cls get_employee_legal_obligations_txt print(Employee.get_employee_legal_obligations_txt())\n\n\n 1. An employee must complete 8 hours per working day\n 2. ...\n employee_1 = Employee('Andrew', 'Brown', 85000)\nprint(employee_1.get_employee_legal_obligations_txt())\n\n\n 1. An employee must complete 8 hours per working day\n 2. ...\n"
},
{
"answer_id": 66672138,
"author": "H.H",
"author_id": 9312573,
"author_profile": "https://Stackoverflow.com/users/9312573",
"pm_score": 4,
"selected": false,
"text": "class Parent:\n _class_name = \"Parent\"\n\n @staticmethod\n def print_name():\n print(Parent._class_name)\n\n\nclass Child(Parent):\n _class_name = \"Child\"\n\n @staticmethod\n def print_name():\n print(Child._class_name)\n\n\nParent.print_name()\nChild.print_name()\n class Parent:\n _class_name = \"Parent\"\n\n @classmethod\n def print_name(cls):\n print(cls._class_name)\n\n\nclass Child(Parent):\n _class_name = \"Child\"\n\n\nParent.print_name()\nChild.print_name()\n"
},
{
"answer_id": 68459641,
"author": "Arpan Saini",
"author_id": 7353562,
"author_profile": "https://Stackoverflow.com/users/7353562",
"pm_score": 0,
"selected": false,
"text": "Convert a function to be a static method.\n\nA static method does not receive an implicit first argument.\nTo declare a static method, use this idiom:\n\n class C:\n @staticmethod\n def f(arg1, arg2, ...):\n ...\n\nIt can be called either on the class (e.g. C.f()) or on an instance\n(e.g. C().f()). The instance is ignored except for its class.\n\nStatic methods in Python are similar to those found in Java or C++.\nFor a more advanced concept, see the classmethod builtin.\n\"\"\"\n Convert a function to be a class method.\n\nA class method receives the class as implicit first argument,\njust like an instance method receives the instance.\nTo declare a class method, use this idiom:\n\n class C:\n @classmethod\n def f(cls, arg1, arg2, ...):\n ...\n\nIt can be called either on the class (e.g. C.f()) or on an instance\n(e.g. C().f()). The instance is ignored except for its class.\nIf a class method is called for a derived class, the derived class\nobject is passed as the implied first argument.\n\nClass methods are different than C++ or Java static methods.\nIf you want those, see the staticmethod builtin.\n"
},
{
"answer_id": 73852182,
"author": "David Mendes",
"author_id": 4433157,
"author_profile": "https://Stackoverflow.com/users/4433157",
"pm_score": 0,
"selected": false,
"text": "class Foo:\n @classmethod\n def bar(cls, id: int = None):\n query = session.query(\n a.id,\n a.name,\n a.address,\n )\n\n if id is not None:\n query = query.filter(a.id == id)\n\n return query\n"
},
{
"answer_id": 74470227,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "@classmethod cls cls @classmethod cls cls @staticmethod self cls @classmethod @classmethod cls @classmethod class Person:\n x = \"Hello\"\n def __init__(self, name):\n self.name = name\n \n @classmethod # Here\n def test1(cls):\n print(cls.x) # Class variable by `cls`\n cls.test2(cls) # Instance method by `cls`\n cls.test3() # Class method by `cls`\n cls.test4() # Static method by `cls`\n print()\n print(Person.x) # Class variable by class name\n Person.test2(\"Test2\") # Instance method by class name\n Person.test3() # Class method by class name\n Person.test4() # Static method by class name\n \n def test2(self):\n print(\"Test2\")\n \n @classmethod\n def test3(cls):\n print(\"Test3\")\n \n @staticmethod\n def test4():\n print(\"Test4\")\n\nobj = Person(\"John\")\nobj.test1() # By object\n\n# Or\n\nPerson.test1() # By class name\n Hello\nTest2\nTest3\nTest4\n\nHello\nTest2\nTest3\nTest4\n @classmethod cls @classmethod cls # ...\n \n @classmethod\n def test1(cls):\n print(cls.name) # Instance variable by `cls`\n \n # Or\n\n print(Person.name) # Instance variable by class name\n# ...\n\nobj = Person(\"John\")\nobj.test1()\n\n# Or\n\nPerson.test1()\n @classmethod cls # ...\n \n @classmethod\n def test1(): # Without \"cls\"\n print(\"Test1\")\n \n# ...\n\nobj = Person(\"John\")\nobj.test1()\n\n# Or\n\nPerson.test1()\n @classmethod cls cls # ...\n\n @classmethod\n def test1(orange):\n print(orange.x) # Class variable\n orange.test2(orange) # Instance method\n orange.test3() # Class method\n orange.test4() # Static method\n\n# ...\n\nobj = Person(\"John\")\nobj.test1()\n\n# Or\n\nPerson.test1()\n Hello\nTest2\nTest3\nTest4\n @staticmethod @staticmethod class Person:\n x = \"Hello\"\n def __init__(self, name):\n self.name = name\n\n @staticmethod # Here\n def test1():\n print(\"Test1\")\n \n def test2(self):\n print(\"Test2\")\n \n @classmethod\n def test3(cls):\n print(\"Test3\")\n \n @staticmethod\n def test4():\n print(\"Test4\")\n\nobj = Person(\"John\")\nobj.test1() # By object\n\n# Or\n\nPerson.test1() # By class name\n Test1\n @staticmethod # ...\n \n @staticmethod\n def test1():\n print(Person.x) # Class variable\n Person.test2(\"Test2\") # Instance method\n Person.test3() # Class method\n Person.test4() # Static method\n \n# ...\n\nobj = Person(\"John\")\nobj.test1()\n\n# Or\n\nPerson.test1()\n Hello\nTest2\nTest3\nTest4\n @staticmethod # ...\n \n @staticmethod\n def test1():\n print(Person.name) # Instance variable\n \n# ...\n\nobj = Person(\"John\")\nobj.test1()\n\n# Or\n\nPerson.test1()\n @staticmethod self cls @staticmethod self cls # ...\n \n @staticmethod\n def test1(self): # With \"self\"\n print(self)\n\n # Or\n\n @staticmethod\n def test1(cls): # With \"cls\"\n print(cls)\n\n# ...\n\nobj = Person(\"John\")\nobj.test1(\"Test1\") # With an argument\n\n# Or\n\nPerson.test1(\"Test1\") # With an argument\n Test1\n # ...\n \n @staticmethod\n def test1(self): # With \"self\"\n print(\"Test1\")\n\n # Or\n\n @staticmethod\n def test1(cls): # With \"cls\"\n print(\"Test1\")\n\n# ...\n\nobj = Person(\"John\")\nobj.test1() # Without an argument\n\n# Or\n\nPerson.test1() # Without an argument\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
136,098
|
<p>Browsing to a dynamic web page built using Grails version 1.0.3 the console log shows the following errors for each page request:</p>
<pre><code>[Fatal Error] :-1:-1: Premature end of file.
</code></pre>
<p>How do I stop this error from appearing for each request?</p>
|
[
{
"answer_id": 158386,
"author": "Josh",
"author_id": 16175,
"author_profile": "https://Stackoverflow.com/users/16175",
"pm_score": 3,
"selected": true,
"text": "grails.mime.types = [ html: ['text/html','application/xhtml+xml'],\nxml: ['text/xml', 'application/xml'], ...\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/136098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16175/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.